问:
SignalR backplane with Azure Service Bus
I need to realize a simple cluster of workers that creates file zip file with a lot of pdf in it. The architecture, right now look like this:

A single client (WebAPI + AngularJS)

A cluster of Hangfire server that do the work

As soon the clients ask for a new zip file, the request is enqueued in the Hangfire queue. When one of the node in the cluster is free, the job will starts. During the execution of the job the client will be notified about the progress. Since the cluster, is necessary another component:

A so called, SignalR backplane that handle the communication between workers and client

I use Redis to implement this component, and thanks to some NuGet packages (i.e. Microsoft.AspNet.SignalR, Microsoft.AspNet.SignalR.Redis) and this doc this is super simple and the only things I need is to add some new line in the Owin startups file; one for the worker:

```<code>public class WorkerStartup
{
    public void Configuration(IAppBuilder app)
    {
       GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");
       GlobalHost.DependencyResolver.UseRedis("IP", 6379, String.Empty, "TOPIC");

       app.MapSignalR();
       app.UseHangfireServer();
    }
}
</code>```

one for the WebAPI, they are equals but Hangfire configuration:

```<code>public class ClientStartup
{
    public void Configuration(IAppBuilder app)
    {
       GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");
       GlobalHost.DependencyResolver.UseRedis("IP", 6379, String.Empty, "TOPIC");

       app.MapSignalR();
       app.UseHangfireDashboard(); // The client only needs Hangfire dashboard
    }
}
</code>```

It works like a charm and Redis do the job pretty well. I would try to reimplement everything using Azure Service Bus (based on the link here), I replaced the package Microsoft.AspNet.SignalR.Redis with Microsoft.AspNet.SignalR.ServiceBus and replaced the line UseRedis like:

```<code>GlobalHost.DependencyResolver.UseServiceBus("Endpoint=sb://XXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXX", "TOPIC");
</code>```

but as soon I start the client/server communication I get:

No transport could be initialized successfully. Try specifying a
  different transport or none at all for auto initialization."

What's wrong, it should work without problem...

答:
No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.

To troubleshoot the issue, you could enable tracing and log on your hub, and you could see which transport your application is using in your browser console tab.

```<code>$.connection.hub.logging = true;
</code>```

And then you could try to explicitly specify a different transport when the client connection is started and test if it works.

```<code>$.connection.hub.start({ transport: 'specify transport that you want' })
</code>```

Currently, the following transports are supported:

WebSockets

Server-Sent

Events Forever Frame (for Internet Explorer only)

Ajax long polling

Body:
I need to realize a simple cluster of workers that creates file zip file with a lot of pdf in it. The architecture, right now look like this:

A single client (WebAPI + AngularJS)

A cluster of Hangfire server that do the work

As soon the clients ask for a new zip file, the request is enqueued in the Hangfire queue. When one of the node in the cluster is free, the job will starts. During the execution of the job the client will be notified about the progress. Since the cluster, is necessary another component:

A so called, SignalR backplane that handle the communication between workers and client

I use Redis to implement this component, and thanks to some NuGet packages (i.e. Microsoft.AspNet.SignalR, Microsoft.AspNet.SignalR.Redis) and this doc this is super simple and the only things I need is to add some new line in the Owin startups file; one for the worker:

public class WorkerStartup
{
    public void Configuration(IAppBuilder app)
    {
       GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");
       GlobalHost.DependencyResolver.UseRedis("IP", 6379, String.Empty, "TOPIC");

       app.MapSignalR();
       app.UseHangfireServer();
    }
}

one for the WebAPI, they are equals but Hangfire configuration:

public class ClientStartup
{
    public void Configuration(IAppBuilder app)
    {
       GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");
       GlobalHost.DependencyResolver.UseRedis("IP", 6379, String.Empty, "TOPIC");

       app.MapSignalR();
       app.UseHangfireDashboard(); // The client only needs Hangfire dashboard
    }
}

It works like a charm and Redis do the job pretty well. I would try to reimplement everything using Azure Service Bus (based on the link here), I replaced the package Microsoft.AspNet.SignalR.Redis with Microsoft.AspNet.SignalR.ServiceBus and replaced the line UseRedis like:

GlobalHost.DependencyResolver.UseServiceBus("Endpoint=sb://XXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXX", "TOPIC");

but as soon I start the client/server communication I get:

No transport could be initialized successfully. Try specifying a
  different transport or none at all for auto initialization."

What's wrong, it should work without problem...

Body:
No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.

To troubleshoot the issue, you could enable tracing and log on your hub, and you could see which transport your application is using in your browser console tab.

$.connection.hub.logging = true;

And then you could try to explicitly specify a different transport when the client connection is started and test if it works.

$.connection.hub.start({ transport: 'specify transport that you want' })

Currently, the following transports are supported:

WebSockets

Server-Sent

Events Forever Frame (for Internet Explorer only)

Ajax long polling


来源: stackexchange

问:
how to use mini_magick to delete exif?
you can show all the exif of a image in mini_magick, like this:

```<code>image = MiniMagick::Image.open('example.jpg')
pp image.exif
</code>```

but I can't delete the exif, like image.exif={}, it shows the error:

```<code>mogrify: unrecognized option `-exif=' @ error/mogrify.c/MogrifyImageCommand/4833.
</code>```

so, how can I delete all the exif information of a image use mini_magick?

答:
well, finally, I found a solution: use mogrify, batch process all the images

```<code>mogrify -strip -quality 75%  *.jpg
</code>```

the argument strip delete all the exif information, set the quality to 75%!

ContentLicense: CC BY-SA 3.0

Title: how to use mini_magick to delete exif?

Body:
you can show all the exif of a image in mini_magick, like this:

image = MiniMagick::Image.open('example.jpg')
pp image.exif

but I can't delete the exif, like image.exif={}, it shows the error:

mogrify: unrecognized option `-exif=' @ error/mogrify.c/MogrifyImageCommand/4833.

so, how can I delete all the exif information of a image use mini_magick?

Body:
well, finally, I found a solution: use mogrify, batch process all the images

mogrify -strip -quality 75%  *.jpg

the argument strip delete all the exif information, set the quality to 75%!


问:
angular2 how to iterate array of objects
I want to iterate an array of objects but I received the following error:

```<code>inline template:25:9 caused by: Cannot read property 'length' of null
</code>```

The followings are parts of my code:

```<code>// Definition of the array
public columnsConfig: Array<ColumnConfig>;
</code>```

where ColumnConfig is a class of all the instances included in the array.

```<code>// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();

// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`
}
</code>```

Template:

What am I missing here?

答:
You can use RX js map operator to iterate and make an Array of values.</p>

```<code>import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';

@Component( {
  selector: 'app-root',
  template:
  `<ol>
    <li *ngFor="let config of columnsConfig ">
    {{config}}
   </li>
   </ol>`
} )
export class AppComponent
{
  ngOnInit() { this.make() }

  public columnsConfig: any[]
  public _headers: any =
  [
    { columnName: 'one', otherName: 'foo' },
    { columnName: 'two', otherName: 'boo' },
    { columnName: 'three', otherName: 'loo' }
  ];

  make()
  {
    let config = [];
    this._headers
      .map( x =>
      {
        config.push( x.columnName );

        this.columnsConfig = config;

        console.log( 'progress: ', config );
      } )
    console.log( 'final result: ', this.columnsConfig );
  }
}
</code>```

Body:
I want to iterate an array of objects but I received the following error:

inline template:25:9 caused by: Cannot read property 'length' of null

The followings are parts of my code:

// Definition of the array
public columnsConfig: Array<ColumnConfig>;

where ColumnConfig is a class of all the instances included in the array.

// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();

// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`
}

Template:

What am I missing here?

Body:
You can use RX js map operator to iterate and make an Array of values.

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';

@Component( {
  selector: 'app-root',
  template:
  `<ol>
    <li *ngFor="let config of columnsConfig ">
    {{config}}
   </li>
   </ol>`
} )
export class AppComponent
{
  ngOnInit() { this.make() }

  public columnsConfig: any[]
  public _headers: any =
  [
    { columnName: 'one', otherName: 'foo' },
    { columnName: 'two', otherName: 'boo' },
    { columnName: 'three', otherName: 'loo' }
  ];

