问:
ArrayBuffer of Strings - Min
I have the following code inside a scalatest Spec:

```<code>val arr = ArrayBuffer("Mary", "had", "a", "little", "lamb")
arr.max shouldEqual "little"
arr.min shouldEqual "a"
</code>```

Which fails on the second shouldEqual, saying:

"[Mary]" did not equal "[a]"

Why does this not return "a"?

According to Scala for the Impatient, 2nd ed.: "...the min and max methods yield the smallest and largest element in an array or array buffer."

Horstmann, Cay S.. Scala for the Impatient (Kindle Locations 1515-1517). Pearson Education. Kindle Edition.

Postface: When book says "...yields the smallest and largest..." it means ASCII comparison, not the length as in implemented in the chosen answer.

答:
On ascii table, upper case letters come before lower case letters, so Mary < a and is the smallest element, you can check this in the scala REPL:

```<code>scala> "Mary" < "a"
// res4: Boolean = true
</code>```

If you need to compare by the number of characters in the string, you can use minBy and maxBy to compare strings by their sizes:

```<code>import scala.collection.mutable.ArrayBuffer

val arr = ArrayBuffer("Mary", "had", "a", "little", "lamb")
// arr: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Mary, had, a, little, lamb)

arr.minBy(_.size)
// res5: String = a

arr.maxBy(_.size)
// res6: String = little
</code>```

Title: ArrayBuffer of Strings - Min

Body:
I have the following code inside a scalatest Spec:

val arr = ArrayBuffer("Mary", "had", "a", "little", "lamb")
arr.max shouldEqual "little"
arr.min shouldEqual "a"

Which fails on the second shouldEqual, saying:

"[Mary]" did not equal "[a]"

Why does this not return "a"?

According to Scala for the Impatient, 2nd ed.: "...the min and max methods yield the smallest and largest element in an array or array buffer."

Horstmann, Cay S.. Scala for the Impatient (Kindle Locations 1515-1517). Pearson Education. Kindle Edition.

Postface: When book says "...yields the smallest and largest..." it means ASCII comparison, not the length as in implemented in the chosen answer.

Body:
On ascii table, upper case letters come before lower case letters, so Mary < a and is the smallest element, you can check this in the scala REPL:

scala> "Mary" < "a"
// res4: Boolean = true

If you need to compare by the number of characters in the string, you can use minBy and maxBy to compare strings by their sizes:

import scala.collection.mutable.ArrayBuffer

val arr = ArrayBuffer("Mary", "had", "a", "little", "lamb")
// arr: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Mary, had, a, little, lamb)

arr.minBy(_.size)
// res5: String = a

arr.maxBy(_.size)
// res6: String = little


来源: stackexchange

问:
C# Class as one Value in Class // Mimic int behaviour
Is there a way to make my new Class mimic the behavior of an int or any Valuetype?

I want something, so these assignments are valid

```<code>MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!
</code>```

The MyClass looks roughly like this

```<code>public class MyClass {
    public int Value{get;set;}
    public int AnotherValue{get;set;}
    public T GetSomething<T>() {..}
}
</code>```

Every assignment of MyClass should return the Variable Value as Type int.

So far i found implicit operator int and implicit operator MyClass (int value). But this is not 'good enough'.

I want that MyClass realy behaves like an int. So var i = myClass lets i be an int.

Is this even possible?

答:
Is this even possible?

No.

You can convert and cast types to other types implicitly and explicitly, but to have one type supersede another type without any inheritance or interface implementation flies in the face of object-oriented programming principles.

The var keyword is a convenience that tries to guess the type of a value with as much precision as possible. Therefore it can't be forced to represent int when the type is MyClass.

You might consider something like this: var x = (int) myClass;

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to make my new Class mimic the behavior of an int or any Valuetype?

I want something, so these assignments are valid

MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!

The MyClass looks roughly like this

public class MyClass {
    public int Value{get;set;}
    public int AnotherValue{get;set;}
    public T GetSomething<T>() {..}
}

Every assignment of MyClass should return the Variable Value as Type int.

So far i found implicit operator int and implicit operator MyClass (int value). But this is not 'good enough'.

I want that MyClass realy behaves like an int. So var i = myClass lets i be an int.

Is this even possible?


问:
How can you predict/get the next ChangeSetId before checking in files using TFS SDK
I have a requirement to build a Custom TFS Policy using C# & the TFS 2010 SDK.  This policy would validate that a custom note (bug #) are populated in the TFS Checkin dialog and then update a Bug Tracking system upon successful validation of the bug #.

Once I have the bug # validated, I would then use the Bug Tracking systems SDK to update the bug # with the names of the source files & the ChangeSetID.

The problem i'm having is that it appears the TFS SDK does not provide the functionality to get me the next available ChangeSetID that will be used as part of the checkin.  There doesn't seem to be a way to get this information.  Direct DB Access is not an option (I was thinking about doing something along the lines of SELECT ChangeSetId.nextVal).

Can someone let me know if this is an option with the TFS SDK?  I am trying to update the bug tracking system at the time my Custom Policy runs so I don't have to create another process to update the bug tracking system after the fact.

I added a client event handler for the TFS Server (CommitCheckin event), and i was able to do what i wanted from there.  Is there any problems that I will run into if I do it client side by subscribing to this event?  CommitCheckin

答:
I doubt that this would be possible. Even if you could get the next id then there is no guarantee that someone else would not use it before you. </p>

<p>What if the check-in was done into a branch - you then use the checkin id of the branch and then once validated you merged the branch with the main line? </p>

Body:
I doubt that this would be possible. Even if you could get the next id then there is no guarantee that someone else would not use it before you.

What if the check-in was done into a branch - you then use the checkin id of the branch and then once validated you merged the branch with the main line?

ContentLicense: CC BY-SA 2.5


问:
How to set added item as active object?
I'm using the following to add text to my fabricjs canvas and I was wondering how I could have it be automatically selected when the onclick is triggered?

```<code>// Add text
function Addtext() {
   canvas.add(new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   }));
}
</code>```

```<code><button onclick="Addtext()">+ Text</button>
</code>```

