问:
top bar overlapping in unsafe area
my top bar works fine in all other iPhones except iPhoneX due to safe area introduction.The top bar starts in unsafe area itself.The top bar is a custom UI.It looks as below:

The code is as follows:

```<code>    //Top Bar
    let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
    topBar.backgroundColor = UIColor.white
    topBar.layer.shadowColor = UIColor.gray.cgColor
    topBar.layer.shadowOffset = CGSize(width: 0, height: 3)
    topBar.layer.shadowOpacity = 1
    topBar.layer.masksToBounds = false
    topBar.layer.shadowRadius = 8.0;

    self.view.addSubview(topBar)
</code>```

How do I fix this.I want view to start from safe area.And I don't want to use UINavigationBar.Thanks.

答:
Use Auto-Layout and layout guide to build your UI. For example, use SnapKit.

```<code>let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
topBar.snp.makeConstraints { make in

    make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)

    make.leading.trailing.equalToSuperview()
}
</code>```

Update

Re-write with original api.

```<code>let topBar = UIView(frame:CGRect(x: 0,y: 0, width: 30, height: 60))
self.view.addSubview(topBar)
let top = NSLayoutConstraint.init(item: topBar, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let leading = NSLayoutConstraint.init(item: topBar, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailing = NSLayoutConstraint.init(item: topBar, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let height = NSLayoutConstraint.init(item: topBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)
topBar.addConstraints([top, leading, trailing, height])
</code>```

Title: top bar overlapping in unsafe area

Body:
my top bar works fine in all other iPhones except iPhoneX due to safe area introduction.The top bar starts in unsafe area itself.The top bar is a custom UI.It looks as below:

The code is as follows:

    //Top Bar
    let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
    topBar.backgroundColor = UIColor.white
    topBar.layer.shadowColor = UIColor.gray.cgColor
    topBar.layer.shadowOffset = CGSize(width: 0, height: 3)
    topBar.layer.shadowOpacity = 1
    topBar.layer.masksToBounds = false
    topBar.layer.shadowRadius = 8.0;

    self.view.addSubview(topBar)

How do I fix this.I want view to start from safe area.And I don't want to use UINavigationBar.Thanks.

Body:
Use Auto-Layout and layout guide to build your UI. For example, use SnapKit.

let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
topBar.snp.makeConstraints { make in

    make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)

    make.leading.trailing.equalToSuperview()
}

Update

Re-write with original api.