  make()
  {
    let config = [];
    this._headers
      .map( x =>
      {
        config.push( x.columnName );

        this.columnsConfig = config;

        console.log( 'progress: ', config );
      } )
    console.log( 'final result: ', this.columnsConfig );
  }
}


问:
What is the difference between .col-xs-4 or col-xs-4?
New to HTML, CSS, and Bootstrap. Is it necessary to add a period before col-xs-4? What is the difference between .col-xs-4 and col-xs-4?

I currently have this:

Hello, world!

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

```

Thank you for your time.

答:
Don't add the period.
The dot is used in the CSS to specify it as a class.

```<code>.col-xs-4 {
width: 25%;
}
</code>```

Then the class is added to the element in the HTML. The dot isn't needed because it is in the class attribute.

```<code><div class="col-xs-4">Some content</div>
</code>```

Body:
New to HTML, CSS, and Bootstrap. Is it necessary to add a period before col-xs-4? What is the difference between .col-xs-4 and col-xs-4?

I currently have this:

Hello, world!

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Thank you for your time.

Body:
Don't add the period.
The dot is used in the CSS to specify it as a class.

.col-xs-4 {
width: 25%;
}

Then the class is added to the element in the HTML. The dot isn't needed because it is in the class attribute.

<div class="col-xs-4">Some content</div>


问:
When are nested functions generally appropriate in JavaScript?
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();
</code>```

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

```<code>function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}
</code>```

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

答: One possible advantage of this code is caching the result of a highly computational code which has to be done only once (although this is rare) and then using that result for other purposes. Browser related variables are generally cached using this strategy.</p>

Body:
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!


问:
How to test after_destroy callback in Rails and RSpec?
I have this User class in Ruby on Rails:

```<code>class User < ActiveRecord::Base

  after_destroy :ensure_an_admin_remains

  private

  def ensure_an_admin_remains
    if User.where("admin = ?", true).count.zero?
      raise "Can't delete Admin."
    end
  end

end
</code>```

This works great and causes a database rollback if someone accidentally deletes an admin user.

The problem is that it seems to break the user delete action, even when testing with a non-admin user (generated by Factory Girl). This is my user_controller_spec.rb:

```<code>describe 'DELETE #destroy' do

  before :each do
    @user = create(:non_admin_user)
    sign_in(@user)
  end

  it "deletes the user" do
    expect{
      delete :destroy, id: @user
    }.to change(User, :count).by(-1)
  end

end
</code>```

Whenever I run this test, I get this error:

```<code>Failure/Error: expect{
count should have been changed by -1, but was changed by 0
</code>```

There shouldn't be any error, though, because @user's admin attribute is set to false by default.

Can anybody help me out here?

Thanks...

答:
You shouldn't raise for control flow. You can halt during callbacks to prevent the record being commited.

I've improved one some of the answers here for anyone else trying to work out how to do this properly as of Rails 5

```<code>class User < ActiveRecord::Base
  before_destroy :ensure_an_admin_remains

  private def ensure_an_admin_remains
    return unless admin && User.where(admin: true).limit(2).size == 1
    errors.add(:base, "You cannot delete the last admin.")
    throw :abort
  end
end
</code>```

Body:
I have this User class in Ruby on Rails:

class User < ActiveRecord::Base

  after_destroy :ensure_an_admin_remains

  private

  def ensure_an_admin_remains
    if User.where("admin = ?", true).count.zero?
      raise "Can't delete Admin."
    end
  end

end

This works great and causes a database rollback if someone accidentally deletes an admin user.

The problem is that it seems to break the user delete action, even when testing with a non-admin user (generated by Factory Girl). This is my user_controller_spec.rb:

describe 'DELETE #destroy' do

  before :each do
    @user = create(:non_admin_user)
    sign_in(@user)
  end

  it "deletes the user" do
    expect{
      delete :destroy, id: @user
    }.to change(User, :count).by(-1)
  end

end

Whenever I run this test, I get this error:

Failure/Error: expect{
count should have been changed by -1, but was changed by 0

There shouldn't be any error, though, because @user's admin attribute is set to false by default.

Can anybody help me out here?

Thanks...

Body:
You shouldn't raise for control flow. You can halt during callbacks to prevent the record being commited.

I've improved one some of the answers here for anyone else trying to work out how to do this properly as of Rails 5

class User < ActiveRecord::Base
  before_destroy :ensure_an_admin_remains

  private def ensure_an_admin_remains
    return unless admin && User.where(admin: true).limit(2).size == 1
    errors.add(:base, "You cannot delete the last admin.")
    throw :abort
  end
end


问:
Divide the navbar into 3 equal parts
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <html>
    <head>
     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    </head>
    <body>
    <div class="container-fluid">
     <div class="navbar navbar-inverse">
      <div class="navbar-header ">
             <ul class="nav navbar-nav container">
              <li class="col-md-4" id="intr1"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr2"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr3"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
             </ul>
           </div>
     </div>
    </div>

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

答:
I hope this will help you a lot:

HTML:

```<code><nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav customnavbarnav">
                <li class="customlist"><a href="#">Link </a>
                </li>
                <li class="customlist"><a href="#">Link </a>
                </li>
                <li class="customlist"><a href="#">Link </a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
</nav>
<!-- /.navbar navbar-default -->
</code>```

CSS:

```<code>.customnavbarnav{
    width: 100%;
    text-align: center;
}
.customlist{
    width: 33.33333333333333%
}
</code>```

Title: Divide the navbar into 3 equal parts

Body:
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }

     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

INTERIOR DESIGN

INTERIOR DESIGN

INTERIOR DESIGN

Body:
I hope this will help you a lot:

HTML:

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav customnavbarnav">
                <li class="customlist"><a href="#">Link </a>
                </li>
                <li class="customlist"><a href="#">Link </a>
                </li>
                <li class="customlist"><a href="#">Link </a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
</nav>
<!-- /.navbar navbar-default -->

CSS:

.customnavbarnav{
    width: 100%;
    text-align: center;
}
.customlist{
    width: 33.33333333333333%
}


问:
Inconsistent behavior in JavaScript's conditional checking
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

```<code>if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

```<code>if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

答:
I tried to reconstruct it using chrome JScript console

If you add a watch expression to both obj1 and obj1.obj2 before your two lines both are of course not defined:

obj1: ReferenceError: obj1 is not defined

obj1.obj2: ReferenceError: obj1 is not defined

As soon as you go over this line  if (typeof obj1==='undefined') obj1 = {}; all of a sudden they turn into

obj1: Object

obj1.obj2: undefined

So, you cannot check the first with ! because it is not undefined

Hope this helps

ContentLicense: CC BY-SA 2.5

Body:
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?


问:
how to write a single sql query based on combobox selection?
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

```<code>if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}
</code>```

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

答:
I think you have to try something like this with parameterization:</p>

```<code>StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();

if (combobox1.selectedindex > -1)
{
   queryBuilder.Append(" And city_name = @city_name ");
   cmdSql.Parameters.Add("@city_name", SqlDbType.VarChar).Value = combobox.text;
}
else if(Condition 2)
{
   queryBuilder.Append(" And column2 = @col2 ");
   cmdSql.Parameters.Add("@col2", SqlDbType.VarChar).Value = "some Value here;
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command
</code>```

Body:
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

Body:
I think you have to try something like this with parameterization:

StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();