答:
You can use canvas.setActiveObject(). Jsfiddle

```<code>var canvas  = new fabric.Canvas('c');

function Addtext() {
   var text = new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   });
   canvas.add(text);
   canvas.setActiveObject(text);
}
$('#add').click(Addtext);
</code>```

Title: How to set added item as active object?

Body:
I'm using the following to add text to my fabricjs canvas and I was wondering how I could have it be automatically selected when the onclick is triggered?

// Add text
function Addtext() {
   canvas.add(new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   }));
}

<button onclick="Addtext()">+ Text</button>

Body:
You can use canvas.setActiveObject(). Jsfiddle

var canvas  = new fabric.Canvas('c');

function Addtext() {
   var text = new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   });
   canvas.add(text);
   canvas.setActiveObject(text);
}
$('#add').click(Addtext);


问:
Import JSON to html (table) filtering results
I'm trying to import JSON data to a html table. I have different types of data. In my case I need only  to see the "link" data type in a table this is the JSON data I'm getting.

```<code>  {   "data": [
  {
     "type": "photo",
     "created_time": "2017-11-15T14:30:43+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/693061044378702",
     "shares": {
        "count": 2270
     },
     "id": "104957429855736_693061044378702"
  },
  {
     "type": "link",
     "created_time": "2017-11-15T02:34:46+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692656794419127",
     "shares": {
        "count": 86
     },
     "id": "104957429855736_692656794419127"
  },
  {
     "type": "photo",
     "created_time": "2017-11-15T00:34:50+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692493157768824",
     "shares": {
        "count": 1628
     },
     "id": "104957429855736_692493157768824"
  },
  {
     "type": "photo",
     "created_time": "2017-11-14T23:51:53+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692442954440511",
     "shares": {
        "count": 6239
     },
     "id": "104957429855736_692442954440511"
</code>```

This is the code I have:

```<code>   <body>
    <input type="text" class="txtPagina">
    <button class="btnBuscar">Buscar</button>
    <table class="tabla" border='1'>
         <tr>

             <td>Type</td>
          <td>created time</td>
             <td>permalink url</td>
             <td>Shares Count</td>

         </tr>
    </table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

     $(document).ready(function(){
            $('.btnBuscar').on('click', function (){
                var pagina = $('.txtPagina').val();
            //Ajax
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "https://graph.facebook.com/"+pagina+"/feed?fields=type,created_time,permalink_url,shares&limit=25& access_token=(mytoken)",
                success: function(data){

     $.each(data.data, function(i, d){
        var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
        $('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
      });
    },
                    error: function (){
                        console.log("Error");
</code>```

And this is the result I'm getting:

As you can see I'm getting photos and links but I need to see only links.

答:
Just add an if statement in your loop to filter out the photos.</p>

```<code> $.each(data.data, function(i, d){
      if(d.type =='link'){
      var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
    $('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
    }
  });
</code>```

Body:
I'm trying to import JSON data to a html table. I have different types of data. In my case I need only  to see the "link" data type in a table this is the JSON data I'm getting.

  {   "data": [
  {
     "type": "photo",
     "created_time": "2017-11-15T14:30:43+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/693061044378702",
     "shares": {
        "count": 2270
     },
     "id": "104957429855736_693061044378702"
  },
  {
     "type": "link",
     "created_time": "2017-11-15T02:34:46+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692656794419127",
     "shares": {
        "count": 86
     },
     "id": "104957429855736_692656794419127"
  },
  {
     "type": "photo",
     "created_time": "2017-11-15T00:34:50+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692493157768824",
     "shares": {
        "count": 1628
     },
     "id": "104957429855736_692493157768824"
  },
  {
     "type": "photo",
     "created_time": "2017-11-14T23:51:53+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692442954440511",
     "shares": {
        "count": 6239
     },
     "id": "104957429855736_692442954440511"

This is the code I have:

    <input type="text" class="txtPagina">
    <button class="btnBuscar">Buscar</button>

             Type
          created time
             permalink url
             Shares Count

Body:
Just add an if statement in your loop to filter out the photos.

 $.each(data.data, function(i, d){
      if(d.type =='link'){
      var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
    $('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
    }
  });


问:
Delete file from server using UTL_FILE.FRemove without knowing the file name
I am a reporting analyst, who was asked to learn some PL/SQL to automate some processes.  So I am almost finished, with one step standing in the way. I have a package that

Loads a table with a query I wrote.

Exports the results from that table to a .txt file on the server with the     current_date tacked onto the file name .

I am trying to delete the 3 files it creates using a wildcard, but I continually get errors such as "vendor_file.ia.*.txt is not defined":

file_location is my path

I can delete it no problem with:

```<code>    utl_file.fremove(file_location,'vendor_file.ia.09.02.2015.txt');
    utl_file.fremove(file_location,'vendor_file.il.09.02.2015.txt');
    utl_file.fremove(file_location,'vendor_file.sd.09.02.2015.txt');
</code>```

But obviously that won't delete it when it gets run next month. So am I missing a simple wildcard to search just for 'vendor_file.ia.*' And does the syntax look in Oracle?

If I didn't provide enough information please let me know!

Thanks a lot!

答:
You could use the preprocessor to run a shell script to delete the files.
Oracle docs on preprocessor</p>

Body:
I am a reporting analyst, who was asked to learn some PL/SQL to automate some processes.  So I am almost finished, with one step standing in the way. I have a package that

Loads a table with a query I wrote.

Exports the results from that table to a .txt file on the server with the     current_date tacked onto the file name .

I am trying to delete the 3 files it creates using a wildcard, but I continually get errors such as "vendor_file.ia.*.txt is not defined":

file_location is my path

I can delete it no problem with:

    utl_file.fremove(file_location,'vendor_file.ia.09.02.2015.txt');
    utl_file.fremove(file_location,'vendor_file.il.09.02.2015.txt');
    utl_file.fremove(file_location,'vendor_file.sd.09.02.2015.txt');

But obviously that won't delete it when it gets run next month. So am I missing a simple wildcard to search just for 'vendor_file.ia.*' And does the syntax look in Oracle?

If I didn't provide enough information please let me know!

Thanks a lot!


问:
Increasing email quota of all my application id on google app engine
We have multiple applications on google app engine account with different application id. We have limit of 100 emails/day with respect to each application id. How can we increase it using any api? Provide details how many emails we can send with that api?</p>

答:
You can't programatically change the email quota. From Quotas and limits:

The quota is reset daily. If you exceed the daily quota, you will get
  an over quota exception. If you need to send more mail then the
  quota allows, you can use a third-party mail provider, such as
  SendGrid or Mailgun.

It seems Mailjet is also a partner 3rd party provider.


问:
Defining UIBarButtonItems in a closure of a property in the ViewController
I would like to setup an array of UIBarButtonItems in property of the view controller through a closure.

So instead of doing this in viewDidLoad:

```<code>let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))
navigationItem.rightBarButtonItems = [b3, b2, b1]
</code>```

I did this:

```<code>lazy var bbItems: [UIBarButtonItem] = {
    let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
    let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
    let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))

    return  [b3, b2, b1]
}()
</code>```

Then in viewDidLoad:

```<code>navigationItem.rightBarButtonItems = bbItems
</code>```

I had to make it a lazy var for it to execute the functions connected to the buttons. When it was just a regular var it didn't execute it.

Is there any drawback in doing it like this. Is there a better way?

Thanks

答:
you can pass target to closure through parameters. i used Protocol to define a abstract type which have required functions for target.

it would be something like this in swift 4

```<code>// it should be @objc because selectors need functions that are visibile to Objective-C
@objc protocol NavigaitonBarConfigurable: class {
    func b1Tapped(_ sender: UIBarButtonItem)
    func b2Tapped(_ sender: UIBarButtonItem)
    func b3Tapped(_ sender: UIBarButtonItem)
}

/// create UIBarButtonItems
func createNavigationBarButtons(target: NavigaitonBarConfigurable) ->  [UIBarButtonItem] {
    let b1 = UIBarButtonItem(title: "MoveUp",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b1Tapped(_:)))
    let b2 = UIBarButtonItem(title: "b2",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b2Tapped(_:)))
    let b3 = UIBarButtonItem(title: "b3",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b3Tapped(_:)))
    return [b1, b2, b3]
}

class ViewController: UIViewController {
    // pass the function for creating buttons with target as self (self is NavigaitonBarConfigurable)
    lazy var bbItems: [UIBarButtonItem] = createNavigationBarButtons(target: self)

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.setRightBarButtonItems(self.bbItems, animated: false)
    }
}

extension ViewController: NavigaitonBarConfigurable {
    func b1Tapped(_ sender: UIBarButtonItem) {
        print("b1")
    }

    func b2Tapped(_ sender: UIBarButtonItem) {
        print("b2")
    }

    func b3Tapped(_ sender: UIBarButtonItem) {
        print("b3")
    }
}
</code>```

Body:
I would like to setup an array of UIBarButtonItems in property of the view controller through a closure.

So instead of doing this in viewDidLoad:

let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))
navigationItem.rightBarButtonItems = [b3, b2, b1]

I did this:

lazy var bbItems: [UIBarButtonItem] = {
    let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
    let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
    let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))

    return  [b3, b2, b1]
}()