let topBar = UIView(frame:CGRect(x: 0,y: 0, width: 30, height: 60))
self.view.addSubview(topBar)
let top = NSLayoutConstraint.init(item: topBar, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let leading = NSLayoutConstraint.init(item: topBar, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailing = NSLayoutConstraint.init(item: topBar, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let height = NSLayoutConstraint.init(item: topBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)
topBar.addConstraints([top, leading, trailing, height])


来源: stackexchange

问:
Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
i have created a chat app using pusher in laravel
but this types errors occurs in console when run application

WebSocket connection to 'wss://ws-your-pusher-app-cluster.pusher.com/app/your-pusher-key?protocol=7&client=js&version=4.1.0&flash=false' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

OPTIONS https://sockjs-your-pusher-app-cluster.pusher.com/pusher/app/your-pusher-key/150/ccc8teqg/xhr_streaming?protocol=7&client=js&version=4.1.0&t=1510723218799&n=1 net::ERR_NAME_NOT_RESOLVED

答: ERR_NAME_NOT_RESOLVED means the hostname cannot be resolved to an IP address by the DNS. If you look at the hostname ws-your-pusher-app-cluster.pusher.com, you can see that you should change the subdomain ws-your-pusher-app-cluster to whatever cluster your pusher app is located on. You can find the cluster in the Pusher dashboard.

ContentLicense: CC BY-SA 3.0


问:
CSS/Javascript - using hover to show dropdown div
I am having a hard time of this... I have an existing navigation bar that uses a table (i know it would be better to use a UL tag but i'm editing a pre existing page so would rather not reinvent the wheel). I have a javascript snipped that shows a dropdown menu when you hover. However, i'm at a loss to figure out how in the world to make it disappear at the right time. As in... when you hover over anavbar1, the div is shown as expected. but then, how to make it hide after say a certain number of seconds, or as soon as another navbar dropdown is triggered (like a normal dropdown)? here is my entire code :</p>

```<code><link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:600" rel="stylesheet">
<style type="text/css">
    #anavbar0 {
        display: block;
        width: 633px; height: 107px;
        background: url("../GFX/slice0.png") no-repeat 0 0;
    }
    #anavbar0:hover {}
    #anavbar0 span {
        display: none;
    }

    .anavbar1 {
        display: block;
        width: 104px; height: 107px;
        background: url("../GFX/slice1.png") no-repeat 0 0;
    }
    .anavbar1:hover .dropdown1 {
        display: block;
    }
    .anavbar1:hover {
        background-position: 0 -107px;
    }
    .anavbar1 span {
        display: none;
    }

    #anavbar2 {
        display: block;
        width: 169px; height: 107px;
        background: url("../GFX/slice2.png") no-repeat 0 0;
    }
    #anavbar2:hover {
        background-position: 0 -107px;
    }
    #anavbar2 span {
        display: none;
    }

    #anavbar3 {
        display: block;
        width: 134px; height: 107px;
        background: url("../GFX/slice3.png") no-repeat 0 0;
    }
    #anavbar3:hover {
        background-position: 0 -107px;
    }
    #anavbar3 span {
        display: none;
    }

    #anavbar4 {
        display: block;
        width: 102px; height: 107px;
        background: url("../GFX/slice4.png") no-repeat 0 0;
    }
    #anavbar4:hover {
        background-position: 0 -107px;
    }
    #anavbar4 span {
        display: none;
    }

    #anavbar5 {
        display: block;
        width: 103px; height: 107px;
        background: url("../GFX/slice5.png") no-repeat 0 0;
    }
    #anavbar5:hover {
        background-position: 0 -107px;
    }
    #anavbar5 span {
        display: none;
    }

    #anavbar6 {
        display: block;
        width: 144px; height: 107px;
        background: url("../GFX/slice6.png") no-repeat 0 0;
    }
    #anavbar6:hover {
        background-position: 0 -107px;
    }
    #anavbar6 span {
        display: none;
    }

    #anavbar7 {
        display: block;
        width: 111px; height: 107px;
        background: url("../GFX/slice7.png") no-repeat 0 0;
    }
    #anavbar7:hover {
        background-position: 0 -107px;
    }
    #anavbar7 span {
        display: none;
    }

    .dropdown1 {
        display:none;
       position: absolute;
       top:200px;
       background-color: #f9f9f9;
       min-width: 160px;
       box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
       z-index: 1;
    }

    #drop1 {
        position: absolute;
        width: 119px;
        height: 117px;
        z-index: 1;
        left: 634px;
        top: 115px;
        visibility: hidden;
        font-family: 'Source Sans Pro', sans-serif;
        font-size: 36px;
    }
    .hoverTable{
        width:100%; border-collapse:collapse;
    }
    .hoverTable td{
        padding:7px;
        border:#888888 1px solid;
    }
    .hoverTable tr{
        background: #444444;
        color:#EEE;
    }
    .hoverTable tr:hover {
        background-color:#294E7A
    }
</style>
<script type="text/javascript">
    div = {show: function(elem) {document.getElementById(elem).style.visibility = 'visible';},
    hide: function(elem) {document.getElementById(elem).style.visibility = 'hidden';}}
</script>
<table width="900" border="0" cellpadding="0" cellspacing="0" >
    <tr>
        <td width="98"><a id="anavbar0" ></a></td>
        <td onMouseOver="div.show('drop1')"  width="98" class="anavbar1"><a id="anavbar1" href="home.php" ></a></td>
        <td width="117"><a id="anavbar2" href="link1.php"></a></td>
        <td width="115"><a id="anavbar3" href="link2.php"></a></td>
        <td width="134"><a id="anavbar4" href="link3.php"></a></td>
        <td width="78"><a id="anavbar5" href="link4.php"></a></td>
        <td width="117"><a id="anavbar6" href="link5.php"></a></td>
        <td width="117"><a id="anavbar7" href="link6.php"></a></td>
    </tr>
</table>
<div id="drop1" >
    <table align="right" class="hoverTable">
        <tr>
            <td align="right">Text 1A</td>
        </tr>
        <tr>
            <td align="right">Text 2A</td>
        </tr>
        <tr>
            <td align="right">Text 3A</td>
        </tr>
    </table>
</div>
</code>```

答:
You see how this is 'mouseover'

```<code><td onMouseOver="div.show('drop1')" ...
</code>```

You need to add 'mouseout'

```<code><td onMouseOut="div.hide('drop1')" ...
</code>```

Which is in the js:

```<code><script type="text/javascript">
div = {show: function(elem) {document.getElementById(elem).style.visibility = 'visible';},
       hide: function(elem) {document.getElementById(elem).style.visibility = 'hidden';}}
</script>
</code>```

Body:
I am having a hard time of this... I have an existing navigation bar that uses a table (i know it would be better to use a UL tag but i'm editing a pre existing page so would rather not reinvent the wheel). I have a javascript snipped that shows a dropdown menu when you hover. However, i'm at a loss to figure out how in the world to make it disappear at the right time. As in... when you hover over anavbar1, the div is shown as expected. but then, how to make it hide after say a certain number of seconds, or as soon as another navbar dropdown is triggered (like a normal dropdown)? here is my entire code :

<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:600" rel="stylesheet">

            Text 1A

            Text 2A

            Text 3A

Body:
You see how this is 'mouseover'

<td onMouseOver="div.show('drop1')" ...

You need to add 'mouseout'

<td onMouseOut="div.hide('drop1')" ...

Which is in the js:

<script type="text/javascript">
div = {show: function(elem) {document.getElementById(elem).style.visibility = 'visible';},
       hide: function(elem) {document.getElementById(elem).style.visibility = 'hidden';}}
</script>


问:
Saving dictionary key values to a variable
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

```<code>def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)
</code>```

I want to save values of source_id, limit and research_id to a variable.

答:
Something like this should work</p>

```<code>def foo(**var2):
    for val in var2.values():
        print(val)
        # you can save the values to other variables here
</code>```

Body:
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)

I want to save values of source_id, limit and research_id to a variable.

Body:
Something like this should work

def foo(**var2):
    for val in var2.values():
        print(val)
        # you can save the values to other variables here


问:
how do i get gender from facebook public profile Facebook IOS Swift SDK
The reason why I need to get the gender of the Facebook user is because my app is only cater for women and by getting the gender of the user could solve a lot of the app problem.

The code

```<code>loginManager.logIn(readPermissions: [ .publicProfile, .email ], viewController: self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(_, _, let accessToken):

                if let userId = accessToken.userId {

                }

            }
        }
</code>```

The result that I get from the facebook server

```<code>["picture": {
    data =     {
        height = 200;
        "is_silhouette" = 1;
        url = "https://www.picture.com";
        width = 200;
    };
}, "last_name": Test, "email": test123@gmail.com, "id": 1234556, "first_name": Airsoft]
</code>```

I didn't get the gender of the user. How do I get the gender of the user?

Regards

答:
You can get these details using Graph api. Check this link https://developers.facebook.com/docs/graph-api/reference/user</p>

```<code>      let request = FBSDKGraphRequest(graphPath: "\(user-id)", parameters: ["fields" : "id,name,email,birthday,gender,hometown" ], httpMethod: "GET")
      request?.start(completionHandler: { (connection, result, error) in
        // Handle the result
      })
</code>```

Body:
The reason why I need to get the gender of the Facebook user is because my app is only cater for women and by getting the gender of the user could solve a lot of the app problem.

The code

loginManager.logIn(readPermissions: [ .publicProfile, .email ], viewController: self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(_, _, let accessToken):

                if let userId = accessToken.userId {

                }

            }
        }

The result that I get from the facebook server

["picture": {
    data =     {
        height = 200;
        "is_silhouette" = 1;
        url = "https://www.picture.com";
        width = 200;
    };
}, "last_name": Test, "email": test123@gmail.com, "id": 1234556, "first_name": Airsoft]

I didn't get the gender of the user. How do I get the gender of the user?

Regards

Body:
You can get these details using Graph api. Check this link https://developers.facebook.com/docs/graph-api/reference/user

      let request = FBSDKGraphRequest(graphPath: "\(user-id)", parameters: ["fields" : "id,name,email,birthday,gender,hometown" ], httpMethod: "GET")
      request?.start(completionHandler: { (connection, result, error) in
        // Handle the result
      })


问:
Primary key for a table where DATETIME col is used for almost all SELECT operations
I'm wondering what kind of PK I should be choosing for this table in MySQL. Almost all the SELECT operations will involve the DATETIME (date ranges, a specific date, etc.).

Is there a best practice for this?

答:
It's perfectly acceptable to use dates to form part of a composite primary key especially if you're using innodb and want to take advantage of clustered primary key indexes to gain maximum read performance.

have a look at the following:

http://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html

http://www.xaprb.com/blog/2006/07/04/how-to-exploit-mysql-index-optimizations/

MySQL script

Things to note:

innodb doesnt support auto_increment composite primary keys hence the use of the sequence table.

the auto_increment portion of the primary key just helps guarantee uniqueness - the outer part of the key is the important part i.e the date.

full script here: http://pastie.org/1475625 or continue reading...

```<code>drop table if exists foo_seq;
create table foo_seq
(
next_val int unsigned not null default 0
)
engine = innodb;

insert into foo_seq values (0);

drop table if exists foo;
create table foo
(
foo_date datetime not null,
foo_id int unsigned not null, -- auto inc field which just guarantees uniqueness
primary key (foo_date, foo_id) -- clustered composite PK (innodb only)
)
engine=innodb;

delimiter #
create trigger foo_before_ins_trig before insert on foo
for each row
begin
declare v_id int unsigned default 0;
    select next_val+1 into v_id from foo_seq;
    set new.foo_id = v_id;
    update foo_seq set next_val = v_id;
end#

delimiter ;
</code>```

Stats:

```<code>select count(*) as counter from foo; -- count(*) under innodb always slow
+---------+
| counter |
+---------+
| 2000000 |
+---------+

select min(foo_date) as min_foo_date from foo;
+---------------------+
| min_foo_date        |
+---------------------+
| 1782-11-21 16:32:00 |
+---------------------+
1 row in set (0.00 sec)

select max(foo_date) as max_foo_date from foo;
+---------------------+
| max_foo_date        |
+---------------------+
| 2011-01-18 23:06:04 |
+---------------------+
1 row in set (0.00 sec)

select count(*) as counter from foo where foo_date between
    '2009-01-01 00:00:00' and '2011-01-01 00:00:00';

+---------+
| counter |
+---------+
|   17520 |
+---------+
1 row in set (0.01 sec)

select * from foo where foo_date between
  '2009-01-01 00:00:00' and '2011-01-01 00:00:00' order by 1 desc limit 10;

+---------------------+--------+
| foo_date            | foo_id |
+---------------------+--------+
| 2010-12-31 23:06:04 |    433 |
| 2010-12-31 22:06:04 |    434 |
| 2010-12-31 21:06:04 |    435 |
| 2010-12-31 20:06:04 |    436 |
| 2010-12-31 19:06:04 |    437 |
| 2010-12-31 18:06:04 |    438 |
| 2010-12-31 17:06:04 |    439 |
| 2010-12-31 16:06:04 |    440 |
| 2010-12-31 15:06:04 |    441 |
| 2010-12-31 14:06:04 |    442 |
+---------------------+--------+
10 rows in set (0.00 sec)

explain
select * from foo where foo_date between
  '2009-01-01 00:00:00' and '2011-01-01 00:00:00' order by 1 desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  |rows  | Extra                    |
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
|  1 | SIMPLE      | foo   | range | PRIMARY       | PRIMARY | 8       | NULL |35308 | Using where; Using index |
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
1 row in set (0.00 sec)
</code>```

Pretty performant considering there are 2 million rows...

Hope this helps :)

ContentLicense: CC BY-SA 2.5

Body:
It's perfectly acceptable to use dates to form part of a composite primary key especially if you're using innodb and want to take advantage of clustered primary key indexes to gain maximum read performance.

have a look at the following:

http://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html

http://www.xaprb.com/blog/2006/07/04/how-to-exploit-mysql-index-optimizations/

MySQL script

Things to note:

innodb doesnt support auto_increment composite primary keys hence the use of the sequence table.

the auto_increment portion of the primary key just helps guarantee uniqueness - the outer part of the key is the important part i.e the date.

full script here: http://pastie.org/1475625 or continue reading...

drop table if exists foo_seq;
create table foo_seq
(
next_val int unsigned not null default 0
)
engine = innodb;

insert into foo_seq values (0);

drop table if exists foo;
create table foo
(
foo_date datetime not null,
foo_id int unsigned not null, -- auto inc field which just guarantees uniqueness
primary key (foo_date, foo_id) -- clustered composite PK (innodb only)
)
engine=innodb;

delimiter #
create trigger foo_before_ins_trig before insert on foo
for each row
begin
declare v_id int unsigned default 0;
    select next_val+1 into v_id from foo_seq;
    set new.foo_id = v_id;
    update foo_seq set next_val = v_id;
end#

delimiter ;

Stats:

select count(*) as counter from foo; -- count(*) under innodb always slow
+---------+
| counter |
+---------+
| 2000000 |
+---------+

select min(foo_date) as min_foo_date from foo;
+---------------------+
| min_foo_date        |
+---------------------+
| 1782-11-21 16:32:00 |
+---------------------+
1 row in set (0.00 sec)

select max(foo_date) as max_foo_date from foo;
+---------------------+
| max_foo_date        |
+---------------------+
| 2011-01-18 23:06:04 |
+---------------------+
1 row in set (0.00 sec)

select count(*) as counter from foo where foo_date between
    '2009-01-01 00:00:00' and '2011-01-01 00:00:00';

+---------+
| counter |
+---------+
|   17520 |
+---------+
1 row in set (0.01 sec)

select * from foo where foo_date between
  '2009-01-01 00:00:00' and '2011-01-01 00:00:00' order by 1 desc limit 10;

+---------------------+--------+
| foo_date            | foo_id |
+---------------------+--------+
| 2010-12-31 23:06:04 |    433 |
| 2010-12-31 22:06:04 |    434 |
| 2010-12-31 21:06:04 |    435 |
| 2010-12-31 20:06:04 |    436 |
| 2010-12-31 19:06:04 |    437 |
| 2010-12-31 18:06:04 |    438 |
| 2010-12-31 17:06:04 |    439 |
| 2010-12-31 16:06:04 |    440 |
| 2010-12-31 15:06:04 |    441 |
| 2010-12-31 14:06:04 |    442 |
+---------------------+--------+
10 rows in set (0.00 sec)

explain
select * from foo where foo_date between
  '2009-01-01 00:00:00' and '2011-01-01 00:00:00' order by 1 desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  |rows  | Extra                    |
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
|  1 | SIMPLE      | foo   | range | PRIMARY       | PRIMARY | 8       | NULL |35308 | Using where; Using index |
+----+-------------+-------+-------+---------------+---------+---------+------+-------+--------------------------+
1 row in set (0.00 sec)

Pretty performant considering there are 2 million rows...

Hope this helps :)


问:
Sort a 2D Array/Grid/Table of items in Javascript
I have an inventory of items in my game and the player will need to have the ability to auto-sort the items based on several criteria being name,quantity and type.

// create the Inventory grid
var InventoryWidth  = 2;
var InventoryHeight = 4;

var Inventory = new Array(InventoryWidth);
for (var i = 0; i < InventoryWidth; i++) {
 Inventory[i] = new Array(InventoryHeight);
}

// set the Items & default quantities
Inventory[0][0] = "Potion";
 Inventory[1][0] = 2;

Inventory[0][1] = "Elixir";
 Inventory[1][1] = 9;

Inventory[0][2] = "Antidote";
 Inventory[1][2] = 5;

Inventory[0][3] = "Ether";
 Inventory[1][3] = 1;

// function for sorting items
function Sort2D(array2D, byColumn, ascending) {

 // sort, seems I am using the wrong sorting function or my approach is wrong here:
  // not sure how to do ASC/DESC as well
 array2D.sort(function(a, b)
 {
  if(a[0] === b[0])
  {
   var x = a[byColumn].toLowerCase(), y = b[byColumn].toLowerCase();

   return x < y ? -1 : x > y ? 1 : 0;
  }
  return a[0] - b[0];
 });

}

// sort all rows by first column: "name", setting to 1 should compare and sort the quantities instead
Sort2D( Inventory, 0, true);

// print grid contents
var output = "";
for(var i = 0; i < InventoryHeight; i++) {

  if (i == 0) {
      output += " | name | own |";
    }

 for(var j = 0; j < InventoryWidth; j++) {

  if (j == 0) {
   output += "\n"+i+"|";
  }

  output+=Inventory[j][i];

  if (j >= Inventory[0].length-1) {
   output += "|\n";
  } else {
   output += ", ";
  }
 }
}
console.log(output);```

However I can't seem to figure out how to sort the grid like a table of items.
I'd need it to sort the row order by a chosen column and the ability to have it in ASC/DESC order. How would I go about this?

答:
To sort an array alphabetically, you just need to use the localeCompare method. Numbers have their own version and that can be confusing, so we coerce the variable before comparing it.

```<code>function sortAlphabetically(a, b) {
    return String(a).localeCompare(b);
}

["cat", "apple", "dog", "beef"].sort(sortAlphabetically);
// -> ["apple", "beef", "cat", "dog"]
</code>```

I think the main problem you're having is actually with the way you've created your array. At the moment, your array looks like this:

```<code>var inventory = [
    ["Potion", "Elixir", "Antidote", "Ether"],
    [2, 9, 5, 1]
];
</code>```

That means there's no association between "Potion" and 2, other than the array indicies. I think you'll have much better luck if you adjust the array to look like this.

```<code>var inventory = [
    ["Potion", 2],
    ["Elixir", 9],
    ["Antidote", 5],
    ["Ether", 1]
];
</code>```

Sorting that is much easier. As a bonus, running the .concat() method will clone the array before trying to sort it so the original data isn't modified and having the function return the data in ascending order by default is more conventional.

```<code>function sort2D(array, byColumn, isDescending) {

    var sorted = array.concat().sort(function (a, b) {

        return typeof a[byColumn] === "string"
            ? sortAlphabetically(a[byColumn], b[byColumn])
            : a[byColumn] - b[byColumn];

    });

    return isDescending
        ? sorted.reverse()
        : sorted;

}

sort2D(inventory, 0);
// -> [ ["Antidote", 5], ["Elixir", 9], ["Ether", 1], ["Potion", 2] ]
sort2D(inventory, 0, true);
// -> [ ["Potion", 2], ["Ether", 1], ["Elixir", 9], ["Antidote", 5] ]
sort2D(inventory, 1);
// -> [ ["Ether", 1], ["Potion", 2], ["Antidote", 5], ["Elixir", 9] ]
</code>```

I hope that helps.

Update:
Logging out your information becomes easier as well:

```<code>var output = inventory
    .map(function (inv) {
        return "| " + inv.join(" | ") + " |";
    })
    .join("\n");
console.log("| name | own |\n" + output);
</code>```

Update 2:
Here's how to sort the old data.

```<code>function sort2D(array, byColumn, isDescending) {

    // Step 1: sort the part of the array you're trying to sort.

    var preSort = array[byColumn].concat().sort(function (a, b) {

        return typeof a === "string"
            ? sortAlphabetically(a, b)
            : a - b;

    });

    if (isDescending) {
        preSort = preSort.reverse();
    }

    // Step 2: create a new, sorted array with your sorted column.

    var sorted = [];
    sorted[byColumn] = preSort;

    // Step 3: create a map to show how the array way sorted.

    var sortMap = {};
    preSort.forEach(function (item, i) {
        sortMap[array[byColumn].indexOf(item)] = i;
    });

    // Step 4: manually sort the other items of the array.

    array.forEach(function (info, i) {

        var copy = [];

        if (i !== byColumn) {

            info.forEach(function (item, j) {
                copy[sortMap[j]] = item;
            });

            sorted[i] = copy;

        }

    });

    // Step 5: return the newly sorted array.

    return sorted;

}
</code>```

Body:
I have an inventory of items in my game and the player will need to have the ability to auto-sort the items based on several criteria being name,quantity and type.

// create the Inventory grid
var InventoryWidth  = 2;
var InventoryHeight = 4;

var Inventory = new Array(InventoryWidth);
for (var i = 0; i < InventoryWidth; i++) {
 Inventory[i] = new Array(InventoryHeight);
}

// set the Items & default quantities
Inventory[0][0] = "Potion";
 Inventory[1][0] = 2;

Inventory[0][1] = "Elixir";
 Inventory[1][1] = 9;

Inventory[0][2] = "Antidote";
 Inventory[1][2] = 5;

Inventory[0][3] = "Ether";
 Inventory[1][3] = 1;

// function for sorting items
function Sort2D(array2D, byColumn, ascending) {

 // sort, seems I am using the wrong sorting function or my approach is wrong here:
  // not sure how to do ASC/DESC as well
 array2D.sort(function(a, b)
 {
  if(a[0] === b[0])
  {
   var x = a[byColumn].toLowerCase(), y = b[byColumn].toLowerCase();

   return x < y ? -1 : x > y ? 1 : 0;
  }
  return a[0] - b[0];
 });

}

// sort all rows by first column: "name", setting to 1 should compare and sort the quantities instead
Sort2D( Inventory, 0, true);

// print grid contents
var output = "";
for(var i = 0; i < InventoryHeight; i++) {

  if (i == 0) {
      output += " | name | own |";
    }

 for(var j = 0; j < InventoryWidth; j++) {

  if (j == 0) {
   output += "\n"+i+"|";
  }

  output+=Inventory[j][i];

  if (j >= Inventory[0].length-1) {
   output += "|\n";
  } else {
   output += ", ";
  }
 }
}
console.log(output);

However I can't seem to figure out how to sort the grid like a table of items.
I'd need it to sort the row order by a chosen column and the ability to have it in ASC/DESC order. How would I go about this?

Body:
To sort an array alphabetically, you just need to use the localeCompare method. Numbers have their own version and that can be confusing, so we coerce the variable before comparing it.

function sortAlphabetically(a, b) {
    return String(a).localeCompare(b);
}

["cat", "apple", "dog", "beef"].sort(sortAlphabetically);
// -> ["apple", "beef", "cat", "dog"]

I think the main problem you're having is actually with the way you've created your array. At the moment, your array looks like this:

var inventory = [
    ["Potion", "Elixir", "Antidote", "Ether"],
    [2, 9, 5, 1]
];

That means there's no association between "Potion" and 2, other than the array indicies. I think you'll have much better luck if you adjust the array to look like this.

var inventory = [
    ["Potion", 2],
    ["Elixir", 9],
    ["Antidote", 5],
    ["Ether", 1]
];

Sorting that is much easier. As a bonus, running the .concat() method will clone the array before trying to sort it so the original data isn't modified and having the function return the data in ascending order by default is more conventional.

function sort2D(array, byColumn, isDescending) {

    var sorted = array.concat().sort(function (a, b) {

        return typeof a[byColumn] === "string"
            ? sortAlphabetically(a[byColumn], b[byColumn])
            : a[byColumn] - b[byColumn];

    });

    return isDescending
        ? sorted.reverse()
        : sorted;

}

sort2D(inventory, 0);
// -> [ ["Antidote", 5], ["Elixir", 9], ["Ether", 1], ["Potion", 2] ]
sort2D(inventory, 0, true);
// -> [ ["Potion", 2], ["Ether", 1], ["Elixir", 9], ["Antidote", 5] ]
sort2D(inventory, 1);
// -> [ ["Ether", 1], ["Potion", 2], ["Antidote", 5], ["Elixir", 9] ]

I hope that helps.

Update:
Logging out your information becomes easier as well:

var output = inventory
    .map(function (inv) {
        return "| " + inv.join(" | ") + " |";
    })
    .join("\n");
console.log("| name | own |\n" + output);

Update 2:
Here's how to sort the old data.

function sort2D(array, byColumn, isDescending) {

    // Step 1: sort the part of the array you're trying to sort.

    var preSort = array[byColumn].concat().sort(function (a, b) {

        return typeof a === "string"
            ? sortAlphabetically(a, b)
            : a - b;

    });

    if (isDescending) {
        preSort = preSort.reverse();
    }

    // Step 2: create a new, sorted array with your sorted column.

    var sorted = [];
    sorted[byColumn] = preSort;

    // Step 3: create a map to show how the array way sorted.

    var sortMap = {};
    preSort.forEach(function (item, i) {
        sortMap[array[byColumn].indexOf(item)] = i;
    });

    // Step 4: manually sort the other items of the array.

    array.forEach(function (info, i) {

        var copy = [];

        if (i !== byColumn) {

            info.forEach(function (item, j) {
                copy[sortMap[j]] = item;
            });

            sorted[i] = copy;

        }

    });

    // Step 5: return the newly sorted array.

    return sorted;

}


问:
How this If statement compiles without any error?
When I was resolving merge conflicts, It appeared, that one of the conflict was automatically resolved by git in one of my code piece.

The code that rendered after merge conflict was:

```<code>if(condition1)
{
   //Statement 1

}
{
  //Statement 2

}
</code>```

The code compiled and ran without any error. Is the statement 2 code piece serving as else here? if yes, then what is the use of else keyword?

答: No the second {} is not a else statement but it just defines a scope ,did you try removing the braces and checking the output again?</p>

Body:
When I was resolving merge conflicts, It appeared, that one of the conflict was automatically resolved by git in one of my code piece.

The code that rendered after merge conflict was:

if(condition1)
{
   //Statement 1

}
{
  //Statement 2

}

The code compiled and ran without any error. Is the statement 2 code piece serving as else here? if yes, then what is the use of else keyword?


问:
How to compare Character for empty space
I need to check if a Character is a space, how do you do that?</p>

```<code>for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}
</code>```

答:
Depends on the kind of space you're looking for. For "normal" spaces (0x20) your code should work. But it won't evaluate to true for "special" spaces.

Given the following string, which contains different kind of spaces,

```<code>let myString = "This\u{0020}text contains normal spaces\u{00a0}and\u{00a0}non-breaking\u{00a0}ones"
</code>```

comparing to " " will result in finding 4 occurrences

```<code>let result1 = myString.enumerated().filter { $0.element == " " }