if (combobox1.selectedindex > -1)
{
   queryBuilder.Append(" And city_name = @city_name ");
   cmdSql.Parameters.Add("@city_name", SqlDbType.VarChar).Value = combobox.text;
}
else if(Condition 2)
{
   queryBuilder.Append(" And column2 = @col2 ");
   cmdSql.Parameters.Add("@col2", SqlDbType.VarChar).Value = "some Value here;
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command


问:
How to return specific properties of a custom vb.net object
I'm trying to generate a list of all of the TableName and FieldName properties for a custom object type called LxTextBox. I've gotten as far as generating a list of all of the LxTextBox names on my form, but I can't figure out a way to call the properties of the custom object... I've been looking into System.Reflection, but I haven't ever used it. Additionally, I'm returning the list to a RichTextBox while I'm testing this out, but ultimately, I need to return each objects properties as a data row. Example:

```<code>    ObjectName      Table           Field
    ---------------------------------------
    LxTextBox23     SomeTbl         SomeFld
</code>```

Here's my code to return the list - updated based on @OneFineDay...

```<code>Imports System.Collections.Generic
Imports Application.UDF.Controls

Public Class MeasurementsControl

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim textBoxList As New List(Of Control)
        Dim customTbs = GetAllControls(Me)

        Dim sb As New System.Text.StringBuilder
        For index As Integer = 0 To customTbs.Count - 1
            sb.Append(customTbs.Item(index).TableName & "." & customTbs.Item(Index).FieldName & System.Environment.NewLine)
        Next

        RichTextBox1.Text = sb.ToString

    End Sub

    Private Function GetAllControls(ByVal searchWithin As Control) As List(Of LxTextbox)
        Dim returnList As List(Of LxTextbox) = Nothing
        If searchWithin.HasChildren Then
            returnList = searchWithin.Controls.OfType(Of LxTextbox).ToList
            For Each ctrl As Control In searchWithin.Controls
                returnList.AddRange(GetAllControls(ctrl))
            Next
        End If
        Return returnList
    End Function
End Class
</code>```

I made the changes suggested and I'm throwing an error: OfType is not a member of System.Windows.Forms.Control.ControlCollection

FYI - Adding Imports System.Linq did not fix the error.

答:
You are boxing it into a Control the object from where it derives, where you're custom properties cannot be found. You can cast it right from the control collection.

```<code>Dim customTbs = GetAllControls(Me)

'recursive function
Private Function GetAllControls(ByVal searchWithin As Control) As List(Of LxTextbox)
 Dim returnList As List(Of LxTextbox) = Nothing
 returnList = searchWithin.Controls.OfType(Of LxTextbox).ToList
 If searchWithin.HasChildren Then
  For Each ctrl As Control In searchWithin.Controls
    Dim ctrls = GetAllControls(ctrl)
    If Not ctrls Is Nothing Then returnList.AddRange(ctrls)
  Next
 End If
 Return returnList
End Function
</code>```

Body:
I'm trying to generate a list of all of the TableName and FieldName properties for a custom object type called LxTextBox. I've gotten as far as generating a list of all of the LxTextBox names on my form, but I can't figure out a way to call the properties of the custom object... I've been looking into System.Reflection, but I haven't ever used it. Additionally, I'm returning the list to a RichTextBox while I'm testing this out, but ultimately, I need to return each objects properties as a data row. Example:

    ObjectName      Table           Field
    ---------------------------------------
    LxTextBox23     SomeTbl         SomeFld

Here's my code to return the list - updated based on @OneFineDay...

Imports System.Collections.Generic
Imports Application.UDF.Controls

Public Class MeasurementsControl

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim textBoxList As New List(Of Control)
        Dim customTbs = GetAllControls(Me)

        Dim sb As New System.Text.StringBuilder
        For index As Integer = 0 To customTbs.Count - 1
            sb.Append(customTbs.Item(index).TableName & "." & customTbs.Item(Index).FieldName & System.Environment.NewLine)
        Next

        RichTextBox1.Text = sb.ToString

    End Sub

    Private Function GetAllControls(ByVal searchWithin As Control) As List(Of LxTextbox)
        Dim returnList As List(Of LxTextbox) = Nothing
        If searchWithin.HasChildren Then
            returnList = searchWithin.Controls.OfType(Of LxTextbox).ToList
            For Each ctrl As Control In searchWithin.Controls
                returnList.AddRange(GetAllControls(ctrl))
            Next
        End If
        Return returnList
    End Function
End Class

I made the changes suggested and I'm throwing an error: OfType is not a member of System.Windows.Forms.Control.ControlCollection

FYI - Adding Imports System.Linq did not fix the error.

Body:
You are boxing it into a Control the object from where it derives, where you're custom properties cannot be found. You can cast it right from the control collection.

Dim customTbs = GetAllControls(Me)

'recursive function
Private Function GetAllControls(ByVal searchWithin As Control) As List(Of LxTextbox)
 Dim returnList As List(Of LxTextbox) = Nothing
 returnList = searchWithin.Controls.OfType(Of LxTextbox).ToList
 If searchWithin.HasChildren Then
  For Each ctrl As Control In searchWithin.Controls
    Dim ctrls = GetAllControls(ctrl)
    If Not ctrls Is Nothing Then returnList.AddRange(ctrls)
  Next
 End If
 Return returnList
End Function


答:
You should not be putting a . before col-xs-4 in the class attribute of the element. The . is the character used to indicate that whatever follows it until the start of the next selector segment is a class.

Similarly, you do not want to put a # character in the ID field.

Reference: W3 Schools CSS Selectors Page

Title: What is the difference between .col-xs-4 or col-xs-4?


问:
MVC3 Conditionally disable Html.TextBoxFor()
I have a C# .Net web app. In that app I need to conditionally disable Html.TextBoxFor controls (also Html.DropDownListFor controls) based on who is logged into the system.  I tried using

```<code> @Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.IsDisabled })
</code>```

Where @ViewBag.IsDisabled is set to either String.Empty or "disabled" in the Controller. However, this renders as IsDisabled='disabled' or IsDisabled="" so the control is not disabled. When I tried

```<code>@Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.Disabled })
</code>```

The control was always disabled even if ViewBag.Disabled contained no text.  How can I conditionally disable the Html.TextBoxFor() controls?

答:
Extending @James's answer, I wrote this HtmlHelper extension that updates/removes the disabled attribute if it's already present, or adds it if not:

```<code>public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled) {
    string html = helper.ToString();
    var regex = new Regex("(disabled(?:=\".*\")?)");
    if (regex.IsMatch(html)) {
        html = regex.Replace(html, disabled ? "disabled=\"disabled\"" : "", 1);
    } else {
        regex = new Regex(@"(\/?>)");
        html = regex.Replace(html, disabled ? "disabled=\"disabled\"$1" : "$1", 1);
    }
    return MvcHtmlString.Create(html);
}
</code>```

It also plays nicely with self-closing tags (like <input />).

Usage is the same:

```<code>@Html.TextBoxFor(model => model.PropertyName).Disable(true)
</code>```

Tested on both @Html.DropDownListFor() and @Html.TextBoxFor().

Body:
I have a C# .Net web app. In that app I need to conditionally disable Html.TextBoxFor controls (also Html.DropDownListFor controls) based on who is logged into the system.  I tried using

 @Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.IsDisabled })

Where @ViewBag.IsDisabled is set to either String.Empty or "disabled" in the Controller. However, this renders as IsDisabled='disabled' or IsDisabled="" so the control is not disabled. When I tried

@Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.Disabled })

The control was always disabled even if ViewBag.Disabled contained no text.  How can I conditionally disable the Html.TextBoxFor() controls?

Body:
Extending @James's answer, I wrote this HtmlHelper extension that updates/removes the disabled attribute if it's already present, or adds it if not:

public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled) {
    string html = helper.ToString();
    var regex = new Regex("(disabled(?:=\".*\")?)");
    if (regex.IsMatch(html)) {
        html = regex.Replace(html, disabled ? "disabled=\"disabled\"" : "", 1);
    } else {
        regex = new Regex(@"(\/?>)");
        html = regex.Replace(html, disabled ? "disabled=\"disabled\"$1" : "$1", 1);
    }
    return MvcHtmlString.Create(html);
}

It also plays nicely with self-closing tags (like <input />).

Usage is the same:

@Html.TextBoxFor(model => model.PropertyName).Disable(true)

Tested on both @Html.DropDownListFor() and @Html.TextBoxFor().


问:
Remove odd numbers in array
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

```<code>let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);
</code>```

答:
If you only need support as far back as IE9 you can use the Array.prototype.filter method.

```<code>var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var output = arr.filter(function(item) {
    return item % 2 === 0;
});
</code>```

Output will be a new array of the filtered values (Only even).

Title: Remove odd numbers in array

Body:
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);

Body:
If you only need support as far back as IE9 you can use the Array.prototype.filter method.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var output = arr.filter(function(item) {
    return item % 2 === 0;
});

Output will be a new array of the filtered values (Only even).