Then in viewDidLoad:

navigationItem.rightBarButtonItems = bbItems

I had to make it a lazy var for it to execute the functions connected to the buttons. When it was just a regular var it didn't execute it.

Is there any drawback in doing it like this. Is there a better way?

Thanks

Body:
you can pass target to closure through parameters. i used Protocol to define a abstract type which have required functions for target.

it would be something like this in swift 4

// it should be @objc because selectors need functions that are visibile to Objective-C
@objc protocol NavigaitonBarConfigurable: class {
    func b1Tapped(_ sender: UIBarButtonItem)
    func b2Tapped(_ sender: UIBarButtonItem)
    func b3Tapped(_ sender: UIBarButtonItem)
}

/// create UIBarButtonItems
func createNavigationBarButtons(target: NavigaitonBarConfigurable) ->  [UIBarButtonItem] {
    let b1 = UIBarButtonItem(title: "MoveUp",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b1Tapped(_:)))
    let b2 = UIBarButtonItem(title: "b2",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b2Tapped(_:)))
    let b3 = UIBarButtonItem(title: "b3",
                             style: .plain,
                             target: target,
                             action: #selector(NavigaitonBarConfigurable.b3Tapped(_:)))
    return [b1, b2, b3]
}

class ViewController: UIViewController {
    // pass the function for creating buttons with target as self (self is NavigaitonBarConfigurable)
    lazy var bbItems: [UIBarButtonItem] = createNavigationBarButtons(target: self)

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.setRightBarButtonItems(self.bbItems, animated: false)
    }
}

extension ViewController: NavigaitonBarConfigurable {
    func b1Tapped(_ sender: UIBarButtonItem) {
        print("b1")
    }

    func b2Tapped(_ sender: UIBarButtonItem) {
        print("b2")
    }

    func b3Tapped(_ sender: UIBarButtonItem) {
        print("b3")
    }
}


问:
Problem with session attributes in JSP EL using Spring MVC
I'm trying to show a session attribute "userSession" in a jsp page using JSP EL, but it returns null (case 1). Request attributes are shown properly in EL expressions though.

Using java scriptlet instead, behaves as shown in cases 2 and 3:

<c:out value="${userSession}"/> \\Returns null

<c:out value='<%=request.getSession().getAttribute("userSession")%>'/>
\\Works fine - returns session attribute

<c:out value='<%=session.getAttribute("userSession")%>'/>
\\Throws exception: cannot find variable session

Exception of case 3 may be related to case 1 problem, something like not recognizing the session variable for some reason and that affecting the EL expression then.

I'm using Spring MVC 2.5 and JSTL 1.1.2.

I can post anything else needed to clarify the problem.

答:
Fixed. Problem was with a <%@ page session="false" %> directive found in an include.jsp used by my page, which I removed from that global place.

It prevents a jsp page from access to session scope variables. So only <%=request.getSession().getAttribute("foo")%> works in that case...


问:
CSS Div Positions
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