print(result1)
/*
   [(offset: 4, element: " "),
    (offset: 9, element: " "),
    (offset: 18, element: " "),
    (offset: 25, element: " ")]
*/
</code>```

But you can also use the whitespace CharacterSet. Be aware: this will evaluate to true for other whitespace-types (like newlines, tabs) as well.

```<code>let result2 = myString.unicodeScalars.enumerated().filter {
                  CharacterSet.whitespaces.contains($0.element)
              }

print(result2)
/*
    [(offset: 4, element: " "),
     (offset: 9, element: " "),
     (offset: 18, element: " "),
     (offset: 25, element: " "),
     (offset: 32, element: "\u{00A0}"),
     (offset: 36, element: "\u{00A0}"),
     (offset: 49, element: "\u{00A0}")]
*/
</code>```

Body:
I need to check if a Character is a space, how do you do that?

for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}

Body:
Depends on the kind of space you're looking for. For "normal" spaces (0x20) your code should work. But it won't evaluate to true for "special" spaces.

Given the following string, which contains different kind of spaces,

let myString = "This\u{0020}text contains normal spaces\u{00a0}and\u{00a0}non-breaking\u{00a0}ones"

comparing to " " will result in finding 4 occurrences

let result1 = myString.enumerated().filter { $0.element == " " }

print(result1)
/*
   [(offset: 4, element: " "),
    (offset: 9, element: " "),
    (offset: 18, element: " "),
    (offset: 25, element: " ")]
*/

But you can also use the whitespace CharacterSet. Be aware: this will evaluate to true for other whitespace-types (like newlines, tabs) as well.

let result2 = myString.unicodeScalars.enumerated().filter {
                  CharacterSet.whitespaces.contains($0.element)
              }

print(result2)
/*
    [(offset: 4, element: " "),
     (offset: 9, element: " "),
     (offset: 18, element: " "),
     (offset: 25, element: " "),
     (offset: 32, element: "\u{00A0}"),
     (offset: 36, element: "\u{00A0}"),
     (offset: 49, element: "\u{00A0}")]
*/


问:
Using variable number of float arguments
I'm trying to implement a flexible constructor for my struct Polynomial :

```<code>struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};
</code>```

The degree of the polynomial is variable.
What I would like is to have a constructor like

```<code>Polynomial(float... _coefficients);
</code>```

I've tried variadic template :

```<code>template<float... Args>
Polynomial(Args... args);
</code>```

But float is a non-type, so I've done :

```<code>template<typename... Args>
Polynomial(Args... args);
</code>```

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

```<code>Polynomial(size_t _degree, ...);
</code>```

But it is really unsafe.

At the moment I'm using :

```<code>Polynomial(std::vector<float>);
</code>```

But this force the call to be like :

```<code>Polynomial P({f1, f2, f3}); // with fn floats
</code>```

So I would like to know if there is a good way to do this.

Thank you !

答:
You have many options. You might want to look at the constructors of std::vector for inspiration. For example a templated constructor that takes two iterators is very flexible:

```<code>template<typename T>
Polynomial(T begin, T end) : coefficients(begin, end), degree(coefficients.size()) {}