问:
how to make dropdown keep open on hover and disappear when leave it
i really need help. i tried but it is still not working. i want to make a dropdown menu that will appear on hover and will disappear when leave that dropdown.

$(document).ready(function(){
 $('.navigation-menu').mouseenter(function(){
   $('.navigation-dropdown').addClass('visible');
  });
  $('.navigation-dropdown').mouseleave(function(){
   $('.navigation-dropdown').removeClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  margin: 0;
}
.container{
  background-color: rgb(0,0,0);
  height: 30px;
  padding: 10px;
}
.container-dropdown{
  background-color: rgb(125,125,125)
}
.dropdown-menu{
  display: inline-block;
}
.navigation-dropdown{
  display: none;
}
.navigation-menu{
  display: inline-block;
  height: 100%;
}
.visible{
  display: block;
}</code>```

home

home

home

```

So, i just want to make that gray div disappear when i move my mouse leave the navigation-menu class

my problem: i have to move the mouse to the gray div first to make the gray div disappear. all i want is make the gray div can disappear without have to move the mouse to the gray div first

答:
There are much better design options for you to look forward to, to get what you want. But if you just want to stick to the current layout and design, I would make a couple of changes to get what you are looking for.

```<code>.container{
  background-color: rgb(0,0,0);
  height: 20px;
  padding: 10px;
  padding-bottom: 0px; --to remove any space between menu title and the dropdown
}
</code>```

and

```<code>$(document).ready(function(){
    $('.navigation-menu').mouseenter(function(){
    $('.navigation-dropdown').addClass('visible');
  });
  $('.navigation-dropdown').mouseleave(function(){
    $('.navigation-dropdown').removeClass('visible');
  });

  $('.navigation-dropdown').mouseenter(function(){
      $('.navigation-dropdown').addClass('visible');
  });

  $('.navigation').mouseleave(function(){
        $('.navigation-dropdown').removeClass('visible');
  });

  $('.navigation-menu').mouseleave(function(){
        $('.navigation-dropdown').removeClass('visible');
  });
});
</code>```

to hide dropdown menu if mouse leaves navigation div.

hope this helps.

Body:
i really need help. i tried but it is still not working. i want to make a dropdown menu that will appear on hover and will disappear when leave that dropdown.

$(document).ready(function(){
 $('.navigation-menu').mouseenter(function(){
   $('.navigation-dropdown').addClass('visible');
  });
  $('.navigation-dropdown').mouseleave(function(){
   $('.navigation-dropdown').removeClass('visible');
  });
});

ul{
  margin: 0;
}
.container{
  background-color: rgb(0,0,0);
  height: 30px;
  padding: 10px;
}
.container-dropdown{
  background-color: rgb(125,125,125)
}
.dropdown-menu{
  display: inline-block;
}
.navigation-dropdown{
  display: none;
}
.navigation-menu{
  display: inline-block;
  height: 100%;
}
.visible{
  display: block;
}

home

home

home

So, i just want to make that gray div disappear when i move my mouse leave the navigation-menu class

my problem: i have to move the mouse to the gray div first to make the gray div disappear. all i want is make the gray div can disappear without have to move the mouse to the gray div first

Body:
There are much better design options for you to look forward to, to get what you want. But if you just want to stick to the current layout and design, I would make a couple of changes to get what you are looking for.

.container{
  background-color: rgb(0,0,0);
  height: 20px;
  padding: 10px;
  padding-bottom: 0px; --to remove any space between menu title and the dropdown
}

and

$(document).ready(function(){
    $('.navigation-menu').mouseenter(function(){
    $('.navigation-dropdown').addClass('visible');
  });
  $('.navigation-dropdown').mouseleave(function(){
    $('.navigation-dropdown').removeClass('visible');
  });

  $('.navigation-dropdown').mouseenter(function(){
      $('.navigation-dropdown').addClass('visible');
  });

  $('.navigation').mouseleave(function(){
        $('.navigation-dropdown').removeClass('visible');
  });

  $('.navigation-menu').mouseleave(function(){
        $('.navigation-dropdown').removeClass('visible');
  });
});

to hide dropdown menu if mouse leaves navigation div.

hope this helps.


问:
Count greater elements on right side of a current element in an array
I am trying to count the number of elements greater than the element on the right side of the array. Here my function goes.

```<code>int* SurpassersKing(int input1_size, int* input1,int* output_size)
    {
        int i,k;
        int count[input1_size];
        for  (i = 0; i < input1_size; i++)
            count[i] = 0;

        for ( i = 0; i < input1_size; i++)
        {
            for ( k = i + 1; k <input1_size; k++)
                {
                        if (input1[i] < input1[k]) {
                                 count[i]++;
                        }
                }
        }

        return count;
    }
</code>```

This is my function where I am counting greater elements in an array.

So in this following code snippet i have wriiten the main function , declaring all the veriable like output_size,counting array ,i ,k as an index for the arrays and printing the stuff , and calling counting function .

```<code>int main() {
    int output_size;
    int* output;

    int ip1_size = 0;
    int ip1_i;
    scanf("%d\n", &ip1_size);
    int ip1[ip1_size];
    for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
        int ip1_item;
        scanf("%d", &ip1_item);

        ip1[ip1_i] = ip1_item;
    }
    output = SurpassersKing(ip1_size,ip1,&output_size);
    int output_i;
    for(output_i=0; output_i < output_size; output_i++) {

        printf("%d\n", output[output_i]);

    }
    return 0;
}
</code>```

but i am not getting the output required so what can i do to improve this.

答:
Your logic to calculate the count of the numbers to the right side is correct. Only problem is you can't return arrays like that from a function. Try following:

Replace

int count[input1_size];

with

int * count = malloc(input1_size*sizeof(int));

And then in the main function

Add

free(output);

just before the return statement.

Body:
I am trying to count the number of elements greater than the element on the right side of the array. Here my function goes.

int* SurpassersKing(int input1_size, int* input1,int* output_size)
    {
        int i,k;
        int count[input1_size];
        for  (i = 0; i < input1_size; i++)
            count[i] = 0;

        for ( i = 0; i < input1_size; i++)
        {
            for ( k = i + 1; k <input1_size; k++)
                {
                        if (input1[i] < input1[k]) {
                                 count[i]++;
                        }
                }
        }

        return count;
    }

This is my function where I am counting greater elements in an array.

So in this following code snippet i have wriiten the main function , declaring all the veriable like output_size,counting array ,i ,k as an index for the arrays and printing the stuff , and calling counting function .

int main() {
    int output_size;
    int* output;

    int ip1_size = 0;
    int ip1_i;
    scanf("%d\n", &ip1_size);
    int ip1[ip1_size];
    for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
        int ip1_item;
        scanf("%d", &ip1_item);

        ip1[ip1_i] = ip1_item;
    }
    output = SurpassersKing(ip1_size,ip1,&output_size);
    int output_i;
    for(output_i=0; output_i < output_size; output_i++) {

        printf("%d\n", output[output_i]);

    }
    return 0;
}

but i am not getting the output required so what can i do to improve this.


问:
Is there a timeout mecanism in MPI?
Everything is the title.
My team and I are currently working on a project and we are using MPI. In one place, we are doing a MPI_send resquesting  for a resource with a timeout. If the resource is available, we return 1 and if not and the timeout ended, we return 0.
We tried using the signals like SIGALRM, but it doesn't work because every new request cancel the old ones by setting a new alarm.

Thanks for your answer !!

答: You should investigate the non-blocking point-to-point communication primitives such as MPI_Isend, MPI_Irecv and MPI_Iprobe. You can then implement the timeout yourself, and use MPI_Cancel if you wish.

Title: Is there a timeout mecanism in MPI?


问:
R: Apply to slices of an array and return an array
I want to find the simplest way to apply a function across slices of an array, where each application of the function returns a matrix, and receive a sensible array object as the final answer.

I feel like there should be a simple way to do this with apply function, but I feel like I need a simplify = 'array' option, which would be super convenient. The closest I get is this:

```<code>dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

result = apply(arr, c(4,5), function(x) apply(x, c(3), function(y) (y - y[,1])^2 ) )
</code>```

The result should be an array with dimension c(2,3,10,4,5) or some permutation thereof.

I could get to the right form by calling as.array on result with the appropriate dimensions, but there should be an easier way that preserves the dimnames automatically.

答:
To iterate over a multidimensional array with apply, specify the margins you want to keep. It's easier to visualize in two dimensions:

m <- matrix(1, 2, 3)

m
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1

apply(m, 1, sum)
#> [1] 3 3
```

<p>—iterating over rows keeps that dimension, and collapses the unmentioned column one. For the more complicated array in question, then, </p>

<pre class="lang-r prettyprint-override"><code>res <- apply(arr, 2:5, function(x){mean(x^2)})
# or even just apply(arr^2, 2:5, mean) (h/t @thelatemail)

str(res)
#>  num [1:2, 1:3, 1:4, 1:5] 0.313 0.215 0.32 0.29 0.288 ...
#>  - attr(*, "dimnames")=List of 4
#>   ..$ : chr [1:2] "b1" "b2"
#>   ..$ : chr [1:3] "c1" "c2" "c3"
#>   ..$ : chr [1:4] "d1" "d2" "d3" "d4"
#>   ..$ : chr [1:5] "e1" "e2" "e3" "e4" ...
</code>```

Body:
I want to find the simplest way to apply a function across slices of an array, where each application of the function returns a matrix, and receive a sensible array object as the final answer.

I feel like there should be a simple way to do this with apply function, but I feel like I need a simplify = 'array' option, which would be super convenient. The closest I get is this:

dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

result = apply(arr, c(4,5), function(x) apply(x, c(3), function(y) (y - y[,1])^2 ) )

The result should be an array with dimension c(2,3,10,4,5) or some permutation thereof.

I could get to the right form by calling as.array on result with the appropriate dimensions, but there should be an easier way that preserves the dimnames automatically.

Body:
To iterate over a multidimensional array with apply, specify the margins you want to keep. It's easier to visualize in two dimensions:

m <- matrix(1, 2, 3)

m
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1

apply(m, 1, sum)
#> [1] 3 3

—iterating over rows keeps that dimension, and collapses the unmentioned column one. For the more complicated array in question, then,

res <- apply(arr, 2:5, function(x){mean(x^2)})
# or even just apply(arr^2, 2:5, mean) (h/t @thelatemail)

str(res)
#>  num [1:2, 1:3, 1:4, 1:5] 0.313 0.215 0.32 0.29 0.288 ...
#>  - attr(*, "dimnames")=List of 4
#>   ..$ : chr [1:2] "b1" "b2"
#>   ..$ : chr [1:3] "c1" "c2" "c3"
#>   ..$ : chr [1:4] "d1" "d2" "d3" "d4"
#>   ..$ : chr [1:5] "e1" "e2" "e3" "e4" ...


问:
if statement + stop in R
Background:

I have two elements in an R function called GG (see my R code below), type and width. The type element simply can only take the following character arguments:  "normal" or "cauchy". When type is "cauchy" width can be any number OR it can be one of the following 3 words: "medium", "wide", or "very wide". However, when type is "normal", wide must only be a number.

Question:

First, when I run GG(type = "normal", width = "medium") the function should STOP and return a message, but I get an error, how can I fix that?

Second, could these if statements be more efficiently written?

```<code>GG = function(type, width){

width <- if(type == "cauchy" & width == "wide") { sqrt(2)/2 } else

if(type == "cauchy" & width == "medium") { 1/2 } else
  if(type == "cauchy" & width == "very wide") { 1 } else
    if(type == "normal" & is.character(width) ) {
      stop(message(cat("You must provide a number")))
    } else { width }

return(width)

}

GG(type = "normal", width = "medium") ## if you I run this, I get an error.
</code>```

答:
By definition, stop is an error message

stop stops execution of the current expression and executes an error action.

so it is unsurprising that this is an error, but it is doing exactly what you want, which is stopping and returning a message.

42's suggestion might have meant something along these lines:

```<code>GG2 <- function(type, width) {

  width_vals <- list(
    "wide" = sqrt(2)/2,
    "medium" = 1/2,
    "very wide" = 1
  )

  if (type == "normal" & is.character(width)) {
    stop("You must provide a number")
  } else if (type == "cauchy") {
      width <- width_vals[[width]]
  }
  return(width)
}

GG2(type = "normal", width = 2) # 2
GG2(type = "normal", width = "wide") # error
GG2(type = "cauchy", width = "wide") # 0.7071068
GG2(type = "cauchy", width = "medium") # 0.5
GG2(type = "cauchy", width = "very wide") # 1
</code>```

Title: if statement + stop in R

Body:
Background:

I have two elements in an R function called GG (see my R code below), type and width. The type element simply can only take the following character arguments:  "normal" or "cauchy". When type is "cauchy" width can be any number OR it can be one of the following 3 words: "medium", "wide", or "very wide". However, when type is "normal", wide must only be a number.

Question:

First, when I run GG(type = "normal", width = "medium") the function should STOP and return a message, but I get an error, how can I fix that?

Second, could these if statements be more efficiently written?

GG = function(type, width){

width <- if(type == "cauchy" & width == "wide") { sqrt(2)/2 } else

if(type == "cauchy" & width == "medium") { 1/2 } else
  if(type == "cauchy" & width == "very wide") { 1 } else
    if(type == "normal" & is.character(width) ) {
      stop(message(cat("You must provide a number")))
    } else { width }

return(width)

}

GG(type = "normal", width = "medium") ## if you I run this, I get an error.

Body:
By definition, stop is an error message

stop stops execution of the current expression and executes an error action.

so it is unsurprising that this is an error, but it is doing exactly what you want, which is stopping and returning a message.

42's suggestion might have meant something along these lines:

GG2 <- function(type, width) {

  width_vals <- list(
    "wide" = sqrt(2)/2,
    "medium" = 1/2,
    "very wide" = 1
  )

  if (type == "normal" & is.character(width)) {
    stop("You must provide a number")
  } else if (type == "cauchy") {
      width <- width_vals[[width]]
  }
  return(width)
}

GG2(type = "normal", width = 2) # 2
GG2(type = "normal", width = "wide") # error
GG2(type = "cauchy", width = "wide") # 0.7071068
GG2(type = "cauchy", width = "medium") # 0.5
GG2(type = "cauchy", width = "very wide") # 1


问:
How can I maintain consistency in a 2-way object relationship in JavaScript?
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

```<code>function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;
</code>```

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}
</code>```

Describing this relationship is now simple and encourages consistency:

```<code>harry.setWife(wendy);
</code>```

Likewise, it would be nice to have the reverse option:

```<code>wendy.setHusband(harry);
</code>```

To do this I create a setHusband method on Wife, and tweak Husband as needed.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}
</code>```

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

答:
Something like this is one way to do what you're asking:</p>

```<code>function Husband() {
  this.marry = function(wife) {
    this.wife = wife;
    wife.husband = this;
  }

  this.say = function() {
    if (this.wife) {
      console.log('Hi! I\'m married to a wife!');
    } else {
      console.log('Hi! I\'m single, no wife.');
    }
  }

}

function Wife() {
  this.marry = function(husband) {
    this.husband = husband;
    husband.wife = this;
  }

  this.say = function() {
    if (this.husband) {
      console.log('Hi! I\'m married to a husband!');
    } else {
      console.log('Hi! I\'m single. No husband.');
    }
  }
}

var h = new Husband();
var w = new Wife();
h.marry(w);
w.say();
h.say();
</code>```

Body:
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}