```

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

答:
JSFiddle Here

.first {
  border: 5px solid black;
  height: auto;
  position: relative;
  padding: 5px;
  margin-bottom: 50px;
  margin-top: 50px;
}
.first img {
  position: relative;
  height: auto;
}

.second {
  position: relative;
}
.second img {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div style="border-style: solid;border-color:blue;">
     <div class="icon" style="float:right">
      <img id="logo"src="https://www.circle-cafe.com/files/social-icons/in.svg">
      <img id="logo"src="https://ugihvac.com/wp-content/uploads/2015/10/twitter_icon.png">
      <img id="logo"src="http://saconnects.org/wp-content/uploads/Facebook-icon-e1447702821330.png">
      </div>
        <br><br>
        <div class="first">
      <img style="float:left;"src="https://d30y9cdsu7xlg0.cloudfront.net/png/17241-200.png">
      <p> <strong> Ali Omar <br> November 13,2017 </strong> </p>
      <br>
      <p> The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice. </p>
        </div>

     <div class="second" style="border-style: solid;border-color:orange;">
         <br>
      <img style="float:left;"src="https://d30y9cdsu7xlg0.cloudfront.net/png/17241-200.png">
      <p> <strong> Guest <br> November 13,2017 <br> Hi Ali,,, </strong> </p>
      <br>
      <p> When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me </p>
     </div>
      <br>
    </div></code>```

Title: CSS Div Positions

Body:
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

Body:
JSFiddle Here

.first {
  border: 5px solid black;
  height: auto;
  position: relative;
  padding: 5px;
  margin-bottom: 50px;
  margin-top: 50px;
}
.first img {
  position: relative;
  height: auto;
}

.second {
  position: relative;
}
.second img {
  position: relative;
}

 <div style="border-style: solid;border-color:blue;">
     <div class="icon" style="float:right">
      <img id="logo"src="https://www.circle-cafe.com/files/social-icons/in.svg">
      <img id="logo"src="https://ugihvac.com/wp-content/uploads/2015/10/twitter_icon.png">
      <img id="logo"src="http://saconnects.org/wp-content/uploads/Facebook-icon-e1447702821330.png">
      </div>
        <br><br>
        <div class="first">
      <img style="float:left;"src="https://d30y9cdsu7xlg0.cloudfront.net/png/17241-200.png">
      <p> <strong> Ali Omar <br> November 13,2017 </strong> </p>
      <br>
      <p> The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice. </p>
        </div>

     <div class="second" style="border-style: solid;border-color:orange;">
         <br>
      <img style="float:left;"src="https://d30y9cdsu7xlg0.cloudfront.net/png/17241-200.png">
      <p> <strong> Guest <br> November 13,2017 <br> Hi Ali,,, </strong> </p>
      <br>
      <p> When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me </p>
     </div>
      <br>
    </div>


问:
Check if a value from a list of values in a python dictionary exists in another dictionary
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

```<code> import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')
</code>```

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

```<code>errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1
</code>```

However the output I get is wrong. I get :

```<code>name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report
</code>```

My expected output would :

```<code>AccountReport is an invalid report
dob is an invalid field in PersonReport report
</code>```

Any help is appreciated
Thanks
p.s I'm using python 3.6

答:
I kept it simple and followed your conventions:

```<code>errorCount = 0

for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    else:
        if template[key] != master[key]:
            fields = [f for f in template[key] if f not in master[key]]
            for f in fields:
                print("{} is an invalid field in {} report".format(f, key))
                errorCount += 1
</code>```

From the console:

```<code>AccountReport is an invalid report
dob is an invalid field in  PersonReport report
</code>```

Body:
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

 import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1

However the output I get is wrong. I get :

name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report

My expected output would :

AccountReport is an invalid report
dob is an invalid field in PersonReport report

Any help is appreciated
Thanks
p.s I'm using python 3.6

Body:
I kept it simple and followed your conventions:

errorCount = 0

for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    else:
        if template[key] != master[key]:
            fields = [f for f in template[key] if f not in master[key]]
            for f in fields:
                print("{} is an invalid field in {} report".format(f, key))
                errorCount += 1

From the console:

AccountReport is an invalid report
dob is an invalid field in  PersonReport report


问:
Jupyter | How to rotate 3D graph
I am not sure about how to rotate graph in Python Jupyter notebook, its static for me and not rotate on mouse movement

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6,2,3,13,4,1,2,4,8]
z =[2,3,3,3,5,7,9,11,9,10]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
</code>```

答:
As described on matplotlib website you can create an interactive graph by importing mplot3d. Please use the following sample Rotate Axes.

I am going to include the code just in case the link is not available in future.

```<code>from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

%matplotlib notebook

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# load some test data for demonstration and plot a wireframe
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)

# rotate the axes and update
for angle in range(0, 360):
    ax.view_init(30, angle)
    plt.draw()
    plt.pause(.001)