auto init = std::vector<float>{2.0, 1.0, 4.0};
Polynomial p2{init.begin(), init.end()};
</code>```

Or you could take a std::initializer_list<float> as Jodocus suggested.

You could have a templated constructor that takes any container type:

```<code>template<typename T>
Polynomial(T container)
: coefficients(begin(container), end(container))
, degree(coefficients.size()) {}

auto init = std::vector<float>{2.0, 1.0, 4.0};
Polynomial p2{init};
</code>```

Live demo.

Or you could provide a combination of different constructors to suit different needs.

Body:
I'm trying to implement a flexible constructor for my struct Polynomial :

struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};

The degree of the polynomial is variable.
What I would like is to have a constructor like

Polynomial(float... _coefficients);

I've tried variadic template :

template<float... Args>
Polynomial(Args... args);

But float is a non-type, so I've done :

template<typename... Args>
Polynomial(Args... args);

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

Polynomial(size_t _degree, ...);

But it is really unsafe.

At the moment I'm using :

Polynomial(std::vector<float>);

But this force the call to be like :

Polynomial P({f1, f2, f3}); // with fn floats

So I would like to know if there is a good way to do this.

Thank you !

Body:
You have many options. You might want to look at the constructors of std::vector for inspiration. For example a templated constructor that takes two iterators is very flexible:

template<typename T>
Polynomial(T begin, T end) : coefficients(begin, end), degree(coefficients.size()) {}

auto init = std::vector<float>{2.0, 1.0, 4.0};
Polynomial p2{init.begin(), init.end()};

Or you could take a std::initializer_list<float> as Jodocus suggested.

You could have a templated constructor that takes any container type:

template<typename T>
Polynomial(T container)
: coefficients(begin(container), end(container))
, degree(coefficients.size()) {}

auto init = std::vector<float>{2.0, 1.0, 4.0};
Polynomial p2{init};

Live demo.

Or you could provide a combination of different constructors to suit different needs.


问:
Is there a simple way to repeat a php mysql query?
I'm hoping there's a little trick to php that will save me 100's of copy>paste>change-number - thanks for taking a look!

I've got a relatively large dataset in a MySQL db.

There are just two columns: Models (about 7000 unique entries) and Manufacturers (about 100 unique ones, i.e. the models are from just 100 different manufacturers)

At the moment (well, as I am writing the very slow, repetitious way), I have a huge list of PHP database queries along the lines of:

$result = mysql_query("SELECT * FROM products WHERE manufacturer ='3M'" );

  while ($row = mysql_fetch_array($result)) {

  echo $row['manufacturer'] . " " . $row['model']; }

What I'm doing is working, but is there perhaps a way of getting a list of all manufacturers then running the php above on the list?

Or maybe something different I haven't thought about?

Thanks heaps,

(The actual outputting is done into a javascript accordian - so displaying it on a single page isn't an issue)

答:
If you want to fetch all the results from you database with 1 query, you can simply fetch all without a where clause and ordering by manufacturer, so you can "group" the rows in php. I understand this is you want, you should paginate anyway. </p>

```<code>$result = mysql_query("SELECT * FROM products ORDER BY manufacturer ASC;" );

$last_manufacturer = false;

while ($row = mysql_fetch_array($result)) {

if ($last_manufacturer !== $row['manufacturer']) {
 //we got a different manufacturer since we ordered in alphabetical order
    $last_manufacturer = $row['manufacturer'];
    #... do something like put an separator between manufacturers
    # in this example we put a title, you should put the accordion markup or something similar
    echo "<h1> Manufacturer:", $row['manufacturer']  ,"</h1>";

}
echo $row['manufacturer'] . " " . $row['model'];

}
</code>```

Body:
If you want to fetch all the results from you database with 1 query, you can simply fetch all without a where clause and ordering by manufacturer, so you can "group" the rows in php. I understand this is you want, you should paginate anyway.

$result = mysql_query("SELECT * FROM products ORDER BY manufacturer ASC;" );

$last_manufacturer = false;

while ($row = mysql_fetch_array($result)) {

if ($last_manufacturer !== $row['manufacturer']) {
 //we got a different manufacturer since we ordered in alphabetical order
    $last_manufacturer = $row['manufacturer'];
    #... do something like put an separator between manufacturers
    # in this example we put a title, you should put the accordion markup or something similar
    echo "<h1> Manufacturer:", $row['manufacturer']  ,"</h1>";

}
echo $row['manufacturer'] . " " . $row['model'];

}


问:
VBA String to Integer without rounding
I want to convert a String into Integer and keep the decimal places.

I tried multiple things like Foramat and CInt but all of them end up rounding my value.

My Code is:

```<code>Dim posZ As Integer
Dim TestZ As Integer
Dim strTestZ As String
Dim TestZold As Integer

For i = 1 To tllength
  posZ = InStr(tlmold(i), "Z=")
  strTestZ = Mid(tlmold(i), posZ + 2, 5)

  TestZ = Format(strTestZ, "0.0000")

   If TestZold = TestZ Or (TestZold - TestZ) > 0.02 Or (TestZ - TestZold) > 0.02 Then
   countLip = countLip + 1
   End If
 TestZold = TestZ