Describing this relationship is now simple and encourages consistency:

harry.setWife(wendy);

Likewise, it would be nice to have the reverse option:

wendy.setHusband(harry);

To do this I create a setHusband method on Wife, and tweak Husband as needed.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

Body:
Something like this is one way to do what you're asking:

function Husband() {
  this.marry = function(wife) {
    this.wife = wife;
    wife.husband = this;
  }

  this.say = function() {
    if (this.wife) {
      console.log('Hi! I\'m married to a wife!');
    } else {
      console.log('Hi! I\'m single, no wife.');
    }
  }

}

function Wife() {
  this.marry = function(husband) {
    this.husband = husband;
    husband.wife = this;
  }

  this.say = function() {
    if (this.husband) {
      console.log('Hi! I\'m married to a husband!');
    } else {
      console.log('Hi! I\'m single. No husband.');
    }
  }
}

var h = new Husband();
var w = new Wife();
h.marry(w);
w.say();
h.say();


问:
Count how many months has passed since
I'm using numerals for each month. If I want to know how many months have passed since 5 (last May), how would I go about that?

```<code>$current_month = date('m');
$other_month = 5;
$months_since = ?;
</code>```

So some results would be like:

Example 1:

```<code>$current_month = 3
$other_month = 1
$months_since = 3
</code>```