</code>```

Title: Jupyter | How to rotate 3D graph

Body:
I am not sure about how to rotate graph in Python Jupyter notebook, its static for me and not rotate on mouse movement

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6,2,3,13,4,1,2,4,8]
z =[2,3,3,3,5,7,9,11,9,10]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

Body:
As described on matplotlib website you can create an interactive graph by importing mplot3d. Please use the following sample Rotate Axes.

I am going to include the code just in case the link is not available in future.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

%matplotlib notebook

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# load some test data for demonstration and plot a wireframe
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)

# rotate the axes and update
for angle in range(0, 360):
    ax.view_init(30, angle)
    plt.draw()
    plt.pause(.001)


问:
How to preserve pandas dataframe columns using to_sql
I want to store some data from dataframes into an sqlite database. I am doing the following:

first create a database:

```<code>conn = sqlite3.connect("mydatabase.db")
</code>```

then add table from dataframe df to database:

```<code>df.to_sql(table_name, conn,if_exists='append')
</code>```

then querying the table from the database:

```<code>cur = conn.cursor()
cur.execute("SELECT * FROM table_name")
rows = cur.fetchall()
df2=pd.DataFrame(rows)
</code>```

df2 does not have the original common names but has been reindex to 0, 1,2,3 etc.

How can I preserve the columns of the original dataframe?

Thank you

答:
try this:

```<code>df2 = pd.read_sql("SELECT * FROM table_name", conn)
</code>```

some color:

your table is fine, it has the columns, you fetch a list of tuple of values using cur.fetchall() it does not have any info for columns name so pandas just use numbers.

read_sql() check for column names and does it for you

Body:
I want to store some data from dataframes into an sqlite database. I am doing the following:

first create a database:

conn = sqlite3.connect("mydatabase.db")

then add table from dataframe df to database:

df.to_sql(table_name, conn,if_exists='append')

then querying the table from the database:

cur = conn.cursor()
cur.execute("SELECT * FROM table_name")
rows = cur.fetchall()
df2=pd.DataFrame(rows)

df2 does not have the original common names but has been reindex to 0, 1,2,3 etc.

How can I preserve the columns of the original dataframe?

Thank you

Body:
try this:

df2 = pd.read_sql("SELECT * FROM table_name", conn)

some color:

your table is fine, it has the columns, you fetch a list of tuple of values using cur.fetchall() it does not have any info for columns name so pandas just use numbers.

read_sql() check for column names and does it for you


问:
Lift doesn't like my Web.xml
I am having trouble with a basic hello world lift application from working under tomcat 6.0.18. My web.xml looks like this

```<code><?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <filter>
        <filter-name>LiftFilter</filter-name>
        <display-name>Lift Filter</display-name>
        <description>The Filter that intercepts lift calls</description>
        <filter-class>net.liftweb.http.LiftFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LiftFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
</code>```

But when I start up the app, I get

```<code>INFO: Starting service Catalina Jan 18, 2011 7:42:44 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.18 Jan 18, 2011 7:42:44 PM org.apache.catalina.startup.ContextConfig defaultWebConfig
INFO: No default web.xml
Jan 18, 2011 7:42:45 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9981 Jan 18, 2011 7:42:45 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1275 ms
</code>```

Which leads me to believe it doesn't like my web.xml.

Any ideas?

答: The default web.xml (in the conf directory) seems to be missing, you web.xml should be OK providing it's in the WEB-INF folder of course.

Title: Lift doesn't like my Web.xml

Body:
I am having trouble with a basic hello world lift application from working under tomcat 6.0.18. My web.xml looks like this

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <filter>
        <filter-name>LiftFilter</filter-name>
        <display-name>Lift Filter</display-name>
        <description>The Filter that intercepts lift calls</description>
        <filter-class>net.liftweb.http.LiftFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LiftFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

But when I start up the app, I get

INFO: Starting service Catalina Jan 18, 2011 7:42:44 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.18 Jan 18, 2011 7:42:44 PM org.apache.catalina.startup.ContextConfig defaultWebConfig
INFO: No default web.xml
Jan 18, 2011 7:42:45 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9981 Jan 18, 2011 7:42:45 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1275 ms

Which leads me to believe it doesn't like my web.xml.

Any ideas?


问:
three.js / A-Frame ObjectLoader does not load Texture and positions Meshes wrongly
We have an issue with exporting our 3D Assets and animations correctly so that three.js can correctly display them.

All our 3D artists work with Cinema4D so we need to go through blender to export a three.js compatible JSON. They export the scene as FBX and then import it to blender. This seems to work fine. The model looks good there (with Material View set in Preview Window) and the simpler models we exported even worked with textures and animations.

But we now have a scene where, when we load the resulting JSON, some of the meshes are flipped 180° (but only some - the trees) and one of the models (Santa model) is not textured. They all look fine in blender.

When loading the JSON in https://threejs.org/editor/ you will immediately see the issues:

Is this an export problem? Can we fix it by tweaking the export params? Will we need to adjust the model in blender?

答:
I would advise a couple things here:

File a bug on three.js including the .blend file

Try freezing transforms in Blender or C4D before export

Perhaps try a different three.js-compatible blender exporter, like glTF-Blender-Exporter.


问:
How do I detect with JavaScript or JQuery whether a URL points to a web page or a binary file?
I'm crawling a web page list of links that are either web pages or large binary files (PPT etc), using javascript and jquery. </p>

<p>How do I detect whether the content is a web page ('text/html') or not? I'm pretty sure it is looking at the HTTP header using $.ajax, and I know there are some similar posted questions, but I can't find an example that fits this particular question. </p>

答:
You can check extension of url - lightest method.
Or you can try ajax solution</p>

```<code>var url = 'someurl';
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
  if (this.readyState == this.DONE) {
    console.log(this.status);
    console.log(this.getResponseHeader("Content-Type"));
  }
};
xhttp.send();
</code>```

Body:
I'm crawling a web page list of links that are either web pages or large binary files (PPT etc), using javascript and jquery.

How do I detect whether the content is a web page ('text/html') or not? I'm pretty sure it is looking at the HTTP header using $.ajax, and I know there are some similar posted questions, but I can't find an example that fits this particular question.

Body:
You can check extension of url - lightest method.
Or you can try ajax solution

var url = 'someurl';
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
  if (this.readyState == this.DONE) {
    console.log(this.status);
    console.log(this.getResponseHeader("Content-Type"));
  }
};
xhttp.send();


问:
Designing custom sign in flow/activity for Cognito
I am following the Amazon cognito user signin guide here: http://docs.aws.amazon.com/mobile-hub/latest/developerguide/add-aws-mobile-user-sign-in-email-and-password.html#email-and-password-config-overview

It all works perfectly, but the default activity they launch is ugly and surprisingly hard to use. The code they use to launch this activity is

```<code>    AuthUIConfiguration config =
            new AuthUIConfiguration.Builder().userPools(true).build();

    Context context = SplashActivity.this;
    SignInActivity.startSignInActivity(context, config);