Next I
</code>```

e.g. the first value of strTestZ in the array tlmold() would be 0.085, 2nd would be 0.097.

And I want to compare them..

Thanks in Advance

答: Integer is a whole number variable. Use double instead.</p>

Title: VBA String to Integer without rounding

Body:
I want to convert a String into Integer and keep the decimal places.

I tried multiple things like Foramat and CInt but all of them end up rounding my value.

My Code is:

Dim posZ As Integer
Dim TestZ As Integer
Dim strTestZ As String
Dim TestZold As Integer

For i = 1 To tllength
  posZ = InStr(tlmold(i), "Z=")
  strTestZ = Mid(tlmold(i), posZ + 2, 5)

  TestZ = Format(strTestZ, "0.0000")

   If TestZold = TestZ Or (TestZold - TestZ) > 0.02 Or (TestZ - TestZold) > 0.02 Then
   countLip = countLip + 1
   End If
 TestZold = TestZ
Next I

e.g. the first value of strTestZ in the array tlmold() would be 0.085, 2nd would be 0.097.

And I want to compare them..

Thanks in Advance


问:
Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2
I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.

now I am trying to open a read stream from the blob and send it directly to the client.

```<code> [HttpGet]
 [ResponseType(typeof(HttpResponseMessage))]
 public async Task<HttpResponseMessage> DownloadAsync(string file)
 {
     HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
     var stream = await blob.OpenReadAsync("container", file);
     result.Content = new StreamContent(stream);
     return result;
 }
</code>```

The file is downloaded correctly, but the problem is: The code download the complete stream in the client, then the client sees the downloaded file.

I wanted the client to see the file as being downloaded, so the user knows that he is downloading something. Not just blocking the request and wait till it finished.

I am using FileSaver in Angular2:

```<code>this.controller.download('data.zip').subscribe(
      data => {
        FileSaver.saveAs(data, 'data.zip');
      });
</code>```

Has anybody an idea how to fix it?

Thank you!

答:
To fix it you'd need to use the following javascript code instead:

```<code>var fileUri = "http://localhost:56676/api/blobfile";  //replace with your web api endpoint
var link = document.createElement('a');
document.body.appendChild(link);
link.href = fileUri;
link.click();
</code>```

And then in your backend, make it like so:

```<code>HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "data.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
</code>```

Body:
I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.

now I am trying to open a read stream from the blob and send it directly to the client.

 [HttpGet]
 [ResponseType(typeof(HttpResponseMessage))]
 public async Task<HttpResponseMessage> DownloadAsync(string file)
 {
     HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
     var stream = await blob.OpenReadAsync("container", file);
     result.Content = new StreamContent(stream);
     return result;
 }

The file is downloaded correctly, but the problem is: The code download the complete stream in the client, then the client sees the downloaded file.

I wanted the client to see the file as being downloaded, so the user knows that he is downloading something. Not just blocking the request and wait till it finished.

I am using FileSaver in Angular2:

this.controller.download('data.zip').subscribe(
      data => {
        FileSaver.saveAs(data, 'data.zip');
      });

Has anybody an idea how to fix it?

Thank you!

Body:
To fix it you'd need to use the following javascript code instead:

var fileUri = "http://localhost:56676/api/blobfile";  //replace with your web api endpoint
var link = document.createElement('a');
document.body.appendChild(link);
link.href = fileUri;
link.click();

And then in your backend, make it like so:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "data.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;


问:
Make IFrames resizable dynamically
I have the following HTML page in which I have three iframes. I would like to allow users to resize the height and width of the iframes manually using Javascript.</p>

```<code><body>
<table>
    <tr>
        <td colspan="2" id = "freebase_td">
        <iframe id = "freebase_frame" src="" width="100%" height="400px"></iframe>
        </td>
    </tr>
    <tr>
        <td align="left" id = "wiki_td">
        <iframe id = "wiki_frame" src="" width="100%" height="400px"></iframe>
        </td>
        <td align="right" id = "imdb_td">
        <iframe id = "imdb_frame" src="" width="100%" height="400px"></iframe>
        </td>
    </tr>
</table>
</body>
</code>```

答:
you don't need javascript for that in modern browsers. just a little html+css trick. encapsulate your iframe in a div with resize property enabled.

```<code><div>
  <iframe src="https://www.example.com/"></iframe>
</div>

<style>
div {
  overflow: hidden;
  resize: both;
}
iframe {
  height: 100%;
  width: 100%;
  border: none;
}
</style>
</code>```

demo: https://jsfiddle.net/k53a41ej/

Title: Make IFrames resizable dynamically

Body:
you don't need javascript for that in modern browsers. just a little html+css trick. encapsulate your iframe in a div with resize property enabled.

<div>
  <iframe src="https://www.example.com/"></iframe>
</div>

<style>
div {
  overflow: hidden;
  resize: both;
}
iframe {
  height: 100%;
  width: 100%;
  border: none;
}
</style>

demo: https://jsfiddle.net/k53a41ej/

ContentLicense: CC BY-SA 4.0


问:
How to make a rest post call from ReactJS code?
I am new to ReactJS and UI and I wanted to know how to make a simple REST based POST call from ReactJS code.

If there is any example present it would be really helpful.

答:
Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests

```<code>axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

Body:
Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


问:
iPhone + UITableView + row height
I am setting the row height of my UITableView using following code

```<code>[tableView setRowHeight: 100.00];
</code>```

I am using the single line as separator in the UITableView.

Eventhough setting the height above, height of row does not get change.

答:
You should avoid the heightForRowAtIndexPath if all your rows are of similar height and use the rowHeight property. According to the documentation:

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

In the UITableViewController subclass it could be done, for instance, in the viewDidAppear method (the UITableViewController has a reference to the tableView):

```<code>self.tableView.rowHeight = 79.f;
</code>```

Title: iPhone + UITableView + row height

Body:
I am setting the row height of my UITableView using following code

[tableView setRowHeight: 100.00];

I am using the single line as separator in the UITableView.

Eventhough setting the height above, height of row does not get change.

Body:
You should avoid the heightForRowAtIndexPath if all your rows are of similar height and use the rowHeight property. According to the documentation:

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

In the UITableViewController subclass it could be done, for instance, in the viewDidAppear method (the UITableViewController has a reference to the tableView):

self.tableView.rowHeight = 79.f;


问:
How can I Update value of key In JSON Object?
I am using _underscore. I want to rename value of particular key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

In above output in console.log(index), I want to edit value of key(name), meaning add karmal-Copy.

Desired output

```<code>{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}
</code>```

I want only add -Copy with key(name) value.

答:
You could just update the found object.

var users = [{ _id: { $oid: "3426" }, name: "peeter" }, { _id: { $oid: "5a027" }, name:"ken" }, { _id: { $oid: "5999" }, name: "karmal" }],
    item = _.find(users, function(o) { return o._id.$oid == '5999'; });

if (item) {               // check if item exists
    item.name += '-Copy'; // update property
}
console.log(users);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Body:
I am using _underscore. I want to rename value of particular key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);

In above output in console.log(index), I want to edit value of key(name), meaning add karmal-Copy.

Desired output

{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}

I want only add -Copy with key(name) value.

Body:
You could just update the found object.

var users = [{ _id: { $oid: "3426" }, name: "peeter" }, { _id: { $oid: "5a027" }, name:"ken" }, { _id: { $oid: "5999" }, name: "karmal" }],
    item = _.find(users, function(o) { return o._id.$oid == '5999'; });

if (item) {               // check if item exists
    item.name += '-Copy'; // update property
}
console.log(users);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
inlining spread operator during declaration es2018
I want to do something like this:

```<code>const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    uk: {
        ...ru
    }
}
</code>```

obviously it doesn't work, of course, I can set another const, and then use it but I'm lazy ) so I'm curious if javascript allows you to do so?

答:
You can't self reference in objects unless it's a method.

You could do:

```<code>const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    get uk () {
        return this.ru
    }
}
</code>```

Edit

If you want intending for translations.uk to not be a copy of ru and hold it's own data this way won't work. This just sets up translations.uk as a reference to translations.ru

Body:
I want to do something like this:

const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    uk: {
        ...ru
    }
}

obviously it doesn't work, of course, I can set another const, and then use it but I'm lazy ) so I'm curious if javascript allows you to do so?

Body:
You can't self reference in objects unless it's a method.

You could do:

const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    get uk () {
        return this.ru
    }
}

Edit

If you want intending for translations.uk to not be a copy of ru and hold it's own data this way won't work. This just sets up translations.uk as a reference to translations.ru


答:
Try this: </p>

```<code>for(var i = 0; i < users.length; i++) {
    if(users[i]._id.$oid == 5999) {
        users[i].name += "-Copy";
    }
}
</code>```

Title: How can I Update value of key In JSON Object?

Body:
Try this:

for(var i = 0; i < users.length; i++) {
    if(users[i]._id.$oid == 5999) {
        users[i].name += "-Copy";
    }
}


问:
How to call the controller when changing tab in tabbarcontroller? (Swift)
I have a search tab in the tab bar controller and a songs controller. I would like to jump to search tab when user click into one of the button in the songs controller and start searching. I am using this code to change tab

```<code> self.tabBarController?.selectedIndex = 0
</code>```

this above code works but i would like to call the search function in the search tab when changing tabs.

答:
You will be notified implementing the UITabBarControllerDelegate protocol in your ViewControllers

You need add this line in your viewDidLoad for your viewControllers

```<code>self.tabBarController?.delegate = self
</code>```

and implementing this method of UITabBarControllerDelegate protocol

```<code>public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)
</code>```

You will be notified when a new viewController is selected in your tabBarController

Body:
I have a search tab in the tab bar controller and a songs controller. I would like to jump to search tab when user click into one of the button in the songs controller and start searching. I am using this code to change tab

 self.tabBarController?.selectedIndex = 0

this above code works but i would like to call the search function in the search tab when changing tabs.

Body:
You will be notified implementing the UITabBarControllerDelegate protocol in your ViewControllers

You need add this line in your viewDidLoad for your viewControllers

self.tabBarController?.delegate = self

and implementing this method of UITabBarControllerDelegate protocol

public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)