Example 2:

```<code>$current_month = 3
$other_month = 9
$months_since = 7
</code>```

答:
As your logic, you can use this code:</p>

```<code>$months_since = $current_month - $other_month + 1;
</code>```

Title: Count how many months has passed since

Body:
I'm using numerals for each month. If I want to know how many months have passed since 5 (last May), how would I go about that?

$current_month = date('m');
$other_month = 5;
$months_since = ?;

So some results would be like:

Example 1:

$current_month = 3
$other_month = 1
$months_since = 3

Example 2:

$current_month = 3
$other_month = 9
$months_since = 7

Body:
As your logic, you can use this code:

$months_since = $current_month - $other_month + 1;


问:
Passing table name to a function and returning a table
I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.

Using this minimal example:

```<code>CREATE TABLE films (
code        char(5),
kind        varchar(10)
);
INSERT INTO films VALUES
('UA502', 'Comedy');
</code>```

And this function:

```<code>CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS void AS  -- I know, void is not what I am after
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;
</code>```

The following query catches something:

```<code>mydb=> SELECT foo('films');
 foo
-----
(1 row)
</code>```

However because I want to retrieve a table I edit the second line and re-create the function like so:

```<code>CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS TABLE(count integer) AS
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;
</code>```

However the same query does not catch anything:

```<code>mydb=> SELECT foo('films');
foo
-----
(0 rows)
</code>```

Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!

答:
If a function returns a scalar value it must contain return <expression>:

declare a variable,

assign a value to it (in the example with execute ... into ...),

use it in return <expression>.

Example:

```<code>drop function if exists foo(_t text);
create or replace function foo(_t text)
returns bigint as
$func$
declare
    res bigint;
begin
    execute format('select count(*) from %I', _t) into res;
    return res;
end
$func$ language plpgsql;

select foo('films');
</code>```

If a function returns a table it must contain return next or return query:

assign a value to a column of declared return table,

use return next,

call the function in FROM clause, not in SELECT list.

Example 1:

```<code>drop function if exists foo(_t text);
create or replace function foo(_t text)
returns table(count bigint) as
$func$
begin
   execute format('select count(*) from %I', _t) into count;
   return next;
end
$func$  language plpgsql;

select * from foo('films');
</code>```

If a function returns a table you can also use return query:

Example 2:

```<code>drop function if exists foo(_t text);
create or replace function foo(_t text)
returns table(count bigint) as
$func$
begin
    return query
        execute format('select count(*) from %I', _t);
end
$func$  language plpgsql;

select * from foo('films');
</code>```

Body:
I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.

Using this minimal example:

CREATE TABLE films (
code        char(5),
kind        varchar(10)
);
INSERT INTO films VALUES
('UA502', 'Comedy');

And this function:

CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS void AS  -- I know, void is not what I am after
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;

The following query catches something:

mydb=> SELECT foo('films');
 foo
-----
(1 row)

However because I want to retrieve a table I edit the second line and re-create the function like so:

CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS TABLE(count integer) AS
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;

However the same query does not catch anything:

mydb=> SELECT foo('films');
foo
-----
(0 rows)

Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!

Body:
If a function returns a scalar value it must contain return <expression>:

declare a variable,

assign a value to it (in the example with execute ... into ...),

use it in return <expression>.

Example:

drop function if exists foo(_t text);
create or replace function foo(_t text)
returns bigint as
$func$
declare
    res bigint;
begin
    execute format('select count(*) from %I', _t) into res;
    return res;
end
$func$ language plpgsql;

select foo('films');

If a function returns a table it must contain return next or return query:

assign a value to a column of declared return table,

use return next,

call the function in FROM clause, not in SELECT list.

Example 1:

drop function if exists foo(_t text);
create or replace function foo(_t text)
returns table(count bigint) as
$func$
begin
   execute format('select count(*) from %I', _t) into count;
   return next;
end
$func$  language plpgsql;

select * from foo('films');

If a function returns a table you can also use return query:

Example 2:

drop function if exists foo(_t text);
create or replace function foo(_t text)
returns table(count bigint) as
$func$
begin
    return query
        execute format('select count(*) from %I', _t);
end
$func$  language plpgsql;

select * from foo('films');


问:
Comparing floating-point numbers (floats or doubles) for min/max
How to compare two different floats, to a certain degree of accuracy. I know that there are very slight imprecisions while using floats or doubles in any programming language, but which may however, be enough to cause this comparison of floats a < b to return a different value than it actually should.

I was solving a problem from the UVa Online Judge which gave me a Wrong Answer many times. It took few float values as input, albeit, to 2 decimal places. I figured out the makeshift solution, which was by splitting the input and converting it to ints, but I wouldn't prefer to use that always.

So my question is, what's the best way to compare whether a float a is lesser (or greater) than a float b, provided that the inputs of a and b are given correct to n decimal places, in this case, 2?

The language I prefer is C++.

答:
Use std::numeric_limits<T>::epsilon() to check whether two numbers are almost equal.  If you want to know whether one is greater/less you should also take into account the relative tolerance.

```<code>#include <cmath>
#include <limits>

template < typename T >
bool fuzzy_compare(T a, T b)
{
  return std::abs(a - b) < std::numeric_limits<T>::epsilon();
};
</code>```

Body:
Use std::numeric_limits<T>::epsilon() to check whether two numbers are almost equal.  If you want to know whether one is greater/less you should also take into account the relative tolerance.

#include <cmath>
#include <limits>

template < typename T >
bool fuzzy_compare(T a, T b)
{
  return std::abs(a - b) < std::numeric_limits<T>::epsilon();
};


问:
how to convert combination string to array like this?
I have already tried this problem, I have small question this below is my input:

```<code>AA-1001AB-1002
</code>```

my question this combination string with number, word and symbol on above, and convert to array or json:

```<code>["AA-1001","AB-1002"]
</code>```

thanks for help :)

答:
You can use preg_match_all() to get all the matches of a pattern.

```<code>$string = "AA-1001AB-1002";
preg_match_all('/[A-Z]{2}-\d+/', $string, $matches);
$result = $matches[0];
print_r($result);
</code>```

The regular expression matches two uppercase letters, hyphen, followed by any number of digits.

Body:
I have already tried this problem, I have small question this below is my input:

AA-1001AB-1002

my question this combination string with number, word and symbol on above, and convert to array or json:

["AA-1001","AB-1002"]

thanks for help :)

Body:
You can use preg_match_all() to get all the matches of a pattern.

$string = "AA-1001AB-1002";
preg_match_all('/[A-Z]{2}-\d+/', $string, $matches);
$result = $matches[0];
print_r($result);

The regular expression matches two uppercase letters, hyphen, followed by any number of digits.


问:
Get the value of incremented input
I have two buttons which either increment or decrement an input value. I don't know how to retrieve the value later on submit of the result. My current attempts have either resulted in 'undefined' or '0'.

Thanks in advance for any advice

```<code>$('.plus').click(function(e){
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal)) {
        $('input[name='+fieldName+']').val(currentVal + 1);
    } else {
        $('input[name='+fieldName+']').val(0);
    }
});

$(".minus").click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal) && currentVal > 0) {
        $('input[name='+fieldName+']').val(currentVal - 1);
    } else {
        $('input[name='+fieldName+']').val(0);
    }
});

//attempting to get value
var value = document.getElementById( 'inputval' ).val();

$('#submitscore').click(function() {
    alert(value);
});
</code>```

My HTML

```<code> <span class="input-group-btn">
    <button class="btn btn-secondary btn-success minus" field='minusfield' id ="minus" type="button">-</button>
 </span>
 <input type="text" name="inputval" id="inputval" value="0" class="gh form-control" />
 <span class="input-group-btn">
    <button class="btn btn-secondary btn-success plus" id="plus" field='plusfield' type="button">+</button>
 </span>
 <button type="button" id="submitscore" class="btn btn-md btn-orange">Submit</button>
</code>```