</code>```

I would like to build my own sign in flow. Is that even possible? Is there a tutorial out there on how to do this?

I am cant their flow, because when I follow the link to SignInActivity, I get ...\.grade\caches\ modules-2\files-2.1\com.amazonaws\aws-android-sdk-auth-ui\2.6.0\991ae12d55d8733e2ebb4b3e4c30a6cc2ee42d3a\aws-android-sdk-auth-ui-2.6.0-sources.jar!\com\amazonaws\mo and the file is locked for editing.

答:
We have recently worked on the AWS mobile app and we know that only cloning the SigninActivity Code won't work. You would need to clone SigninView, UserPoolSignInView, and CognitoUserPoolsSignInProvider.
We had added a progressbar in the layout and set the visibility on the click event of the buttonview.

I hope these instructions should help.

Cheers,
Kapil

Body:
I am following the Amazon cognito user signin guide here: http://docs.aws.amazon.com/mobile-hub/latest/developerguide/add-aws-mobile-user-sign-in-email-and-password.html#email-and-password-config-overview

It all works perfectly, but the default activity they launch is ugly and surprisingly hard to use. The code they use to launch this activity is

    AuthUIConfiguration config =
            new AuthUIConfiguration.Builder().userPools(true).build();

    Context context = SplashActivity.this;
    SignInActivity.startSignInActivity(context, config);

I would like to build my own sign in flow. Is that even possible? Is there a tutorial out there on how to do this?

I am cant their flow, because when I follow the link to SignInActivity, I get ...\.grade\caches\ modules-2\files-2.1\com.amazonaws\aws-android-sdk-auth-ui\2.6.0\991ae12d55d8733e2ebb4b3e4c30a6cc2ee42d3a\aws-android-sdk-auth-ui-2.6.0-sources.jar!\com\amazonaws\mo and the file is locked for editing.


问:
Why does C++ use the name of the class for the ctor/dtor?
One thing that occasionally irks me about C++ is the repetition of defining constructors. This is especially true when defining the ctors in a separate cpp file. When we refer to them generally, we usually say "constructor", "destructor", "copy constructor", or abbreviate them as "ctor", "dtor", and "cctor". Even some C++ compilers abbreviate them like that. So why doesn't the language use that? Isn't:

```<code>class SomeLongSelfDocumentingClassName
{
   ctor(int a, string b);
   cctor(const SomeLongSelfDocumentingClassName& other);
   ~dtor();
};

SomeLongSelfDocumentingClassName::ctor(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::cctor(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::dtor(int a, string b) { /* ... */ }
</code>```

easier to read than:

```<code>class SomeLongSelfDocumentingClassName
{
   SomeLongSelfDocumentingClassName(int a, string b);
   SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other);
   ~SomeLongSelfDocumentingClassName();
};

SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }
</code>```

?

Admittedly, I've been doing it the repetitive way for so long that the former block looks like nonsense at first glance. Is there a good reason Stroustrup chose the repetitious representation that just hasn't occurred to me?

答:
It comes from the evolution of C++ as being "C with classes".

The C and C++ language committees (ISO these days) are always reluctant to introduce new keywords as doing that can break a lot of code. ctor and dtor would have been a new keywords. Note that cctor would not be additionally required since C++ supports function overloading; even if the very initial drafts did not.

Furthermore, being able to name a member function to be the same as the name of the class would be an exercise in obfuscation! Reserving it for construction and destruction therefore makes sense in this context.

Using the name of the class as the constructor with a ~ for the destructor was a sensible choice at the time. It still is, in my opinion at least.

Body:
One thing that occasionally irks me about C++ is the repetition of defining constructors. This is especially true when defining the ctors in a separate cpp file. When we refer to them generally, we usually say "constructor", "destructor", "copy constructor", or abbreviate them as "ctor", "dtor", and "cctor". Even some C++ compilers abbreviate them like that. So why doesn't the language use that? Isn't:

class SomeLongSelfDocumentingClassName
{
   ctor(int a, string b);
   cctor(const SomeLongSelfDocumentingClassName& other);
   ~dtor();
};

SomeLongSelfDocumentingClassName::ctor(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::cctor(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::dtor(int a, string b) { /* ... */ }

easier to read than:

class SomeLongSelfDocumentingClassName
{
   SomeLongSelfDocumentingClassName(int a, string b);
   SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other);
   ~SomeLongSelfDocumentingClassName();
};

SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(const SomeLongSelfDocumentingClassName& other) { /* ... */ }
SomeLongSelfDocumentingClassName::SomeLongSelfDocumentingClassName(int a, string b) { /* ... */ }

?

Admittedly, I've been doing it the repetitive way for so long that the former block looks like nonsense at first glance. Is there a good reason Stroustrup chose the repetitious representation that just hasn't occurred to me?


答:
in your each loop:

```<code>if(d.type == 'link') {
    //Add as you already do
}
</code>```

Done!

Title: Import JSON to html (table) filtering results

Body:
I'm trying to import JSON data to a html table. I have different types of data. In my case I need only  to see the "link" data type in a table this is the JSON data I'm getting.

  {   "data": [
  {
     "type": "photo",
     "created_time": "2017-11-15T14:30:43+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/693061044378702",
     "shares": {
        "count": 2270
     },
     "id": "104957429855736_693061044378702"
  },
  {
     "type": "link",
     "created_time": "2017-11-15T02:34:46+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692656794419127",
     "shares": {
        "count": 86
     },
     "id": "104957429855736_692656794419127"
  },
  {
     "type": "photo",
     "created_time": "2017-11-15T00:34:50+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692493157768824",
     "shares": {
        "count": 1628
     },
     "id": "104957429855736_692493157768824"
  },
  {
     "type": "photo",
     "created_time": "2017-11-14T23:51:53+0000",
     "permalink_url": "https://www.facebook.com/LaFokaES/posts/692442954440511",
     "shares": {
        "count": 6239
     },
     "id": "104957429855736_692442954440511"

This is the code I have:

    <input type="text" class="txtPagina">
    <button class="btnBuscar">Buscar</button>

             Type
          created time
             permalink url
             Shares Count

Body:
in your each loop:

if(d.type == 'link') {
    //Add as you already do
}

Done!


问:
How to obtain value from vars
Am trying to get value from request.vars but end up getting a null value.
My code:

```<code>if request.vars.message:
    return request.vars.message