You will be notified when a new viewController is selected in your tabBarController


问:
Tensorflow graph building mechanism
When I tried to understand the underlying mechanism of the following tensorflow graph building code, I was confused about 3rd and 4th lines. I assumed that in side the +operator overloading , adder_node builds references to both a and b. However when the adder_node is executed on line 4, what would be the mechanism to distinguish  a(a: 3) and b(b:3). Lets say, if the placeholders are filled with values and if the adder_node has references to both a,b  why do we have to pass these parameters again.</p>

```<code>a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b
print(sess.run(adder_node, {a: 3, b: 4.5}))
</code>```

答:
The a, b, and adder_node are nodes in a graph.

The adder_node knows to take the values inside a and b and to perform an operation on them. The graph looks like this:

When you perform sess.run(adder_node) you're telling tensorflow to evaluate the value of adder_node (aka to perform all the dependent operations and perform the operation of adder_node).

In order to calculate adder_node tf will calculate the value of a and b, which are placeholders, so their operation is to take the values from the feed_dict. So, every time you need to compute adder_node you will have to provide values for the placeholders, so they can get computed.

{a: 3, b: 4.5} is not specifically passing parameters to adder_node but passing parameters to the graph.

You can have this code which passes a, b, and c as parameters to the graph, and adder_node add z an c:

```<code>a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
c = tf.placeholder(tf.float32)
z = a + b
adder_node = z + c
print(sess.run(adder_node, {a: 3, b: 4.5, c: 1.5}))
</code>```

Title: Tensorflow graph building mechanism

Body:
When I tried to understand the underlying mechanism of the following tensorflow graph building code, I was confused about 3rd and 4th lines. I assumed that in side the +operator overloading , adder_node builds references to both a and b. However when the adder_node is executed on line 4, what would be the mechanism to distinguish  a(a: 3) and b(b:3). Lets say, if the placeholders are filled with values and if the adder_node has references to both a,b  why do we have to pass these parameters again.

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b
print(sess.run(adder_node, {a: 3, b: 4.5}))

Body:
The a, b, and adder_node are nodes in a graph.

The adder_node knows to take the values inside a and b and to perform an operation on them. The graph looks like this:

When you perform sess.run(adder_node) you're telling tensorflow to evaluate the value of adder_node (aka to perform all the dependent operations and perform the operation of adder_node).

In order to calculate adder_node tf will calculate the value of a and b, which are placeholders, so their operation is to take the values from the feed_dict. So, every time you need to compute adder_node you will have to provide values for the placeholders, so they can get computed.

{a: 3, b: 4.5} is not specifically passing parameters to adder_node but passing parameters to the graph.

You can have this code which passes a, b, and c as parameters to the graph, and adder_node add z an c:

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
c = tf.placeholder(tf.float32)
z = a + b
adder_node = z + c
print(sess.run(adder_node, {a: 3, b: 4.5, c: 1.5}))


问:
i'am Getting This error. Conversion failed when converting the nvarchar value '- Select -' to data type int. My Code Is Given below
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

```<code> protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }
</code>```

答:
Error caught in stored procedure That A Line Notnull was null Thats why Iam Geting that Error
I Check Table and fixed It</p>

Body:
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }


问:
How to install an iphone test app from a local server?
Something like a week or two ago I read an article (either from Stackoverflow, Mashable, HackerNews or some other tech site) which described how to upload an iphone app to one's server and then to install it directly to your iphone by navigating to the server's address or something like that. I remember the author mentioning that it was way easier than having the iphone plugged into the mac all the time to test the app. I don't remember the iphone needing to be jailbreaked or anything.

Does it ring any bell to anyone? I can't check my browser history since I had to reinstall my OS...

答: This example uses php, but the HTML is transportable. Highly recommended. Note however that doing so might require an Enterprise Dev Center account (we used one for this).</p>


问:
Underline two letters separately
Is there a way to have non-continuous underline? I want the underline stop and restart (and see that visually) where I closed and reopened the  tags..

W. Raven, “al-Washshaʾ”```

答:
.underline {
  text-decoration:underline;
  padding-left:2px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>W. Raven, “al-Wa<span class="underline">sh</span><span class="underline">sh</span>aʾ”</code>```

Title: Underline two letters separately

Body:
.underline {
  text-decoration:underline;
  padding-left:2px;
  }

W. Raven, “al-Wa<span class="underline">sh</span><span class="underline">sh</span>aʾ”


问:
Configure the Db dynamically based on the request using spring bo
I am creating a application using spring boot. In this there will be a master db where all the users details and some other tables will exists. Now while am requesting to create  a user to the application using the webservice  its checks is the user exists in the MasterDb( user Table) or not.
if exists the eg: "Google" user in the master database table. Then the application need to connect to the "Google" db and get the requested data. else it will create a "Google" db and its table using jdbc and it had to connect to  the Google db when next request comes with the "google" db name.</p>

答:
A few points before getting started here:

It is generally considered a bad idea to have multiple databases in an application. Its better to have one database with multiple tables.

In your case, you should be having one single database, with multiple tables for each of the users. Basically, one table for keeping track if the user exists or not, and then one table for each user that exists.

One big issue with your approach of multiple databases is the database configuration management. Suppose, if you have 1000 users, you will have to manage 1000 configuration in your application. Instead, having one database configuration and multiple tables is more manageable. There is a high chance of your application design being flawed if you're trying to create and manage hundereds of database configuration.

Based on the information provided in the question and comments, you can look into using JDBCTemplate in your Spring App. You can configure multiple data sources based on given dynamic parameters and thus connect to multiple databases. Check Spring MVC with JDBC Template. However, you will need to tweak the code given in this tutorial to fit multiple data sources within your app.


问:
Update all local workspaces with changes to a folder in my project collection
I have a folder with name "OutputBinaries" inside my project collection. I have local workspaces mapped to this folder on multiple machines. I want to automatically update all these local workspaces whenever there are any modification to "OutputBinaries" folder.

I know tf get command can help if it is specific to a particular machine or a particular workspace. But how this can be accomplished with workspaces on different machines

We are on the latest TFS version

答:
Firstly, as Daniel mentioned above:

"Binary outputs should not be stored in source control. If they are
  dependencies for applications, you should either manage them as NuGet
  packages or include them as project references."

For you specific question,  we can only run the tf get command in particular workspace on the specific machine.

To update all local workspaces you can try to create a batch script with tf get command. Then run it periodically on each machine. You can set that with Windows Task Scheduler, see How to schedule a Batch File to run automatically in Windows for details.

Also this thread for your reference : Run a task every x-minutes with Windows Task Scheduler


问:
Django: Print url of view without hardcoding the url
Can i print out a url /admin/manage/products/add of a certain view in a template?

Here is the rule i want to create a link for

```<code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
</code>```

I would like to have /manage/products/add in a template without hardcoding it. How can i do this?

Edit: I am not using the default admin (well, i am but it is at another url), this is my own

答:
You can use get_absolute_url, but that will only work for a particular object.  Since your object hasn't been created yet, it won't work in this case.

You want to use named URL patterns.  Here's a quick intro:

Change the line in your urls.py to:

```<code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),
</code>```

Then, in your template you use this to display the URL:

```<code>{% url create-product %}
</code>```

If you're using Django 1.5 or higher you need this:

```<code>{% url 'create-product' %}
</code>```

You can do some more powerful things with named URL patterns, they're very handy.  Note that they are only in the development version (and also 1.0).

OwnerDisplayName: joshhunt

Body:
Can i print out a url /admin/manage/products/add of a certain view in a template?

Here is the rule i want to create a link for

(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),

I would like to have /manage/products/add in a template without hardcoding it. How can i do this?

Edit: I am not using the default admin (well, i am but it is at another url), this is my own

LastEditorDisplayName: joshhunt

Body:
You can use get_absolute_url, but that will only work for a particular object.  Since your object hasn't been created yet, it won't work in this case.

You want to use named URL patterns.  Here's a quick intro:

Change the line in your urls.py to:

(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),

Then, in your template you use this to display the URL:

{% url create-product %}

If you're using Django 1.5 or higher you need this:

{% url 'create-product' %}

You can do some more powerful things with named URL patterns, they're very handy.  Note that they are only in the development version (and also 1.0).

OwnerDisplayName: Harley


问:
Guaranteed file deletion upon program termination (C/C++)
Win32's CreateFile has FILE_FLAG_DELETE_ON_CLOSE, but I'm on Linux.

I want to open a temporary file which will always be deleted upon program termination.  I could understand that in the case of a program crash it may not be practical to guarantee this, but in any other case I'd like it to work.

I know about RAII.  I know about signals.  I know about atexit(3).  I know I can open the file and delete it immediately and the file will remain accessible until the file descriptor is closed (which even handles a crash).  None of these seem like a complete and straightforward solution:

RAII: been there, done that: I have an object whose destructor deletes the file, but the destructor is not called if the program is terminated by a signal.

signals: I'm writing a low-level library which makes registering a signal handler a tricky proposition.  For example, what if the application uses signals itself?  I don't want to step on any toes.  I might consider some clever use of sigaction(2) to cope...but haven't put enough thought into this possibility yet.

atexit(3): apparently useless, since it isn't called during abnormal termination (e.g. via a signal).

preemptive unlink(2): this is pretty good except that I need the file to remain visible in the filesystem (otherwise the system is harder to monitor/troubleshoot).

What would you do here?

Further Explanation