答:
You're mixing standard Javascript usage with jQuery usage when you try to call it like this:

```<code>//attempting to get value
var value = document.getElementById( 'inputval' ).val();
</code>```

Use one or the other:

Standard Javascript:

```<code>document.getElementById('inputval').value
</code>```

jQuery:

```<code>$('#inputval').val()
</code>```

Title: Get the value of incremented input

Body:
I have two buttons which either increment or decrement an input value. I don't know how to retrieve the value later on submit of the result. My current attempts have either resulted in 'undefined' or '0'.

Thanks in advance for any advice

$('.plus').click(function(e){
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal)) {
        $('input[name='+fieldName+']').val(currentVal + 1);
    } else {
        $('input[name='+fieldName+']').val(0);
    }
});

$(".minus").click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal) && currentVal > 0) {
        $('input[name='+fieldName+']').val(currentVal - 1);
    } else {
        $('input[name='+fieldName+']').val(0);
    }
});

//attempting to get value
var value = document.getElementById( 'inputval' ).val();

$('#submitscore').click(function() {
    alert(value);
});

My HTML

    <button class="btn btn-secondary btn-success minus" field='minusfield' id ="minus" type="button">-</button>

 <input type="text" name="inputval" id="inputval" value="0" class="gh form-control" />

    <button class="btn btn-secondary btn-success plus" id="plus" field='plusfield' type="button">+</button>

 <button type="button" id="submitscore" class="btn btn-md btn-orange">Submit</button>

Body:
You're mixing standard Javascript usage with jQuery usage when you try to call it like this:

//attempting to get value
var value = document.getElementById( 'inputval' ).val();

Use one or the other:

Standard Javascript:

document.getElementById('inputval').value

jQuery:

$('#inputval').val()


问:
Error installing Fasttext on Windows 10 Python 3
I am trying to install fastText using pip install fastText on Windows 10. I have Python 3 installed in Anaconda.
I tried reading several posts but they do not give a clear idea about what exact changes should I make to install. I am getting the following error:

The error shown below reads:

```<code>raise ValueError("Unknown MS Compiler version %s " % msc_ver)
ValueError: Unknown MS Compiler version 1900
</code>```

Can anybody help in this?

答: It appears this is a know bug currently in open status according to Python Bug Tracker</p>

Body:
I am trying to install fastText using pip install fastText on Windows 10. I have Python 3 installed in Anaconda.
I tried reading several posts but they do not give a clear idea about what exact changes should I make to install. I am getting the following error:

The error shown below reads:

raise ValueError("Unknown MS Compiler version %s " % msc_ver)
ValueError: Unknown MS Compiler version 1900

Can anybody help in this?


问:
Should I use px or rem value units in my CSS?
I am designing a new website and I want it to be compatible with as much browsers and browser settings as possible. I am trying to decide what unit of measurement I should use for the sizes of my fonts and elements, but am unable to find a conclusive answer.

My question is: should I use px or rem in my CSS?

So far I know that using px isn't compatible with users who adjust their base font size in their browser.

I've disregarded ems because they are more of a hassle to maintain, compared to rems, as they cascade.

Some say that rems are resolution independent and therefore more desirable. But others say that most modern browsers zoom all elements equally anyway, so using px is not a problem.

I'm asking this because there are a lot of different opinions as to what is the most desirable measure of distance in CSS, and I am not sure which is best.

答:
I would like to praise josh3736's answer for providing some excellent historical context. While it's well articulated, the CSS landscape has changed in the almost five years since this question was asked. When this question was asked, px was the correct answer, but that no longer holds true today.

tl;dr: use rem

Unit Overview

Historically px units typically represented one device pixel. With devices having higher and higher pixel density this no longer holds for many devices, such as with Apple's Retina Display.

rem units represent the root em size. It's the font-size of whatever matches :root. In the case of HTML, it's the  element; for SVG, it's the <svg> element. The default font-size in every browser* is 16px.

On Using px

The majority of CSS examples on the internet use px values because they were the de-facto standard. pt, in and a variety of other units could have been used in theory, but they didn't handle small values well as you'd quickly need to resort to fractions, which were longer to type, and harder to reason about.

If you wanted a thin border, with px you could use 1px, with pt you'd need to use 0.75pt for consistent results, and that's just not very convenient.

On Using rem

rem's default value of 16px isn't a very strong argument for its use. Writing 0.0625rem is worse than writing 0.75pt, so why would anyone use rem?

There are two parts to rem's advantage over other units.

User preferences are respected

You can change the apparent px value of rem to whatever you'd like

Respecting User Preferences

Browser zoom has changed a lot over the years. Historically many browsers would only scale up font-size, but that changed pretty rapidly when websites realized that their beautiful pixel-perfect designs were breaking any time someone zoomed in or out. At this point, browsers scale the entire page, so font-based zooming is out of the picture.

Respecting a user's wishes is not out of the picture. Just because a browser is set to 16px by default, doesn't mean any user can't change their preferences to 24px or 32px to correct for low vision or poor visibility (e.x. screen glare). If you base your units off of rem, any user at a higher font-size will see a proportionally larger site. Borders will be bigger, padding will be bigger, margins will be bigger, everything will scale up fluidly.

If you base your media queries on rem, you can also make sure that the site your users see fits their screen. A user with font-size set to 32px on a 640px wide browser, will effectively be seeing your site as shown to a user at 16px on a 320px wide browser. There's absolutely no loss for responsive web design (RWD) in using rem.

Changing Apparent px Value

Because rem is based on the font-size of the :root node, if you want to change what 1rem represents, all you have to do is change the font-size:

:root {
  font-size: 100px;
}
body {
  font-size: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Don't ever actually do this, please</p></code>```

Whatever you do, don't set the :root element's font-size to a px value.

If you set the font-size on html to a px value, you've blown away the user's preferences without a way to get them back.

If you want to change the apparent value of rem, use % units.

The math for this is reasonably straight-forward.

The apparent font-size of :root is 16px, but lets say we want to change it to 20px. All we need to do is multiply 16 by some value to get 20.

Set up your equation:

```<code>16 * X = 20
</code>```

And solve for X:

```<code>X = 20 / 16
X = 1.25
X = 125%
</code>```

:root {
  font-size: 125%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>If you're using the default font-size, I'm 20px tall.</p></code>```

Doing everything in multiples of 20 isn't all that great, but a common suggestion is to make the apparent size of rem equal to 10px. The magic number for that is 10/16 which is 0.625, or 62.5%.

:root {
  font-size: 62.5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>If you're using the default font-size, I'm 10px tall.</p></code>```

The problem now is that your default font-size for the rest of the page is set way too small, but there's a simple fix for that: Set a font-size on body using rem:

:root {
  font-size: 62.5%;
}

body {
  font-size: 1.6rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>I'm the default font-size</p></code>```

It's important to note, with this adjustment in place, the apparent value of rem is 10px which means any value you might have written in px can be converted directly to rem by bumping a decimal place.

```<code>padding: 20px;
</code>```

turns into

```<code>padding: 2rem;
</code>```

The apparent font-size you choose is up to you, so if you want there's no reason you can't use:

```<code>:root {
  font-size: 6.25%;
}
body {
  font-size: 16rem;
}
</code>```

and have 1rem equal 1px.

So there you have it, a simple solution to respect user wishes while also avoiding over-complicating your CSS.

Wait, so what's the catch?

I was afraid you might ask that. As much as I'd like to pretend that rem is magic and solves-all-things, there are still some issues of note. Nothing deal-breaking in my opinion, but I'm going to call them out so you can't say I didn't warn you.

Media Queries (use em)

One of the first issues you'll run into with rem involves media queries. Consider the following code:

```<code>:root {
  font-size: 1000px;
}
@media (min-width: 1rem) {
  :root {
    font-size: 1px;
  }
}
</code>```

Here the value of rem changes depending on whether the media-query applies, and the media query depends on the value of rem, so what on earth is going on?

rem in media queries uses the initial value of font-size and should not (see Safari section) take into account any changes that may have happened to the font-size of the :root element. In other words, it's apparent value is always 16px.

This is a bit annoying, because it means that you have to do some fractional calculations, but I have found that most common media queries already use values that are multiples of 16.

```<code>|   px | rem |
+------+-----+
|  320 |  20 |
|  480 |  30 |
|  768 |  48 |
| 1024 |  64 |
| 1200 |  75 |
| 1600 | 100 |
</code>```

Additionally if you're using a CSS preprocessor, you can use mixins or variables to manage your media queries, which will mask the issue entirely.

Safari

Unfortunately there's a known bug with Safari where changes to the :root font-size do actually change the calculated rem values for media query ranges. This can cause some very strange behavior if the font-size of the :root element is changed within a media query. Fortunately the fix is simple: use em units for media queries.

Context Switching

If you switch between projects various different projects, it's quite possible that the apparent font-size of rem will have different values. In one project, you might be using an apparent size of 10px where in another project the apparent size might be 1px. This can be confusing and cause issues.

My only recommendation here is to stick with 62.5% to convert rem to an apparent size of 10px, because that has been more common in my experience.

Shared CSS Libraries

If you're writing CSS that's going to be used on a site that you don't control, such as for an embedded widget, there's really no good way to know what apparent size rem will have. If that's the case, feel free to keep using px.

If you still want to use rem though, consider releasing a Sass or LESS version of the stylesheet with a variable to override the scaling for the apparent size of rem.

* I don't want to spook anyone away from using rem, but I haven't been able to officially confirm that every browser uses 16px by default. You see, there are a lot of browsers and it wouldn't be all that hard for one browser to have diverged ever so slightly to, say 15px or 18px. In testing, however I have not seen a single example where a browser using default settings in a system using default settings had any value other than 16px. If you find such an example, please share it with me.

ContentLicense: CC BY-SA 4.0

Body:
I would like to praise josh3736's answer for providing some excellent historical context. While it's well articulated, the CSS landscape has changed in the almost five years since this question was asked. When this question was asked, px was the correct answer, but that no longer holds true today.

tl;dr: use rem

Unit Overview

Historically px units typically represented one device pixel. With devices having higher and higher pixel density this no longer holds for many devices, such as with Apple's Retina Display.

rem units represent the root em size. It's the font-size of whatever matches :root. In the case of HTML, it's the <html> element; for SVG, it's the <svg> element. The default font-size in every browser* is 16px.

On Using px

The majority of CSS examples on the internet use px values because they were the de-facto standard. pt, in and a variety of other units could have been used in theory, but they didn't handle small values well as you'd quickly need to resort to fractions, which were longer to type, and harder to reason about.

If you wanted a thin border, with px you could use 1px, with pt you'd need to use 0.75pt for consistent results, and that's just not very convenient.

On Using rem

rem's default value of 16px isn't a very strong argument for its use. Writing 0.0625rem is worse than writing 0.75pt, so why would anyone use rem?

There are two parts to rem's advantage over other units.

User preferences are respected

You can change the apparent px value of rem to whatever you'd like

Respecting User Preferences

Browser zoom has changed a lot over the years. Historically many browsers would only scale up font-size, but that changed pretty rapidly when websites realized that their beautiful pixel-perfect designs were breaking any time someone zoomed in or out. At this point, browsers scale the entire page, so font-based zooming is out of the picture.

Respecting a user's wishes is not out of the picture. Just because a browser is set to 16px by default, doesn't mean any user can't change their preferences to 24px or 32px to correct for low vision or poor visibility (e.x. screen glare). If you base your units off of rem, any user at a higher font-size will see a proportionally larger site. Borders will be bigger, padding will be bigger, margins will be bigger, everything will scale up fluidly.

If you base your media queries on rem, you can also make sure that the site your users see fits their screen. A user with font-size set to 32px on a 640px wide browser, will effectively be seeing your site as shown to a user at 16px on a 320px wide browser. There's absolutely no loss for responsive web design (RWD) in using rem.

Changing Apparent px Value

Because rem is based on the font-size of the :root node, if you want to change what 1rem represents, all you have to do is change the font-size:

:root {
  font-size: 100px;
}
body {
  font-size: 1rem;
}

<p>Don't ever actually do this, please</p>

Whatever you do, don't set the :root element's font-size to a px value.

If you set the font-size on html to a px value, you've blown away the user's preferences without a way to get them back.

If you want to change the apparent value of rem, use % units.

The math for this is reasonably straight-forward.

The apparent font-size of :root is 16px, but lets say we want to change it to 20px. All we need to do is multiply 16 by some value to get 20.

Set up your equation:

16 * X = 20

And solve for X:

X = 20 / 16
X = 1.25
X = 125%

:root {
  font-size: 125%;
}

<p>If you're using the default font-size, I'm 20px tall.</p>

Doing everything in multiples of 20 isn't all that great, but a common suggestion is to make the apparent size of rem equal to 10px. The magic number for that is 10/16 which is 0.625, or 62.5%.

:root {
  font-size: 62.5%;
}

<p>If you're using the default font-size, I'm 10px tall.</p>

The problem now is that your default font-size for the rest of the page is set way too small, but there's a simple fix for that: Set a font-size on body using rem:

:root {
  font-size: 62.5%;
}

body {
  font-size: 1.6rem;
}

<p>I'm the default font-size</p>

It's important to note, with this adjustment in place, the apparent value of rem is 10px which means any value you might have written in px can be converted directly to rem by bumping a decimal place.

padding: 20px;

turns into

padding: 2rem;

The apparent font-size you choose is up to you, so if you want there's no reason you can't use:

:root {
  font-size: 6.25%;
}
body {
  font-size: 16rem;
}

and have 1rem equal 1px.

So there you have it, a simple solution to respect user wishes while also avoiding over-complicating your CSS.

Wait, so what's the catch?

I was afraid you might ask that. As much as I'd like to pretend that rem is magic and solves-all-things, there are still some issues of note. Nothing deal-breaking in my opinion, but I'm going to call them out so you can't say I didn't warn you.

Media Queries (use em)

One of the first issues you'll run into with rem involves media queries. Consider the following code:

:root {
  font-size: 1000px;
}
@media (min-width: 1rem) {
  :root {
    font-size: 1px;
  }
}

Here the value of rem changes depending on whether the media-query applies, and the media query depends on the value of rem, so what on earth is going on?

rem in media queries uses the initial value of font-size and should not (see Safari section) take into account any changes that may have happened to the font-size of the :root element. In other words, it's apparent value is always 16px.

This is a bit annoying, because it means that you have to do some fractional calculations, but I have found that most common media queries already use values that are multiples of 16.

|   px | rem |
+------+-----+
|  320 |  20 |
|  480 |  30 |
|  768 |  48 |
| 1024 |  64 |
| 1200 |  75 |
| 1600 | 100 |

Additionally if you're using a CSS preprocessor, you can use mixins or variables to manage your media queries, which will mask the issue entirely.

Safari

Unfortunately there's a known bug with Safari where changes to the :root font-size do actually change the calculated rem values for media query ranges. This can cause some very strange behavior if the font-size of the :root element is changed within a media query. Fortunately the fix is simple: use em units for media queries.

Context Switching

If you switch between projects various different projects, it's quite possible that the apparent font-size of rem will have different values. In one project, you might be using an apparent size of 10px where in another project the apparent size might be 1px. This can be confusing and cause issues.

My only recommendation here is to stick with 62.5% to convert rem to an apparent size of 10px, because that has been more common in my experience.

Shared CSS Libraries

If you're writing CSS that's going to be used on a site that you don't control, such as for an embedded widget, there's really no good way to know what apparent size rem will have. If that's the case, feel free to keep using px.

If you still want to use rem though, consider releasing a Sass or LESS version of the stylesheet with a variable to override the scaling for the apparent size of rem.

* I don't want to spook anyone away from using rem, but I haven't been able to officially confirm that every browser uses 16px by default. You see, there are a lot of browsers and it wouldn't be all that hard for one browser to have diverged ever so slightly to, say 15px or 18px. In testing, however I have not seen a single example where a browser using default settings in a system using default settings had any value other than 16px. If you find such an example, please share it with me.