R = request.vars.message
return dict (R=R, form =form)
</code>```

My vew.html
{{=R}}

This prints none.

答:
In your code, whenever request.vars.message has a value, it immediately returns the value (inside the if block). The only case in which the code reaches the return dict(...) line at the end is when request.vars.message is missing (technically, any falsey value, but in most cases it is probably None, meaning there is no message key in the request.vars object).

If you want to send the value of message to the view to be displayed, then do not return inside the if block.

Title: How to obtain value from vars

Body:
Am trying to get value from request.vars but end up getting a null value.
My code:

if request.vars.message:
    return request.vars.message
R = request.vars.message
return dict (R=R, form =form)

My vew.html
{{=R}}

This prints none.


问:
Split two divs with diagonal line, scaling to content
I've got a mockup for a website which has a hero section consisting of two sections, split diagonally at the same angle. The two sections have content and need to scale to fit the content.

I have tried the method described here: two divs split with diagonal line - CSS
but it doesn't work well with content; adding text to the div just extends the rectangle not the triangle. How do I get the boxes to scale with the content?

I would post a comment but I don't have the reputation :/

EDIT: by scaling to content, I mean that the if I add content to one of the divs, the div should be able to fit all of the content inside of it. Both of the divs would need to be the same height. Apologies for any confusion :)

答:
The question is not so clear as to :

scaling to content

I suppose it means that it should keep the same aspect after window resize (??).

```<code>// Create a flex container
.hero {
  display: flex;
  height: 500px;
  width: 100%;
  flex-flow: row nowrap; // make the two divs side by side
  font-size: 2em;
  color: white;
  font-family: sans-serif;
  position: relative;
}

// apply basic styles to the divs
.hero div{
  display: flex;
  position: relative;
  background-color: tomato;
  width: 50%;
  padding: 50px;
}

// + 100px for :after and :before to fit
// + 10px for the space we really want to see between diagonal
.hero div:first-child{
  margin-right: 110px;
}

.hero_1:after, .hero_2:before{
  content:'';
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
}

// Add a triangle at the end and starts of both divs to simulate diagonal
.hero_1:after {
    left: 100%;
    border-top: 500px solid tomato;
    border-right: 100px solid transparent;
}
.hero_2:before {
    right: 100%;
    border-bottom: 500px solid tomato;
    border-left: 100px solid transparent;
}
</code>```

Please have a look to this codepen. The split is made with a diagonal line, and it fits to window resizes.

If it's not the desired effect, please edit the question to be more explicit about "scaling to content" I'll be happy to help.

Body:
The question is not so clear as to :

scaling to content

I suppose it means that it should keep the same aspect after window resize (??).

// Create a flex container
.hero {
  display: flex;
  height: 500px;
  width: 100%;
  flex-flow: row nowrap; // make the two divs side by side
  font-size: 2em;
  color: white;
  font-family: sans-serif;
  position: relative;
}

// apply basic styles to the divs
.hero div{
  display: flex;
  position: relative;
  background-color: tomato;
  width: 50%;
  padding: 50px;
}

// + 100px for :after and :before to fit
// + 10px for the space we really want to see between diagonal
.hero div:first-child{
  margin-right: 110px;
}

.hero_1:after, .hero_2:before{
  content:'';
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
}

// Add a triangle at the end and starts of both divs to simulate diagonal
.hero_1:after {
    left: 100%;
    border-top: 500px solid tomato;
    border-right: 100px solid transparent;
}
.hero_2:before {
    right: 100%;
    border-bottom: 500px solid tomato;
    border-left: 100px solid transparent;
}

Please have a look to this codepen. The split is made with a diagonal line, and it fits to window resizes.

If it's not the desired effect, please edit the question to be more explicit about "scaling to content" I'll be happy to help.


问:
Detect face and apply a mask on it with openCV
UPDATE: here is opencv c++ sample and shows exactly what I want to do. Only thing is I need it with java.

I have been working on a real-time Android application which detects face with front camera and add a mask on a detected face. So far face detection is working well with cascade classifier.

I am drawing rectangles around face and circles for eyes:

```<code> Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
    {
        Imgproc.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(), FACE_RECT_COLOR, 3);

        xCenter = (facesArray[i].x + facesArray[i].width + facesArray[i].x) / 2;
        yCenter = (facesArray[i].y + facesArray[i].y + facesArray[i].height) / 2;
        Point center = new Point(xCenter, yCenter);
        Imgproc.circle(mRgba, center, 10, new Scalar(255, 0, 0, 255), 3);

    }