I elided one detail in my original post which I now realize I should have included.  The "file" in this case is not strictly a normal file, but rather is a POSIX Message Queue.  I create it via mq_open().  It can be closed via mq_close() or close() (the former is an alias for the latter on my system).  It can be removed from the system via mq_unlink().  All of this makes it analogous to a regular file, except that I cannot choose the directory in which the file resides.  This makes the current most popular answer (placing the file in /tmp) unworkable, because the "file" is created by the system in a virtual filesystem with very limited capacity.  (I've mounted the virtual filesystem in /dev/mqueue, following the example in man mq_overview) .

This also explains why I need the name to remain visible (making the immediate-unlink approach unworkable): the "file" must be shared between two or more processes.

答:
Maybe someone suggested this already, but I'm unable to spot it, given all your requirements, the best I can think of is to have the filename somehow communicated to a parent process, such as a start-script, which will clean up after the process dies, had it failed to do so. This is perhaps mostly known as a watchdog, but then with the more common use case added to kill and/or restart the process when it somehow fails.

If your parent process dies as well, you're pretty much out of luck, but most script environments are fairly robust and rarely die unless the script is broken, which is often easier to keep correct than a program.

OwnerDisplayName: John Zwinck

LastEditorDisplayName: John Zwinck

OwnerDisplayName: roe


问:
How to set Robots.txt or Apache to allow crawlers only at certain hours?
As traffic is distributed unevenly over 24 hours, I would like to disallow crawlers during peek hours and allow them at non-busy hours.

Is there a method to achieve this?

edit:
thanks for all the good advice.

This is another solution we found.

2bits.com has an article on setting IPTables firewall to limit the number of connections from certain IP addresses.

the article

the setting of IPTables:

Using connlimit

In newer Linux kernels, there is a connlimit module for iptables. It can be used like this:

iptables -I INPUT -p tcp -m connlimit --connlimit-above 5 -j REJECT

This limits connections from each IP address to no more than 5 simultaneous connections. This sort of "rations" connections, and prevents crawlers from hitting the site simultaneously.
*

答: I don't think you can make an appointment with a search engine spider.</p>


问:
How this If statement compiles without any error?
When I was resolving merge conflicts, It appeared, that one of the conflict was automatically resolved by git in one of my code piece.

The code that rendered after merge conflict was:

```<code>if(condition1)
{
   //Statement 1

}
{
  //Statement 2

}
</code>```

The code compiled and ran without any error. Is the statement 2 code piece serving as else here? if yes, then what is the use of else keyword?

答:
What you've got is an if statement followed by a block statement. The block statement introduces a new scope. They're two separate constructs.

It's often useful to introduce a block statement if you want to limit the lifetime of an object within your code. For example, you might only want to acquire a lock for a part of a function:

```<code>void DoSomething()
{
  // Stuff
  // Stuff
  // Stuff

  {
    Lock lock(mutex);
  }

  // Stuff
  // Stuff
  // Stuff
}
</code>```

Body:
When I was resolving merge conflicts, It appeared, that one of the conflict was automatically resolved by git in one of my code piece.

The code that rendered after merge conflict was:

if(condition1)
{
   //Statement 1

}
{
  //Statement 2

}

The code compiled and ran without any error. Is the statement 2 code piece serving as else here? if yes, then what is the use of else keyword?

Body:
What you've got is an if statement followed by a block statement. The block statement introduces a new scope. They're two separate constructs.

It's often useful to introduce a block statement if you want to limit the lifetime of an object within your code. For example, you might only want to acquire a lock for a part of a function:

void DoSomething()
{
  // Stuff
  // Stuff
  // Stuff

  {
    Lock lock(mutex);
  }

  // Stuff
  // Stuff
  // Stuff
}


问:
Doctrine query builder find by interests
today i have an interest task - realize search on DB by some groups and sort it by most relevant criteria

We have 2 entities (User and Interests) on Symfony with ManyToMany relation

We need create query for find users which have most similar interests
ex:

user1 have interests [1,2,3,4,5]

user2 have interests [1,2,4,5,7]

user3 have interests [3,5]

we try find user with interests [2,6,7] and result must be:

```<code>[user2, user1, user0]

user2 - 2 similar interests

user1 - 1 similar interests

user3 - 0
</code>```

Code example:

```<code>class User
{
    // ...

    /**
     * Many Users have Many Interests.
     * @ManyToMany(targetEntity="Interest")
     * @JoinTable(name="users_interests",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="interest_id", referencedColumnName="id")}
     *      )
     */
    private $interests;
...
</code>```

I have no idea how to organize it nicely, can somebody help me?
Thanks!

答:
I suggest you to use simple sql (not DQL) in order to extract only the id of the user that match the criteria.
A simple query could be:

```<code>select distinct user_id, count(*) from users_interests
where interest_id in (1,3,5) --- your interest ids
group by 1
order by 2 DESC;
</code>```

Hope this help

Body:
today i have an interest task - realize search on DB by some groups and sort it by most relevant criteria

We have 2 entities (User and Interests) on Symfony with ManyToMany relation

We need create query for find users which have most similar interests
ex:

user1 have interests [1,2,3,4,5]

user2 have interests [1,2,4,5,7]

user3 have interests [3,5]

we try find user with interests [2,6,7] and result must be:

[user2, user1, user0]

user2 - 2 similar interests

user1 - 1 similar interests

user3 - 0

Code example:

class User
{
    // ...

    /**
     * Many Users have Many Interests.
     * @ManyToMany(targetEntity="Interest")
     * @JoinTable(name="users_interests",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="interest_id", referencedColumnName="id")}
     *      )
     */
    private $interests;
...

I have no idea how to organize it nicely, can somebody help me?
Thanks!

Body:
I suggest you to use simple sql (not DQL) in order to extract only the id of the user that match the criteria.
A simple query could be:

select distinct user_id, count(*) from users_interests
where interest_id in (1,3,5) --- your interest ids
group by 1
order by 2 DESC;

Hope this help


答:
Here you go:

var users = [
  {"_id":{"$oid":"3426"},
  "name":"peeter"
  },
  {"_id":{"$oid":"5a027"},
  "name":"ken"
  },
  {"_id":{"$oid":"5999"},
  "name":"karmal"
  }
];

var index = _.find(users, function(o) {
    if(o._id.$oid == '5999'){
      o.name += '-Copy';
      return o._id.$oid == '5999';
    }
  });

console.log(index);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Body:
I am using _underscore. I want to rename value of particular key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);

In above output in console.log(index), I want to edit value of key(name), meaning add karmal-Copy.

Desired output

{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}

I want only add -Copy with key(name) value.

Body:
Here you go:

var users = [
  {"_id":{"$oid":"3426"},
  "name":"peeter"
  },
  {"_id":{"$oid":"5a027"},
  "name":"ken"
  },
  {"_id":{"$oid":"5999"},
  "name":"karmal"
  }
];

var index = _.find(users, function(o) {
    if(o._id.$oid == '5999'){
      o.name += '-Copy';
      return o._id.$oid == '5999';
    }
  });

console.log(index);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
Chart.js tooltip yAlign
Tooltip don't want be at the bottom.
I tried:

```<code>  Chart.defaults.global.tooltips.yAlign = 'bottom';
</code>```

and

```<code> options = {
     tooltips: {
          yAlign: 'bottom'
     },
</code>```

Did not help

答: It is works fine! But counting is from the top face of the bar! </p>

Title: Chart.js tooltip yAlign

Body:
Tooltip don't want be at the bottom.
I tried:

  Chart.defaults.global.tooltips.yAlign = 'bottom';

and

 options = {
     tooltips: {
          yAlign: 'bottom'
     },

Did not help


问:
Excel autosize text to fit shape
I want to add some VBA to a multiple chart template to autosize  title text to fit textbox. This now runs, but doesn't make any changes to text box ...</p>

```<code>Sub TextBox()

Dim ws As Worksheet
Dim shp As Shape

' loop through sheets in this workbook
 For Each ws In ThisWorkbook.Worksheets
 ' loop through Chartobjects in sheet
   For Each shp In ws.Shapes

    If shp.Type = msoTextBox Then
        With shp.TextFrame2
            strTxt = .TextRange
            .DeleteText
            .WarpFormat = msoWarpFormat1
            .WordWrap = True
            .AutoSize = msoAutoSizeTextToFitShape
            .TextRange = strTxt
        End With
    End If
   Next shp
  Next ws

End Sub
</code>```

答:
You are looping through the all the textbox in the sheets but if your textbox is on chartobject you need to handle it in a slightly different.</p>

```<code>Sub TextBox()

    Dim w As Worksheet
    Dim c As ChartObject
    Dim s As Shape

    For Each w In ActiveWorkbook.Worksheets
        For Each c In w.ChartObjects
            For Each s In c.Chart.Shapes
                If s.Type = msoTextBox Then
                    With s.TextFrame2
                        strTxt = .TextRange
                        .DeleteText
                        .WarpFormat = msoWarpFormat1
                        .WordWrap = True
                        .AutoSize = msoAutoSizeTextToFitShape
                        .TextRange = strTxt
                        .TextRange.Font.Name = "Calibri"
                        .TextRange.Font.Size = "8"
                    End With
                End If
            Next s
        Next c
    Next w

End Sub
</code>```

Title: Excel autosize text to fit shape

Body:
I want to add some VBA to a multiple chart template to autosize  title text to fit textbox. This now runs, but doesn't make any changes to text box ...

Sub TextBox()

Dim ws As Worksheet
Dim shp As Shape

' loop through sheets in this workbook
 For Each ws In ThisWorkbook.Worksheets
 ' loop through Chartobjects in sheet
   For Each shp In ws.Shapes

    If shp.Type = msoTextBox Then
        With shp.TextFrame2
            strTxt = .TextRange
            .DeleteText
            .WarpFormat = msoWarpFormat1
            .WordWrap = True
            .AutoSize = msoAutoSizeTextToFitShape
            .TextRange = strTxt
        End With
    End If
   Next shp
  Next ws

End Sub

Body:
You are looping through the all the textbox in the sheets but if your textbox is on chartobject you need to handle it in a slightly different.

Sub TextBox()

    Dim w As Worksheet
    Dim c As ChartObject
    Dim s As Shape

    For Each w In ActiveWorkbook.Worksheets
        For Each c In w.ChartObjects
            For Each s In c.Chart.Shapes
                If s.Type = msoTextBox Then
                    With s.TextFrame2
                        strTxt = .TextRange
                        .DeleteText
                        .WarpFormat = msoWarpFormat1
                        .WordWrap = True
                        .AutoSize = msoAutoSizeTextToFitShape
                        .TextRange = strTxt
                        .TextRange.Font.Name = "Calibri"
                        .TextRange.Font.Size = "8"
                    End With
                End If
            Next s
        Next c
    Next w

End Sub


问:
Django rest response to display full dependencies structures and data
I have made Django REST function based API. I want to generate response to display full dependencies structure and data.

Employee is onetoone relation with User and Foreignkey to Company.
The response should show Employee data with User and Company related data.

Below is my code excerpts

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

```<code>@api_view(['GET'])
def get_employee(request):
    return Response(Employee.objects.all().values(), status=status.HTTP_200_OK)
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

```<code>class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    identity_number = models.CharField(max_length=20, blank=True)
</code>```

current result

```<code>[
  {
    "id": 1,
    "user_id": 8,
    "company_id": 3,
    "identity_number": "",
    "tel": "",
    "address_1": "",
    "address_2": "",
    "address_zip": "",
    "address_city": "",
    "address_state": "",
    "address_country": "",
    "face_image": "",
    "created_at": "2017-11-12T15:35:19.427973Z",
    "updated_at": "2017-11-12T15:35:19.455553Z"
  },
  {
  ....
</code>```

what i am trying to achieve is this. how to do this result ? kind of like presenter on ruby on rails.

```<code>[
  {
    "id": 1,
    "user":
           {"id": 1,
            "username": "michaeljackson",
            "first_name": "michael",
            "last_name": "jackson",
            "email": "xxx@gmail.com"},
    "company":
           {"id": 2,
            "name": "company X",
            "tel": "123456",
            ....},
    "identity_number": "",
    "tel": "",
    "address_1": "",
    "address_2": "",
    "address_zip": "",
    "address_city": "",
    "address_state": "",
    "address_country": "",
    "face_image": "",
    "created_at": "2017-11-12T15:35:19.427973Z",
    "updated_at": "2017-11-12T15:35:19.455553Z"
  },
  {
  ....
</code>```

答:
there are various ways to do that. One of them could be to create as_dict() for you model which will return a dictionary . You can add whatever fields you need in that dictionary.

Assuming you have following Company model.

```<code>class Company:
     name = model.CharField(max_length)
     domain = model.CharField(max_length)

     def as_dict(self):
        return {'name': self.name, 'domain': self.domain}
</code>```

for User class you can add as_dict as follows

```<code>def user_as_dict(self):
      return {"first_name": self.first_name}

User.add_to_class('as_dict', user_as_dict)
</code>```

as_dict for Employee model:

```<code>def as_dict(self):
    {"company": self.company.as_dict(),
     "user": self.user.as_dict(),
    "identity_number": self.identity_number}
</code>```

And finally you can change response in view

```<code>@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response({"results": data}, status=status.HTTP_200_OK)
</code>```

Body:
I have made Django REST function based API. I want to generate response to display full dependencies structure and data.

Employee is onetoone relation with User and Foreignkey to Company.
The response should show Employee data with User and Company related data.

Below is my code excerpts

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['GET'])
def get_employee(request):
    return Response(Employee.objects.all().values(), status=status.HTTP_200_OK)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    identity_number = models.CharField(max_length=20, blank=True)

current result

[
  {
    "id": 1,
    "user_id": 8,
    "company_id": 3,
    "identity_number": "",
    "tel": "",
    "address_1": "",
    "address_2": "",
    "address_zip": "",
    "address_city": "",
    "address_state": "",
    "address_country": "",
    "face_image": "",
    "created_at": "2017-11-12T15:35:19.427973Z",
    "updated_at": "2017-11-12T15:35:19.455553Z"
  },
  {
  ....

what i am trying to achieve is this. how to do this result ? kind of like presenter on ruby on rails.

[
  {
    "id": 1,
    "user":
           {"id": 1,
            "username": "michaeljackson",
            "first_name": "michael",
            "last_name": "jackson",
            "email": "xxx@gmail.com"},
    "company":
           {"id": 2,
            "name": "company X",
            "tel": "123456",
            ....},
    "identity_number": "",
    "tel": "",
    "address_1": "",
    "address_2": "",
    "address_zip": "",
    "address_city": "",
    "address_state": "",
    "address_country": "",
    "face_image": "",
    "created_at": "2017-11-12T15:35:19.427973Z",
    "updated_at": "2017-11-12T15:35:19.455553Z"
  },
  {
  ....

Body:
there are various ways to do that. One of them could be to create as_dict() for you model which will return a dictionary . You can add whatever fields you need in that dictionary.

Assuming you have following Company model.

class Company:
     name = model.CharField(max_length)
     domain = model.CharField(max_length)

     def as_dict(self):
        return {'name': self.name, 'domain': self.domain}

for User class you can add as_dict as follows

def user_as_dict(self):
      return {"first_name": self.first_name}

User.add_to_class('as_dict', user_as_dict)

as_dict for Employee model:

def as_dict(self):
    {"company": self.company.as_dict(),
     "user": self.user.as_dict(),
    "identity_number": self.identity_number}

And finally you can change response in view

@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response({"results": data}, status=status.HTTP_200_OK)


问:
Error setting date of month to 31st
While setting the date to 31st we encountered this issue.

function getTodayMidnight() {
  var date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(1);
  date.setMilliseconds(0);
  return date;
}

function getDates() {
  var octStartDate = getTodayMidnight();
  octStartDate.setDate(1);
  octStartDate.setMonth(9);

  var octEndDate = getTodayMidnight();
  octEndDate.setDate(31);
  octEndDate.setMonth(9);
  console.log(octStartDate);
  console.log(octEndDate);
}

getDates();```

I'm accounting for the date offset in my timezone (+530, 330 mins). For start of the month case, the behaviour is expected. (We expect to go back to the previous month and display the date). But we are getting an erroneous output in the case of the last date of the month. Why are they pointing to the same date?

答:
Assuming you ran this program today (15th November), then new Date() returns a Date object with the month set to November.  So a call to setDate(31) will result in the date overflowing to 1st December (because November only has 30 days).  You then call setMonth(9), so the final result corresponds to 1st October.

Obviously, you can avoid this by switching the order of your method calls.
 But to avoid this ordering problem entirely, I'd suggest using the Date(year, month, date, ...) constructor (this also avoids mutating a value type, which is generally considered to be a good thing).

Title: Error setting date of month to 31st

Body:
While setting the date to 31st we encountered this issue.

function getTodayMidnight() {
  var date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(1);
  date.setMilliseconds(0);
  return date;
}

function getDates() {
  var octStartDate = getTodayMidnight();
  octStartDate.setDate(1);
  octStartDate.setMonth(9);

  var octEndDate = getTodayMidnight();
  octEndDate.setDate(31);
  octEndDate.setMonth(9);
  console.log(octStartDate);
  console.log(octEndDate);
}

getDates();

I'm accounting for the date offset in my timezone (+530, 330 mins). For start of the month case, the behaviour is expected. (We expect to go back to the previous month and display the date). But we are getting an erroneous output in the case of the last date of the month. Why are they pointing to the same date?


问:
inlining spread operator during declaration es2018
I want to do something like this:

```<code>const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    uk: {
        ...ru
    }
}
</code>```

obviously it doesn't work, of course, I can set another const, and then use it but I'm lazy ) so I'm curious if javascript allows you to do so?

答:
You have to declare this ru value before spreading, i.e.:

```<code>const ru = {
    statistics_title: 'Статистика'
};

const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru,
    uk: {
        ...ru
    }
};
</code>```

Body:
I want to do something like this:

const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru: {
        statistics_title: 'Статистика'
    },
    uk: {
        ...ru
    }
}

obviously it doesn't work, of course, I can set another const, and then use it but I'm lazy ) so I'm curious if javascript allows you to do so?

Body:
You have to declare this ru value before spreading, i.e.:

const ru = {
    statistics_title: 'Статистика'
};

const translations = {
    en: {
        statistics_title: 'Statistics'
    },
    ru,
    uk: {
        ...ru
    }
};


问:
Tensorflow model file size varies significantly
I am using a tensorflow framework and I have noticed that there are major variances in the size of the tensorflow model files.

For example the framework provides 2 models:

one of pretrained model to be used with fine tuning for example

and one which contains an untrained version.

They both have a size of 172.539 kb

When I apply fine tuning in my model with some minor changes in the graph (there is a module in framework for that) and save my model the size remains essentially the same: 178.525 kb.

First, I am bit surprised that my fine-tuned model is somewhat bigger since I change just the last layer from 21 to 14 classes so I would expect a somewhat smaller model file size but since the difference is so little I didn't pay attention.

But when I trained the same model using the same model file (the pretrained one I mean) and saved the model in disk the file size is quite different: 340.097 kb. By the term train I mean I allow the network to modify all parameter not just the parameters of the last layer.

The model that is being implemented is a variation of resnet for semantic image segmentation (if can someone deduct the expected model file size from the model itself).

So, my questions are why I have such a variance in the model file sizes and how come my saved fine-tuned model is larger than the original model? Is there a way to include/exclude parameters in the model to be saved?

P.S.1 Some information that might be handy:

I am using tensorflow v2 model saving while I think the framework files use v1. I am not sure how to identify this besides the fact that the former produces 3 files.

The framework is called tensorflow-deeplab-resnet and can be found here and the models are here.

P.S.2
I am not sure stack overflow it 's the right place for this question either.

答:
That is because, when training models and saving them, Tensorflow will also save the gradients of your ops.

So allowing training on the last layer will increase the size of your saved model a little. And allowing training on the whole model will essentially double the size of the save file because each op will have its gradients saved.