</code>```

My question is, how to apply an image on detected face and show it at real time. (e.g. sunglasses, hat, moustache, and a funny animal face)

If anyone could give a tip or tell me some key points, I would be so grateful.

This is a good example what I expect from my application. I have examined the code though but couldn't understand.

Thanks!

答:
[SOLVED]

Here is a working code for me for putting mask.

Thanks to @paul_poveda and @hariprasad

this is the method:

```<code>Mat putMask(Mat src, Point center, Size face_size){

//mask : masque chargé depuis l'image
Mat mask_resized = new Mat(); //masque resizé
src_roi = new Mat(); //ROI du visage croppé depuis la preview
roi_gray = new Mat();

Imgproc.resize(mask ,mask_resized,face_size);

// ROI selection
roi = new Rect((int) (center.x - face_size.width/2), (int) (center.y - face_size.height/2),(int) face_size.width, (int) face_size.height);
//Rect roi = new Rect(10, 10, (int) face_size.width, (int) face_size.height);

src.submat(roi).copyTo(src_roi);

Log.e(TAG, "MASK SRC1 :"+ src_roi.size());

// to make the white region transparent
Mat mask_grey = new Mat(); //greymask
roi_rgb = new Mat();
Imgproc.cvtColor(mask_resized,mask_grey, Imgproc.COLOR_BGRA2GRAY);
Imgproc.threshold(mask_grey,mask_grey,230,255, Imgproc.THRESH_BINARY_INV);

ArrayList<Mat> maskChannels = new ArrayList<>(4);
ArrayList<Mat> result_mask = new ArrayList<>(4);
result_mask.add(new Mat());
result_mask.add(new Mat());
result_mask.add(new Mat());
result_mask.add(new Mat());

Core.split(mask_resized, maskChannels);

Core.bitwise_and(maskChannels.get(0),mask_grey, result_mask.get(0));
Core.bitwise_and(maskChannels.get(1),mask_grey, result_mask.get(1));
Core.bitwise_and(maskChannels.get(2),mask_grey, result_mask.get(2));
Core.bitwise_and(maskChannels.get(3),mask_grey, result_mask.get(3));

Core.merge(result_mask, roi_gray);

Core.bitwise_not(mask_grey,mask_grey);

ArrayList<Mat> srcChannels = new ArrayList<>(4);
Core.split(src_roi, srcChannels);
Core.bitwise_and(srcChannels.get(0),mask_grey, result_mask.get(0));
Core.bitwise_and(srcChannels.get(1),mask_grey, result_mask.get(1));
Core.bitwise_and(srcChannels.get(2),mask_grey, result_mask.get(2));
Core.bitwise_and(srcChannels.get(3),mask_grey, result_mask.get(3));

Core.merge(result_mask, roi_rgb);

Core.addWeighted(roi_gray,1, roi_rgb,1,0, roi_rgb);

roi_rgb.copyTo(new Mat(src,roi));

return src;}
</code>```

Body:
UPDATE: here is opencv c++ sample and shows exactly what I want to do. Only thing is I need it with java.

I have been working on a real-time Android application which detects face with front camera and add a mask on a detected face. So far face detection is working well with cascade classifier.

I am drawing rectangles around face and circles for eyes:

 Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
    {
        Imgproc.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(), FACE_RECT_COLOR, 3);

        xCenter = (facesArray[i].x + facesArray[i].width + facesArray[i].x) / 2;
        yCenter = (facesArray[i].y + facesArray[i].y + facesArray[i].height) / 2;
        Point center = new Point(xCenter, yCenter);
        Imgproc.circle(mRgba, center, 10, new Scalar(255, 0, 0, 255), 3);

    }

My question is, how to apply an image on detected face and show it at real time. (e.g. sunglasses, hat, moustache, and a funny animal face)

If anyone could give a tip or tell me some key points, I would be so grateful.

This is a good example what I expect from my application. I have examined the code though but couldn't understand.

Thanks!

Body:
[SOLVED]

Here is a working code for me for putting mask.

Thanks to @paul_poveda and @hariprasad

this is the method:

Mat putMask(Mat src, Point center, Size face_size){

//mask : masque chargé depuis l'image
Mat mask_resized = new Mat(); //masque resizé
src_roi = new Mat(); //ROI du visage croppé depuis la preview
roi_gray = new Mat();

Imgproc.resize(mask ,mask_resized,face_size);

// ROI selection
roi = new Rect((int) (center.x - face_size.width/2), (int) (center.y - face_size.height/2),(int) face_size.width, (int) face_size.height);
//Rect roi = new Rect(10, 10, (int) face_size.width, (int) face_size.height);

src.submat(roi).copyTo(src_roi);

Log.e(TAG, "MASK SRC1 :"+ src_roi.size());

// to make the white region transparent
Mat mask_grey = new Mat(); //greymask
roi_rgb = new Mat();
Imgproc.cvtColor(mask_resized,mask_grey, Imgproc.COLOR_BGRA2GRAY);
Imgproc.threshold(mask_grey,mask_grey,230,255, Imgproc.THRESH_BINARY_INV);

ArrayList<Mat> maskChannels = new ArrayList<>(4);
ArrayList<Mat> result_mask = new ArrayList<>(4);
result_mask.add(new Mat());
result_mask.add(new Mat());
result_mask.add(new Mat());
result_mask.add(new Mat());

Core.split(mask_resized, maskChannels);

Core.bitwise_and(maskChannels.get(0),mask_grey, result_mask.get(0));
Core.bitwise_and(maskChannels.get(1),mask_grey, result_mask.get(1));
Core.bitwise_and(maskChannels.get(2),mask_grey, result_mask.get(2));
Core.bitwise_and(maskChannels.get(3),mask_grey, result_mask.get(3));

Core.merge(result_mask, roi_gray);

Core.bitwise_not(mask_grey,mask_grey);

ArrayList<Mat> srcChannels = new ArrayList<>(4);
Core.split(src_roi, srcChannels);
Core.bitwise_and(srcChannels.get(0),mask_grey, result_mask.get(0));
Core.bitwise_and(srcChannels.get(1),mask_grey, result_mask.get(1));
Core.bitwise_and(srcChannels.get(2),mask_grey, result_mask.get(2));
Core.bitwise_and(srcChannels.get(3),mask_grey, result_mask.get(3));

Core.merge(result_mask, roi_rgb);

Core.addWeighted(roi_gray,1, roi_rgb,1,0, roi_rgb);

roi_rgb.copyTo(new Mat(src,roi));

return src;}


答:
You won't reliably be able to infer the type from the URL, as it may contain an extension like exe or html, but doesn't have to, and if it does, it's not a guarantee.

The closest you can get without completely downloading and examining the file is probably to fire off a HEAD HTTP request to the URL. This should return the response headers without the body, which in turn should contain the Content-Type header. This all depends on the implementation and configuration of the backend though, so no guarantee that the request will be answered correctly or even answered at all.

Title: How do I detect with JavaScript or JQuery whether a URL points to a web page or a binary file?


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答: No, it's not atomic.  See this question for why and what to do about it.</p>

OwnerDisplayName: Hanno

LastEditorDisplayName: Hanno

OwnerDisplayName: Jason Cohen


问:
Failed to serialize the response in Web API with Json
I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

I wrote api/users and I receive this:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

In WebApiConfig, already I added these lines:

```<code>HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
</code>```

But it still doesn't work.

My function for return data is this:

```<code>public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}
</code>```

答:
This also happens when the Response-Type is not public!
I returned an internal class as I used Visual Studio to generate me the type.</p>

```<code>internal class --> public class
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

I wrote api/users and I receive this:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

In WebApiConfig, already I added these lines:

HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

But it still doesn't work.

My function for return data is this:

public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}

Body:
This also happens when the Response-Type is not public!
I returned an internal class as I used Visual Studio to generate me the type.

internal class --> public class