问:
How to output debug info with the dropwizard-migrations liquibase module?
When you run liquibase on the command line, you can set the log level to debug with a command line option:

```<code>java -jar liquibase.jar \
  --driver=oracle.jdbc.OracleDriver \
  --classpath=\path\to\classes:jdbcdriver.jar \
  --changeLogFile=com/example/db.changelog.xml \
  --url="jdbc:oracle:thin:@localhost:1521:oracle" \
  --username=scott \
  --password=tiger \
  --logLevel=debug
  update
</code>```

Does anyone know how to set the log level when running liquibase via the dropwizard-migrations module?

```<code>java -jar /mydropwizardapp.jar db migrate config.yml
</code>```

(I am having a problem where it intermittently fails to get a lock (Waiting for changelog lock....) and my deployment fails, and I'd like to see more detail on what it is doing. I'm pretty sure the lock is not left from a previously failed deployment)

Thanks

答:
You can set the logging level to DEBUG on the YAML file:</p>

```<code>logging:
    level: DEBUG
</code>```

Body:
When you run liquibase on the command line, you can set the log level to debug with a command line option:

java -jar liquibase.jar \
  --driver=oracle.jdbc.OracleDriver \
  --classpath=\path\to\classes:jdbcdriver.jar \
  --changeLogFile=com/example/db.changelog.xml \
  --url="jdbc:oracle:thin:@localhost:1521:oracle" \
  --username=scott \
  --password=tiger \
  --logLevel=debug
  update

Does anyone know how to set the log level when running liquibase via the dropwizard-migrations module?

java -jar /mydropwizardapp.jar db migrate config.yml

(I am having a problem where it intermittently fails to get a lock (Waiting for changelog lock....) and my deployment fails, and I'd like to see more detail on what it is doing. I'm pretty sure the lock is not left from a previously failed deployment)

Thanks

Body:
You can set the logging level to DEBUG on the YAML file:

logging:
    level: DEBUG


来源: stackexchange

问:
Embedding a link in react render method
I am fairly new to React JS. I am inside the React render method. I want to embed a link inside of an if statement {menu.Title == "Club Finder" ?  "Club Finder"  : menu.Title}  but it is not rendering the html. Instead the html is being displayed in the navigation menu.  I can not figure out why this is. Any insight on this would be great.  My code is below:</p>

```<code>render() {
    if (!this.props.data.Items) {
      return (
        <div className="alert alert-danger">Menu is empty</div>
      );
    }
    const menuItems = this.props.data.Items.map((menu, index) => (
      <Hammer
        onTap={this.handleMenuTap}
        onClick={this.handleMenuClick}
        onClick={this.handleMenuEnter}
        key={`menu-item-${menu.Title}`}
      >
        <li
          id={`menu-item-${index}`}
        >
          {menu.Title == "Club Finder" ? "<a href='#'>Club Finder</a>"  : menu.Title} <span className="fa fa-chevron-down" />
        </li>
      </Hammer>
    ));
    return (
      <nav className="mega-main-menu">
        <div className="mega-main-menu__logo-container">
          <a className="mega-main-menu__logo" href="/">
            {
              this.props.data.Image ?
                (
                  <img
                    src={this.props.data.Image.Src}
                    alt={this.props.data.Image.Alt}
                    width="264"
                    height="50"
                  />
                ) : ''
            }
          </a>
        </div>
        <div className="mega-main-menu__nav-search-container">
          <Search show={this.state.showSearch} />
          <div className="mega-main-menu__items-container" onMouseLeave={this.handleMenuLeave}>
            <ul className="mega-main-menu__items list--nostyle" style={{ width: 'auto' }}>
              {menuItems}
              {
                this.state.megaMenuContent !== null ? (<MegaMenuOverlay content={this.state.megaMenuContent} />) : ''
              }
            </ul>
          </div>
          <button
            className="mega-main-menu__toggle-mobile btn btn-default"
            onClick={this.showMobileMenu}
          >
            <i className="fa fa-bars text-primary" />
          </button>
          <div className="mega-main-menu__actions">
            <a
              href="/login"
              className="btn bg-primary mega-main-menu__actions-login"
              ref={(button) => { this.usmsButton = button; }}
            >
              MY USMS
            </a>
            <i
              className="fa fa-search text-primary mega-main-menu__actions-search"
              onClick={this.toggleSearch}
            />
          </div>
        </div>
        <MobileMenu
          content={this.props.data.Items}
          handleCloseMenu={this.hideMobileMenu}
          showMobileMenu={this.state.showMobileMenu}
        />
      </nav>
    );
  }
</code>```

答:
Remove double quote from Club Finder hyperlink.

Its JSX.You don't need to put double quote "" around html.

```<code>{
 menu.Title == "Club Finder" ?
 <a href='#'>Club Finder</a>  :  //remove double quote from here.
 menu.Title
}
<span className="fa fa-chevron-down" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Embedding a link in react render method

Body:
I am fairly new to React JS. I am inside the React render method. I want to embed a link inside of an if statement {menu.Title == "Club Finder" ?  "Club Finder"  : menu.Title}  but it is not rendering the html. Instead the html is being displayed in the navigation menu.  I can not figure out why this is. Any insight on this would be great.  My code is below:

render() {
    if (!this.props.data.Items) {
      return (

Menu is empty

      );
    }
    const menuItems = this.props.data.Items.map((menu, index) => (
      <Hammer
        onTap={this.handleMenuTap}
        onClick={this.handleMenuClick}
        onClick={this.handleMenuEnter}
        key={`menu-item-${menu.Title}`}
      >
        <li
          id={`menu-item-${index}`}
        >
          {menu.Title == "Club Finder" ? "Club Finder"  : menu.Title}

      </Hammer>
    ));
    return (

            {
              this.props.data.Image ?
                (

                ) : ''
            }

          <Search show={this.state.showSearch} />

              {menuItems}
              {
                this.state.megaMenuContent !== null ? (<MegaMenuOverlay content={this.state.megaMenuContent} />) : ''
              }

          <button
            className="mega-main-menu__toggle-mobile btn btn-default"
            onClick={this.showMobileMenu}
          >

          </button>

             { this.usmsButton = button; }}
            >
              MY USMS

        <MobileMenu
          content={this.props.data.Items}
          handleCloseMenu={this.hideMobileMenu}
          showMobileMenu={this.state.showMobileMenu}
        />

    );
  }

Body:
Remove double quote from Club Finder hyperlink.

Its JSX.You don't need to put double quote "" around html.

{
 menu.Title == "Club Finder" ?
 <a href='#'>Club Finder</a>  :  //remove double quote from here.
 menu.Title
}
<span className="fa fa-chevron-down" />


问:
Is there a way to cap the max size on a STL::map container?
My application can only process up to a certain number of entry in the map structure, how do I specify that limit in my code so that my code does not get overwhelmed (for lack of better term).  Is there a way to specify the max limit when defining the variable of type map?

Thanks

答:
After trying out the idea of a capped allocator, I think it's way more straightforward to aggregate an std::map (note: not inherit-from!  At least not publicly) in a cappedadaptor.

```<code>template<typename tKey, typename tVal> class cappedmap {
   typedef std::map<tKey,tVal> tmap;
   tmap mymap;

   cappedmap(size_t amax):mymax(amax){}

   // adapt the map interface
   pair<tmap::iterator,bool> insert( tmap::value_type kv ) {
        if( mymap.size() > mymax ) throw myexcept();
        return mymap.insert(kv);
   }

   tVal operator[]( tKey k ) {
     tVal v = mymap[k];
     if( mymap.size() > mymax ) {
        mymap.remove(k)
        throw myexcept();
     }
   }
   ...
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
After trying out the idea of a capped allocator, I think it's way more straightforward to aggregate an std::map (note: not inherit-from!  At least not publicly) in a cappedadaptor.

template<typename tKey, typename tVal> class cappedmap {
   typedef std::map<tKey,tVal> tmap;
   tmap mymap;

   cappedmap(size_t amax):mymax(amax){}

   // adapt the map interface
   pair<tmap::iterator,bool> insert( tmap::value_type kv ) {
        if( mymap.size() > mymax ) throw myexcept();
        return mymap.insert(kv);
   }

   tVal operator[]( tKey k ) {
     tVal v = mymap[k];
     if( mymap.size() > mymax ) {
        mymap.remove(k)
        throw myexcept();
     }
   }
   ...
};


问:
tensorflow using restored (from saved )model get slower after some epochs
I want to save my model at the end of each epoch from this link

I did it in this way:

save:

```<code>model_dir = "{0}/epoch_{1}/res".format(train_dir, epoch_num)
saver.save(sess, model_dir, global_step=global_step_val)
</code>```

restore:

```<code> for ep_num in range(num_epochs):
        model_dir = "{0}/epoch_{1}/".format(train_dir, epoch_num)
        model_meta_file_name = [each for each in
        os.listdir(model_dir) if each.endswith('.meta')][0]
        meta_path="{0}/{1}".format(model_dir, model_meta_file_name)
        saver = tf.train.import_meta_graph(meta_path)
        saver.restore(sess, tf.train.latest_checkpoint(model_dir))
</code>```

and continue evaluating my model with evaluation data.

but after 7-8 epochs,my evaluating process gets very slow, I think I
   am saving some extra things, and after some epochs my graph is very
   big. How do I solve this?

one point: gpu utilization is almost zero during this evaluation
   process.I think fro some reason after some epochs,my process does
   noyt run on GPU

答:
saver = tf.train.import_meta_graph(meta_path)

This line should only run once. You call it at every epoch, and that adds new ops to the graph, so the evaluation becomes slower.

Body:
I want to save my model at the end of each epoch from this link

I did it in this way:

save:

model_dir = "{0}/epoch_{1}/res".format(train_dir, epoch_num)
saver.save(sess, model_dir, global_step=global_step_val)

restore:

 for ep_num in range(num_epochs):
        model_dir = "{0}/epoch_{1}/".format(train_dir, epoch_num)
        model_meta_file_name = [each for each in
        os.listdir(model_dir) if each.endswith('.meta')][0]
        meta_path="{0}/{1}".format(model_dir, model_meta_file_name)
        saver = tf.train.import_meta_graph(meta_path)
        saver.restore(sess, tf.train.latest_checkpoint(model_dir))

and continue evaluating my model with evaluation data.

but after 7-8 epochs,my evaluating process gets very slow, I think I
   am saving some extra things, and after some epochs my graph is very
   big. How do I solve this?

one point: gpu utilization is almost zero during this evaluation
   process.I think fro some reason after some epochs,my process does
   noyt run on GPU


问:
Entity Framework: Find related navigation property by FK property
I need to find the related navigation property of a FK property.

This is my model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}
```

<p>Now, I want to write something like this:
</p>

```var context = new BloggingContext();
var navigationProperty = GetNavigationProperty(context, typeof(Post), "BlogId"); // returns "Blog"
```

I'm using EF 6.2 with code first.

Thank you for any help!

答:
After a lot of research, I didn't find ant resource or sample how to do it, but I found a temporary solution with the following code, I don't know if it is the optimal way or there is exceptions with it.

public static string GetNavigationByForeignKey(this DbContext context, Type entityType, string fkPropertyName)
{
    var objectContext = (context as IObjectContextAdapter).ObjectContext;

    var entityMetadata = objectContext.MetadataWorkspace
        .GetItems<EntityType>(DataSpace.CSpace)
        .FirstOrDefault(et => et.Name == entityType.Name);

    var navigationProperty = entityMetadata.NavigationProperties
        .FirstOrDefault(prop => prop.GetDependentProperties().Any(dep => dep.Name == fkPropertyName));

    return navigationProperty.Name;
}
```

if someone have a better solution, I would be grateful.

Body:
I need to find the related navigation property of a FK property.

This is my model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

Now, I want to write something like this:

var context = new BloggingContext();
var navigationProperty = GetNavigationProperty(context, typeof(Post), "BlogId"); // returns "Blog"

I'm using EF 6.2 with code first.

Thank you for any help!

Body:
After a lot of research, I didn't find ant resource or sample how to do it, but I found a temporary solution with the following code, I don't know if it is the optimal way or there is exceptions with it.

public static string GetNavigationByForeignKey(this DbContext context, Type entityType, string fkPropertyName)
{
    var objectContext = (context as IObjectContextAdapter).ObjectContext;

    var entityMetadata = objectContext.MetadataWorkspace
        .GetItems<EntityType>(DataSpace.CSpace)
        .FirstOrDefault(et => et.Name == entityType.Name);

    var navigationProperty = entityMetadata.NavigationProperties
        .FirstOrDefault(prop => prop.GetDependentProperties().Any(dep => dep.Name == fkPropertyName));

    return navigationProperty.Name;
}

if someone have a better solution, I would be grateful.


问:
Adding leading and trailing spaces to uitableview of child class inherited from parent class programmatically using swift
I am trying to add leading and trailing spaces to tableview embedded in view programmatically. This tableview has constraints been declared in parent class i am trying to override them in child class. I am doing in the following way

```<code>class TestTableView: BaseTableViewController{

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.lpBaseTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.lpBaseTableView.contentSize.height)
    self.lpBaseTableView.center = self.view.center
    self.lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    self.lpBaseTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16).isActive = true
    self.lpBaseTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 16).isActive = true

 }
}
</code>```

After researching few links from stack overflow i am using the above code but there is no change in the table view position as shown below in the image. Please help me out. I am new to swift and iOS

答:
You can try with SnaKit

```<code>    import SnapKit

    lpBaseTableView.snp.makeConstraints { (make) in
    make.center.equalTo(view)
    make.left.equalTo(view.snp.left)
    make.right.equalTo(view.snp.right)
</code>```

Please note that if there is also constraints from Storyboard for same object it could not work properly

Body:
I am trying to add leading and trailing spaces to tableview embedded in view programmatically. This tableview has constraints been declared in parent class i am trying to override them in child class. I am doing in the following way

class TestTableView: BaseTableViewController{

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.lpBaseTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.lpBaseTableView.contentSize.height)
    self.lpBaseTableView.center = self.view.center
    self.lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    self.lpBaseTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16).isActive = true
    self.lpBaseTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 16).isActive = true

 }
}

After researching few links from stack overflow i am using the above code but there is no change in the table view position as shown below in the image. Please help me out. I am new to swift and iOS

Body:
You can try with SnaKit

    import SnapKit

    lpBaseTableView.snp.makeConstraints { (make) in
    make.center.equalTo(view)
    make.left.equalTo(view.snp.left)
    make.right.equalTo(view.snp.right)

Please note that if there is also constraints from Storyboard for same object it could not work properly


问:
how to convert the passed in price value to cents before saving to database?
I have create action that will create a karaoke object.

```<code>  def create
    @user = current_user
    @karaoke = @user.karaokes.build(karaoke_params)

    respond_to do |format|
      if @karaoke.save
        format.html { redirect_to @karaoke, notice: 'Karaoke was successfully created.' }
        format.json { render :show, status: :created, location: @karaoke }
      else
        format.html { render :new }
        format.json { render json: @karaoke.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

i have allowed the following parameters to bind

```<code># Never trust parameters from the scary internet, only allow the white list through.
def karaoke_params
  params.require(:karaoke).permit(:name, :audio, :price)
end
</code>```

Now what i want to do is in database the price field is of type integers because i am saving money as cents in database. So, in create action, before saving the user parameter for price, i want to multiply by 100 to convert it to cents. How can i multiply the passed in price form value by 100 and assign it to price field of Karaoke object? I appreciate any help! Thanks!

The form to accept the karaoke parameters are as follows

```<code><%= form_for(@karaoke) do |f| %>
  <% if @karaoke.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@karaoke.errors.count, "error") %> prohibited this karaoke from being saved:</h2>

      <ul>
      <% @karaoke.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :price %><br>
    <%= f.text_field :price %>
  </div>

  <div class="field">
    <%= f.label :audio %><br>
    <%= f.file_field :audio %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
You can rewrite the setter for price in the Karaoke model in order to convert any Float into Integer:

```<code>def price=(value)
  value = (value * 100).to_i if value.kind_of?(Float)
  super(value)
end
</code>```

So now every time you pass a Float for the price of a Karaoke, it will be multiplied by 100 and converted to an Integer.

Body:
I have create action that will create a karaoke object.

  def create
    @user = current_user
    @karaoke = @user.karaokes.build(karaoke_params)

    respond_to do |format|
      if @karaoke.save
        format.html { redirect_to @karaoke, notice: 'Karaoke was successfully created.' }
        format.json { render :show, status: :created, location: @karaoke }
      else
        format.html { render :new }
        format.json { render json: @karaoke.errors, status: :unprocessable_entity }
      end
    end
  end

i have allowed the following parameters to bind

# Never trust parameters from the scary internet, only allow the white list through.
def karaoke_params
  params.require(:karaoke).permit(:name, :audio, :price)
end

Now what i want to do is in database the price field is of type integers because i am saving money as cents in database. So, in create action, before saving the user parameter for price, i want to multiply by 100 to convert it to cents. How can i multiply the passed in price form value by 100 and assign it to price field of Karaoke object? I appreciate any help! Thanks!

The form to accept the karaoke parameters are as follows

<%= form_for(@karaoke) do |f| %>
  <% if @karaoke.errors.any? %>

<%= pluralize(@karaoke.errors.count, "error") %> prohibited this karaoke from being saved:

      <% @karaoke.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :price %>

    <%= f.text_field :price %>

    <%= f.label :audio %>

    <%= f.file_field :audio %>

    <%= f.submit %>

<% end %>

Body:
You can rewrite the setter for price in the Karaoke model in order to convert any Float into Integer:

def price=(value)
  value = (value * 100).to_i if value.kind_of?(Float)
  super(value)
end

So now every time you pass a Float for the price of a Karaoke, it will be multiplied by 100 and converted to an Integer.


问:
need help with an odd json parsing issue
I have odd problems with parsing what I believe to be well-formed json returned from an ajax call (using jQuery 1.4.4). Oddly, on my dev server it works fine but fails online.

The data is returned from the ajax call as follows:

```<code>returnData = { "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } };
</code>```

jsLint and jsonLint both validate this structure.

The error occurs when I try to access returnData.data

In the "fail" cases, I have removed the dataType from the jQuery.ajax options, thereby allowing the "best-guess" feature.  If I specify json, jQuery throws a parse error, claiming invalid json. I have tried all kinds of things (including the dreaded eval() and the jquery-2json plugin but no luck.  Even the jQ utility jQuery.parseJSON fails.

The problem occurs in both FF 3.6.13 and latest Safari / Chrome.

Question 1: does anyone why know the latest jQuery throws a parse error on this?

Question 2: when I try the following, I have success:

var success = returnData.status;

BUT the following is undefined:

var errorReturn = returnData.data.error_return.

Oddly, Firebug sees this as an object if I "paste" the object into the console, but within the script
1) returns "no child objects" in console.dir
2) BUT will display the object in console.log.

Ideas greatly appreciated

UPDATE:
I discovered that the server was setting the Content type incorrectly.  In the server-side PHP that formats the JSON for return (created in this case in Drupal 6 (I had to hack the core-optional include "commons.inc"), I replaced the content type with 'application/json'. This now works. This problem has been corrected in Drupal 7.

答:
If your quoted text is actually what's being returned, complete with the return_data = part, then it's invalid JSON.

If your ajax call looks like this:

```<code>$.ajax({
    url: "your_url",
    success: function(data) {

    }
});
</code>```

...and within success you want to access the status value, your JSON should look like this:

```<code>{ "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } }
</code>```

(Note, no return_data = at the beginning, no ; at the end.)

...and your success function should look like this:

```<code>success: function(data) {
    if (data.status) {
        // ...
    }
}
</code>```

Live example

That example works with the latest Chrome, Firefox, Opera, ..., using the latest jQuery. Perhaps at some stage you were using a JSON parser that used eval under the covers. Your quoted example is valid JavaScript object literal notation as part of an assignment statement, but not valid JSON. Some "JSON" parsers actually use eval to parse JavaScript rather than JSON, that may have been your issue.

Body:
I have odd problems with parsing what I believe to be well-formed json returned from an ajax call (using jQuery 1.4.4). Oddly, on my dev server it works fine but fails online.

The data is returned from the ajax call as follows:

returnData = { "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } };

jsLint and jsonLint both validate this structure.

The error occurs when I try to access returnData.data

In the "fail" cases, I have removed the dataType from the jQuery.ajax options, thereby allowing the "best-guess" feature.  If I specify json, jQuery throws a parse error, claiming invalid json. I have tried all kinds of things (including the dreaded eval() and the jquery-2json plugin but no luck.  Even the jQ utility jQuery.parseJSON fails.

The problem occurs in both FF 3.6.13 and latest Safari / Chrome.

Question 1: does anyone why know the latest jQuery throws a parse error on this?

Question 2: when I try the following, I have success:

var success = returnData.status;

BUT the following is undefined:

var errorReturn = returnData.data.error_return.

Oddly, Firebug sees this as an object if I "paste" the object into the console, but within the script
1) returns "no child objects" in console.dir
2) BUT will display the object in console.log.

Ideas greatly appreciated

UPDATE:
I discovered that the server was setting the Content type incorrectly.  In the server-side PHP that formats the JSON for return (created in this case in Drupal 6 (I had to hack the core-optional include "commons.inc"), I replaced the content type with 'application/json'. This now works. This problem has been corrected in Drupal 7.

Body:
If your quoted text is actually what's being returned, complete with the return_data = part, then it's invalid JSON.

If your ajax call looks like this:

$.ajax({
    url: "your_url",
    success: function(data) {

    }
});

...and within success you want to access the status value, your JSON should look like this:

{ "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } }

(Note, no return_data = at the beginning, no ; at the end.)

...and your success function should look like this:

success: function(data) {
    if (data.status) {
        // ...
    }
}

Live example

That example works with the latest Chrome, Firefox, Opera, ..., using the latest jQuery. Perhaps at some stage you were using a JSON parser that used eval under the covers. Your quoted example is valid JavaScript object literal notation as part of an assignment statement, but not valid JSON. Some "JSON" parsers actually use eval to parse JavaScript rather than JSON, that may have been your issue.


问:
Web Api - separating workflow from BL
My teammates and I argued about what code the web api controller should hold. We all agree that the controller should not hold business logic but we don't agree on where to place the workflow and if the workflow should be entirely separated from the business logic.

They think that the endpoint should look something like this:

Controller code:

```<code>public Response EndPoint(...)
{
    var flow = new SomeFlow();
    var response = flow.RunFlow(...);
    return response;
}
</code>```

Flow code:

```<code>public class SomeFlow
{
    public HttpResponseMessage Activate(....)
    {
        var service = new Service();
        var entities = someService.GetEntities();
        if(entities == null) return new HttpResponseMessage(HttpStatusCode.NotFound);

        foreach(var entity in entities)
        {
            BusinessLogicClass/Model.DoSomething(entity)
        }

        .....
        .....
    }
}
</code>```

SomeFlow.cs class is located under the Business logic project in the solution.

I've showed them this stackoverflow answer:
https://stackoverflow.com/a/12694104/9062092
but they are still saying this code is more readable.

The thing that disturbes me the most is that the flows classes are located under the business logic project and I think it encourages developers to put business logic inside the flow class and couples the BL with the workflow. I don't see a reason to create this class that has only one public method and will only be used once inside the project.

It is testable on both ways but a bit harder to test pure BL when it is located inside the flow class.

Does the workflow considered as business logic?

Thanks for the replies!

答:
As said in the post you attached,the controller should be a middle tier between the client and the logic.

There are some advantages for separating the workflow from the logic, the most important one is preventing high coupling between them, and making it possible to test each of them separately.

In my opinion, if the flow is not very complex and without any logic it can sit under the controller, a complex flow that contains logic is the only reason to extract the flow from the controller.

Title: Web Api - separating workflow from BL

Body:
My teammates and I argued about what code the web api controller should hold. We all agree that the controller should not hold business logic but we don't agree on where to place the workflow and if the workflow should be entirely separated from the business logic.

They think that the endpoint should look something like this:

Controller code:

public Response EndPoint(...)
{
    var flow = new SomeFlow();
    var response = flow.RunFlow(...);
    return response;
}

Flow code:

public class SomeFlow
{
    public HttpResponseMessage Activate(....)
    {
        var service = new Service();
        var entities = someService.GetEntities();
        if(entities == null) return new HttpResponseMessage(HttpStatusCode.NotFound);

        foreach(var entity in entities)
        {
            BusinessLogicClass/Model.DoSomething(entity)
        }

        .....
        .....
    }
}

SomeFlow.cs class is located under the Business logic project in the solution.

I've showed them this stackoverflow answer:
https://stackoverflow.com/a/12694104/9062092
but they are still saying this code is more readable.

The thing that disturbes me the most is that the flows classes are located under the business logic project and I think it encourages developers to put business logic inside the flow class and couples the BL with the workflow. I don't see a reason to create this class that has only one public method and will only be used once inside the project.

It is testable on both ways but a bit harder to test pure BL when it is located inside the flow class.

Does the workflow considered as business logic?

Thanks for the replies!


问:
How to parse markdown in react-native (esp. android)?
Since React Native webview components is only support iOS, I wonder what other options are available to parse markdown strings for android. Anyone had worked with markdown in React Native for Android app?</p>

答:
I recommend react-native-markdown-view which we're using at 2minute.com.

It's the only RN Markdown lib I found that properly renders a list.  It's also the only one to have merged a pull request in the last month.

Alternatives: I've tried others in some depth but they can't do lists properly. react-native-simple-markdown renders the list bullet in the middle instead of at the top of the list item, and the styling was also bugged. react-native-markdown-renderer renders lists off the right side of the screen.  react-native-markdown hasn't been touched in 3 years so I skipped that one.


问:
Count the number of filled cells between empty cells in pandas
Below is an example of part of my dataframe:

```<code>col1     col2
items1    10
items1     5
items1     3
items1     2
items1   NaN
items1   NaN
items1   NaN
items1     4
items1     1
items1     1
items2     6
items2     4
items2     5
items2   NaN
items2   NaN
items2     2
items2     8
items2     7
items2     9
items2   NaN
...
</code>```

I need for every unique value in column col1 to count number of non empty cells between empty cells. I tried to use groupby() for grouping unique values in col1 and count() to count values, but it count all non empty values for unique values in col1.

Here is my code:

```<code>df = pd.DataFrame({'col1':('items1','items1','items1','items1','items1','items1','items1','items1','items1','items1','items2','items2','items2','items2','items2','items2','items2','items2','items2','items2'),
                  'col2': (10, 5, 3, 2, np.nan, np.nan, np.nan, 4, 1, 1, 6, 4, 5, np.nan, np.nan, 2, 8, 7, 9, np.nan)})
df.groupby('col1')['col2'].count().reset_index()
</code>```

The result looks like this:

```<code>      col1  col2
0   items1     7
1   items2     7
</code>```

But I need to get the following:

```<code>      col1  col2
0   items1     4
1   items1     3
2   items2     3
3   items2     4
</code>```

I would be grateful for any advice!

答:
IIUC, PS:I did not add the reset_index() it will make the code tooo long..

```<code>df.groupby([df['col1'],df['col2'].isnull().diff().fillna(0).cumsum()])['col2'].count().replace(0,np.nan).dropna()
Out[885]:
col1    col2
items1  0       4.0
        2       3.0
items2  2       3.0
        4       4.0
Name: col2, dtype: float64
</code>```

Body:
Below is an example of part of my dataframe:

col1     col2
items1    10
items1     5
items1     3
items1     2
items1   NaN
items1   NaN
items1   NaN
items1     4
items1     1
items1     1
items2     6
items2     4
items2     5
items2   NaN
items2   NaN
items2     2
items2     8
items2     7
items2     9
items2   NaN
...

I need for every unique value in column col1 to count number of non empty cells between empty cells. I tried to use groupby() for grouping unique values in col1 and count() to count values, but it count all non empty values for unique values in col1.

Here is my code:

df = pd.DataFrame({'col1':('items1','items1','items1','items1','items1','items1','items1','items1','items1','items1','items2','items2','items2','items2','items2','items2','items2','items2','items2','items2'),
                  'col2': (10, 5, 3, 2, np.nan, np.nan, np.nan, 4, 1, 1, 6, 4, 5, np.nan, np.nan, 2, 8, 7, 9, np.nan)})
df.groupby('col1')['col2'].count().reset_index()

The result looks like this:

      col1  col2
0   items1     7
1   items2     7

But I need to get the following:

      col1  col2
0   items1     4
1   items1     3
2   items2     3
3   items2     4

I would be grateful for any advice!

Body:
IIUC, PS:I did not add the reset_index() it will make the code tooo long..

df.groupby([df['col1'],df['col2'].isnull().diff().fillna(0).cumsum()])['col2'].count().replace(0,np.nan).dropna()
Out[885]:
col1    col2
items1  0       4.0
        2       3.0
items2  2       3.0
        4       4.0
Name: col2, dtype: float64


问:
Split path by "\\" in C#
How can I split a path by "\\"? It gives me a syntax error if I use

path.split("\\");
```

答:
To be on the safe side, you could use:</p>

```<code>path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Split path by "\\" in C#

Body:
To be on the safe side, you could use:

path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });


问:
INSERTING INTO table on Linked Server
I have this

```<code>IF @publishdr = 1
BEGIN
TRUNCATE TABLE [LINKEDSERVERNAME].[Website-LIVE].[dbo].[VehicleData]
INSERT INTO [LINKEDSERVERNAME].[Website-LIVE].[dbo].[VehicleData]
(VehicleRef, Type, CapId, Maintenance,
CH_2YR_SOURCE, CH_3YR_SOURCE, CH_4YR_SOURCE, PCH_2YR_SOURCE, PCH_3YR_SOURCE, PCH_4YR_SOURCE,
Manufacturer, Model, ShortModText, Derivative, ShortDerText, ManufacturerUrl, ModelUrl, ShortModTextUrl, DerivativeUrl, ShortDerTextUrl, VehicleUrl,
Category, LoCatCode, Fuel, Transmission, Doors, DriveTrain, Seats, Mpg, BodyType, BodyTypeId,
CO2, EngineSize, InsuranceGroup, BHP, ManufacturerRRP,
VanCategory, VanMaxPayload, VanMaxLoadLength, VanMaxLoadWidthBetweenArches, VanMaxLoadWidth, VanMaxLoadHeight,
Co2TaxMonthly, Co2Tax40Monthly, IsInStock, AdhocVehicleRef,
InfoJson)
SELECT VehicleRef, Type, CapId, Maintenance,
CH_2YR_SOURCE, CH_3YR_SOURCE, CH_4YR_SOURCE, PCH_2YR_SOURCE, PCH_3YR_SOURCE, PCH_4YR_SOURCE,
Manufacturer, Model, ShortModText, Derivative, ShortDerText, ManufacturerUrl, ModelUrl, ShortModTextUrl, DerivativeUrl, ShortDerTextUrl, VehicleUrl,
Category, LoCatCode, Fuel, Transmission, Doors, DriveTrain, Seats, Mpg, BodyType, BodyTypeId,
CO2, EngineSize, InsuranceGroup, BHP, ManufacturerRRP,
VanCategory, VanMaxPayload, VanMaxLoadLength, VanMaxLoadWidthBetweenArches, VanMaxLoadWidth, VanMaxLoadHeight,
Co2TaxMonthly, Co2Tax40Monthly, IsInStock, AdhocVehicleRef,
InfoJson
FROM #VehicleData
END
</code>```

I get this error:

The object name 'LINKEDSERVERNAME.Website-LIVE.dbo.VehicleData' contains more than the maximum number of prefixes. The maximum is 2.

I thought that was the correct syntax to specify tables on a linked server.

Thanks

答:
The error might be due to the fact that you are trying to TRUNCATE TABLE across the linked server, which is not supported.

Try this instead:

```<code>EXEC [LINKEDSERVERNAME].[Website-LIVE].[sys].[sp_executesql] N'TRUNCATE TABLE dbo.VehicleData';
</code>```

Title: INSERTING INTO table on Linked Server

Body:
I have this

IF @publishdr = 1
BEGIN
TRUNCATE TABLE [LINKEDSERVERNAME].[Website-LIVE].[dbo].[VehicleData]
INSERT INTO [LINKEDSERVERNAME].[Website-LIVE].[dbo].[VehicleData]
(VehicleRef, Type, CapId, Maintenance,
CH_2YR_SOURCE, CH_3YR_SOURCE, CH_4YR_SOURCE, PCH_2YR_SOURCE, PCH_3YR_SOURCE, PCH_4YR_SOURCE,
Manufacturer, Model, ShortModText, Derivative, ShortDerText, ManufacturerUrl, ModelUrl, ShortModTextUrl, DerivativeUrl, ShortDerTextUrl, VehicleUrl,
Category, LoCatCode, Fuel, Transmission, Doors, DriveTrain, Seats, Mpg, BodyType, BodyTypeId,
CO2, EngineSize, InsuranceGroup, BHP, ManufacturerRRP,
VanCategory, VanMaxPayload, VanMaxLoadLength, VanMaxLoadWidthBetweenArches, VanMaxLoadWidth, VanMaxLoadHeight,
Co2TaxMonthly, Co2Tax40Monthly, IsInStock, AdhocVehicleRef,
InfoJson)
SELECT VehicleRef, Type, CapId, Maintenance,
CH_2YR_SOURCE, CH_3YR_SOURCE, CH_4YR_SOURCE, PCH_2YR_SOURCE, PCH_3YR_SOURCE, PCH_4YR_SOURCE,
Manufacturer, Model, ShortModText, Derivative, ShortDerText, ManufacturerUrl, ModelUrl, ShortModTextUrl, DerivativeUrl, ShortDerTextUrl, VehicleUrl,
Category, LoCatCode, Fuel, Transmission, Doors, DriveTrain, Seats, Mpg, BodyType, BodyTypeId,
CO2, EngineSize, InsuranceGroup, BHP, ManufacturerRRP,
VanCategory, VanMaxPayload, VanMaxLoadLength, VanMaxLoadWidthBetweenArches, VanMaxLoadWidth, VanMaxLoadHeight,
Co2TaxMonthly, Co2Tax40Monthly, IsInStock, AdhocVehicleRef,
InfoJson
FROM #VehicleData
END

I get this error:

The object name 'LINKEDSERVERNAME.Website-LIVE.dbo.VehicleData' contains more than the maximum number of prefixes. The maximum is 2.

I thought that was the correct syntax to specify tables on a linked server.

Thanks

Body:
The error might be due to the fact that you are trying to TRUNCATE TABLE across the linked server, which is not supported.

Try this instead:

EXEC [LINKEDSERVERNAME].[Website-LIVE].[sys].[sp_executesql] N'TRUNCATE TABLE dbo.VehicleData';


问:
GODI installation issue
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.

```<code>$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!
</code>```

I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being:

```<code> /home/nlucaroni/godi/etc
</code>```

(...and the directory exists, with the godi.conf file present). So, I can't figure out why ./bootstrap_stage2 isn't working.

答:
Hey Chris, I just figured it out. Silly mistake.

It was just a permission issue, running everything from /tmp/ worked fine --well after enabling GODI_BASEPKG_PCRE in godi.conf. I had been running it from my home directory, you forget simple things like that at 3:00am.

--

Actually I'm having another problem. Installing conf-opengl-6:

GODI can't seen to find the GL/gl.h file, though I can --you can see that it is Checking the suggestion.

```<code>> ===> Configuring for conf-opengl-6
> Checking the suggestion
>   Include=/usr/include/GL/gl.h Library=/<GLU+GL>
> Checking /usr:
>   Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL>
> Checking /usr:
>   Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Checking /usr/local:
>   Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Exception: Failure "Cannot find library".
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code

### Error: Command fails with code 1: godi_console
</code>```

edit - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine.

OwnerDisplayName: nlucaroni

Title: GODI installation issue

Body:
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.

$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!

I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being:

 /home/nlucaroni/godi/etc

(...and the directory exists, with the godi.conf file present). So, I can't figure out why ./bootstrap_stage2 isn't working.

LastEditorDisplayName: nlucaroni

Body:
Hey Chris, I just figured it out. Silly mistake.

It was just a permission issue, running everything from /tmp/ worked fine --well after enabling GODI_BASEPKG_PCRE in godi.conf. I had been running it from my home directory, you forget simple things like that at 3:00am.

--

Actually I'm having another problem. Installing conf-opengl-6:

GODI can't seen to find the GL/gl.h file, though I can --you can see that it is Checking the suggestion.

> ===> Configuring for conf-opengl-6
> Checking the suggestion
>   Include=/usr/include/GL/gl.h Library=/<GLU+GL>
> Checking /usr:
>   Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL>
> Checking /usr:
>   Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Checking /usr/local:
>   Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Exception: Failure "Cannot find library".
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code

### Error: Command fails with code 1: godi_console

edit - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine.


问:
Learning Clojure coming from Lisp
I'm thinking seriously of making Clojure my new hacking language since I love Lisp but have some problems with CL and Scheme. I've never worked in the Java environment before and my lisp experience is limited to working through "SICP" and "The Little Schemer."

What do I need to know? Are there any good resources on "The Clojure way?" Any resources on Clojure style? I've found Mark Volkmann's excellent page, but the books I've looked through seem a little spare.

Also, what do I need to know about Java? I'd rather not learn Java just to learn Clojure, but I imagine I'll have to know at least a little. Also, what is the workflow like? My experience is limited to dynamic languages, so I have no idea what I'd have to do to distribute an application without source on the JVM.

I've googled this obviously, but there's a large amount of information and not very much "clojure specific" stuff.

I guess I'm looking for some sensible suggestions on the kind of literature I should read in some sort of logical sequence.

答:
Just a quick perspective from someone who came to Clojure from the other direction (Java -> Clojure)

I actually found the Lispy parts of Clojure easy to learn once I got my around the syntax and common idioms. I expect that will be even easier for you.

You don't really need much knowledge of Java to do most things - you can do pretty much everything in pure Clojure if you want to.

It's probably only when you start wanting to use Java libraries that you will need to dive into Java interop. Fortunately, the interop is very simple - it's more LISP-style than Java style, so the only thing you will need to figure out is how to understand Java interfaces and make the appropriate call from the Clojure side.

For my environment, I use Eclipse + Counterclockwise. This works exceptionally well if you like IDEs and/or think you may ultimately want to do some work in Java as well. It requires no further dependencies, gives you an excellent debugger, has a full REPL (an embedded nREPL I believe), does all the project file management (Git, SVN etc.) and automatically handles things like the Java classpath setup for you (which can be a major obstacle for newcomers to Java!). I'd recommend checking it out if you think that might suit your style, I've also heard good things about Enclojure as well.

If you're not into IDEs, then you're probably best with your favourite text editor and command line tools as semperos suggests in his excellent answer.

Title: Learning Clojure coming from Lisp


问:
docker compose Logstash - specify config file and install plugin?
Im trying to copy my Logstash config and install a plugin at the same time. Ive tried multiple methods thus far with no avail, Logstash exists with errors every time

this fails:

```<code>logstash:
  image: logstash:latest
  command: logstash -f /etc/logstash/conf.d/logstash.conf
  command: bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this fails:

```<code>command: logstash -f /etc/logstash/conf.d/logstash.conf bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this fails:

```<code>command: logstash -f /etc/logstash/conf.d/logstash.conf && bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this also fails

```<code>command: bash -c logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate
</code>```

Im having no luck here and I bet the answer is simple... can anyone point me in the right direction?

Thanks

答:
try this if it's Ubuntu image

command: bash -c "logstash -f /etc/logstash/conf.d/logstash.conf && bin/- install logstash-filter-translate".

Else it's Alpine image then use

command : sh  -c " command to run "

Body:
Im trying to copy my Logstash config and install a plugin at the same time. Ive tried multiple methods thus far with no avail, Logstash exists with errors every time

this fails:

logstash:
  image: logstash:latest
  command: logstash -f /etc/logstash/conf.d/logstash.conf
  command: bash -c bin/logstash-plugin install logstash-filter-translate

this fails:

command: logstash -f /etc/logstash/conf.d/logstash.conf bash -c bin/logstash-plugin install logstash-filter-translate

this fails:

command: logstash -f /etc/logstash/conf.d/logstash.conf && bash -c bin/logstash-plugin install logstash-filter-translate

this also fails

command: bash -c logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate

Im having no luck here and I bet the answer is simple... can anyone point me in the right direction?

Thanks


问:
How to connect to db with mongo shell using MONGOLAB_URI?
On heroku everything what is needed to connect to db is stored in MONGOLAB_URI variable. But it is used primary by mongo drivers - not humans.

```<code>$ heroku config
=== app Config Vars
LANG:                     en_US.UTF-8
MONGOLAB_URI:             mongodb://heroku_app123456:2fsf445D@ds039880.mongolab.com:39880/heroku_app123456
</code>```

Is there some fast method how to connect to db using just mongo shell?

答: I'm not sure there is a way to do this from the mongo shell, but from the terminal you can just run mongo [mongodb uri]

Body:
On heroku everything what is needed to connect to db is stored in MONGOLAB_URI variable. But it is used primary by mongo drivers - not humans.

$ heroku config
=== app Config Vars
LANG:                     en_US.UTF-8
MONGOLAB_URI:             mongodb://heroku_app123456:2fsf445D@ds039880.mongolab.com:39880/heroku_app123456

Is there some fast method how to connect to db using just mongo shell?


问:
Overriding public static const members in child classes
I have a piece of working code that I am not sure about. See below for a mocked up version. The jist of it is I have a Foo class, a ChildFoo class and Bar class which has an instance of Foo. Foo presents some keys to Bar to parse a json dictionary. Bar is generic and used in multiple ways, Foo is subclassed for each implementation.

I have a public static const std::string in Foo, which defaults to "" in which case the Bar method to parse the value out just uses its own name instead of a specific key. I override PARAM_VALUE in ChildFoo because it's json dictionary is more complicated and provides {value: [], type:[], ...}, whereas other implementations just return {mName: []}.

Foo.h:

```<code>class Foo
{
public:
    static const std::string PARAM_VALUE;
}
</code>```

Foo.cpp:

```<code>const std::string Foo::PARAM_VALUE = "";

Foo::Foo ()
{
...
}
</code>```

ChildFoo.cpp:

```<code>const std::string Foo::PARAM_VALUE = "value";

ChildFoo::ChildFoo() : Foo()
{
...
}
</code>```

Bar.h

```<code>class Bar
{
private:
    std::string mName;
    ChildFoo * mFoo;
}
</code>```

Bar.cpp:

```<code>Bar::Bar ()
{
...
}

int Bar::parseValue ()
{
    std::string key;
    if (!mFoo->PARAM_VALUE.empty()) {
        key = mFoo->PARAM_VALUE;
    }
    else {
        key = mName;
    }
    ...
}
</code>```

I assumed I would have to go down the route of virtual getters for these keys, but thought I would try this out and was slightly surprised to find it works. On thinking about it, I believe it works because Foo::PARAM_VALUE is overridden by ChildFoo at compile time, so the const isn't restrictive at that point. I'm not completely sure, though.

Is it unsurprising that this works? Is this considered OK? Are there any drawbacks that could come from doing things in this way?

Cheers,
Gary

答:
I'm not convinced that your linker would allow this, the behaviour is certainly undefined if it does.

Your code is in violation of the one definition rule.

You can resort to variable shadowing if you want, but bear in mind that this would not be polymorphic. If you want polymorphism, then you'd need to use virtual functions.

Body:
I have a piece of working code that I am not sure about. See below for a mocked up version. The jist of it is I have a Foo class, a ChildFoo class and Bar class which has an instance of Foo. Foo presents some keys to Bar to parse a json dictionary. Bar is generic and used in multiple ways, Foo is subclassed for each implementation.

I have a public static const std::string in Foo, which defaults to "" in which case the Bar method to parse the value out just uses its own name instead of a specific key. I override PARAM_VALUE in ChildFoo because it's json dictionary is more complicated and provides {value: [], type:[], ...}, whereas other implementations just return {mName: []}.

Foo.h:

class Foo
{
public:
    static const std::string PARAM_VALUE;
}

Foo.cpp:

const std::string Foo::PARAM_VALUE = "";

Foo::Foo ()
{
...
}

ChildFoo.cpp:

const std::string Foo::PARAM_VALUE = "value";

ChildFoo::ChildFoo() : Foo()
{
...
}

Bar.h

class Bar
{
private:
    std::string mName;
    ChildFoo * mFoo;
}

Bar.cpp:

Bar::Bar ()
{
...
}

int Bar::parseValue ()
{
    std::string key;
    if (!mFoo->PARAM_VALUE.empty()) {
        key = mFoo->PARAM_VALUE;
    }
    else {
        key = mName;
    }
    ...
}

I assumed I would have to go down the route of virtual getters for these keys, but thought I would try this out and was slightly surprised to find it works. On thinking about it, I believe it works because Foo::PARAM_VALUE is overridden by ChildFoo at compile time, so the const isn't restrictive at that point. I'm not completely sure, though.

Is it unsurprising that this works? Is this considered OK? Are there any drawbacks that could come from doing things in this way?

Cheers,
Gary


问:
Issue Building Flash Video Player (AS3) with Amazon Cloudfront to Stream MP4
So I have a working Flash player using Cloudfront, AS3, NetConnection & NetStream. Works with a FLV, but I need it to work with MP4s. It connects to the stream, and outputs the following:

```<code>NetConnection.Connect.Success
NetStream.Play.Reset
NetStream.Play.Start
NetStream.Buffer.Full
</code>```

My presumption is that it is working when looking at these messages, however it doesn't show the video or play any audio. Any suggestions?

答:
If you are streaming and the video does not show, this generally indicates a badly converted MP4.  Here is an article showing how to get the right encoding.
http://www.miracletutorials.com/converting-video-tutorials-to-streaming-mp4-for-s3-amazon-using-avs-video-converter/

It uses AVS video converter, but these settings are useful for other encoders too.  Just avoid using converters which give you no tweaking options and you will be fine.
Hope this is useful?

I forgot to mention: a badly converted MP4 might play on local computers and even with a download distribution but as soon as you try to stream them, they fail.

Body:
So I have a working Flash player using Cloudfront, AS3, NetConnection & NetStream. Works with a FLV, but I need it to work with MP4s. It connects to the stream, and outputs the following:

NetConnection.Connect.Success
NetStream.Play.Reset
NetStream.Play.Start
NetStream.Buffer.Full

My presumption is that it is working when looking at these messages, however it doesn't show the video or play any audio. Any suggestions?


问:
NGINX Not Loading Resources for Second Server
I'm new to NGINX (well hosting in general), so please excuse my ignorance. I have a Phoenix web app running on localhost:4000 and an ASP.NET web app running on localhost:5123. I'm trying to utilize NGINX to create a reverse proxy so that either web app can be accessed from the same domain. My NGINX config file contains the following:

```<code>server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://localhost:4000;
  }

  location /test {
    rewrite /test(.*) /$1 break;
    proxy_pass http://localhost:5123;
  }
}
</code>```

I'm able to access server 1 on example.com/ and server 2 on example.com/test, however, server 2 is not able to load its own css, javascript and image files. Is there a way to ensure server 1 and server 2 utilize their own resources via the NGINX config setup?

答:
You are on the right way. There are some lines missing on your second service:

Replace...

```<code>location /test {
    rewrite /test(.*) /$1 break;
    proxy_pass http://localhost:5123;
}
</code>```

with...

```<code>location /test {
    rewrite                /test/(.*) /$1 break;
    rewrite                ^/test$ /test/ permanent;
    proxy_pass             http://localhost:5123/;
    proxy_redirect         / /test/;
    proxy_set_header       Host $host;
    proxy_buffering off;
}
</code>```

I don't know if this is the best way to achieve this. Long time ago I used this configuration to implement an etherpad-service on my server. That time I had not the option to use a subdomain. Anyway - using a subdomain for your second service would be better.

Body:
I'm new to NGINX (well hosting in general), so please excuse my ignorance. I have a Phoenix web app running on localhost:4000 and an ASP.NET web app running on localhost:5123. I'm trying to utilize NGINX to create a reverse proxy so that either web app can be accessed from the same domain. My NGINX config file contains the following:

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://localhost:4000;
  }

  location /test {
    rewrite /test(.*) /$1 break;
    proxy_pass http://localhost:5123;
  }
}

I'm able to access server 1 on example.com/ and server 2 on example.com/test, however, server 2 is not able to load its own css, javascript and image files. Is there a way to ensure server 1 and server 2 utilize their own resources via the NGINX config setup?

Body:
You are on the right way. There are some lines missing on your second service:

Replace...

location /test {
    rewrite /test(.*) /$1 break;
    proxy_pass http://localhost:5123;
}

with...

location /test {
    rewrite                /test/(.*) /$1 break;
    rewrite                ^/test$ /test/ permanent;
    proxy_pass             http://localhost:5123/;
    proxy_redirect         / /test/;
    proxy_set_header       Host $host;
    proxy_buffering off;
}

I don't know if this is the best way to achieve this. Long time ago I used this configuration to implement an etherpad-service on my server. That time I had not the option to use a subdomain. Anyway - using a subdomain for your second service would be better.


问:
Ignore case affect character set
I have created a binary search tree and I want to make it as efficient as possible. When adding nodes I have used equalsIgnoreCase() when comparing it to a String (To prevent duplicates).

When adding two nodes such as: "BOB" and "bob".

For example:

converting "BOB" in to ASCII = 066 079 066

Converting "bob" in to ASCII= 098 111 098

You can see "BOB" and "bob" both have different values due to the uppercase letters.

Would equalsIgnoreCase() accept this as one entry regardless of the capitalisation?

Does this help efficiency?

答:
This would very likely break your binary tree. There are many values (common ones, even) that come between "bob" and "BOB" in lexicographic order. For instance: anything that starts with a lower-case "a" or an upper-case letter "C" or above. If any one of them were in your tree, then "BOB" would go in one direction at that node ("BOB" < "Dog") while "bob" would go in another ("bob" > "Dog"). That means that you wouldn't even have a chance to compare "bob" and "BOB."

You could get it to work by either:

using compareToIgnoreCase(String) or

normalizing all inputs (by using toLowerCase() or toUpperCase())

Title: Ignore case affect character set


问:
Asp.Net Core SAML Response Signature Validation
I'm working on a web application that needs to implement a SAML SSO using a third party idP (SP-initiated). I've reached the point where I am receiving the SAMLResponse from the idP which looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" IssueInstant="2017-12-04T13:47:30Z" ID="mjmobamignjdlgkpmkiijfbknamlbkadhkjcamhp" Version="2.0">
  <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://idp.com</saml:Issuer>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
  </samlp:Status>
  <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="gkifgihgclegelojncjfgegcddfncgdaefcjgbod" IssueInstant="2017-12-04T13:47:30Z" Version="2.0">
    <saml:Issuer>https://idp.com</saml:Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
        <ds:Reference URI="#gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
          <ds:Transforms>
            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
          </ds:Transforms>
          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
          <ds:DigestValue>nyU3iydIomlY9+D+YO7E6zNyq1A=</ds:DigestValue>
        </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>1AVSFcmgaPMFZvPHYyZDz1oFWzgiMCHI6yMfe6yCSK1pw6bkbZd/yZys8DuySi3Q75bnu3FmbrJQ
L9eEfoXK7kJEut79f9xrBwScNYQ21AZdYh5Rdzm7jRsbugYuQpfUUWasR6U37+bStVPpsCYEo4+C
Y1arLC/9ujj7aGxF7H+EMk7X0L4059+2v711X7a/3biowx2CyNOgjNRcrri3cyX/0soryyCA6/zH
fO2wcQi4udMXcZwXtZpAsluah7DjGp9MSTS5NInKm3Is4VIS9fN3KmKKTJYYZI27N0lFAxgHGVXc
GPWsh4hAd1CqQvuM0P5YlBfgPBD6Mu6tmZ9VLg==</ds:SignatureValue>
      <ds:KeyInfo>
        <ds:X509IssuerSerial>
          <ds:X509IssuerName>CN=Symantec Class 3 Secure Server CA - G4,OU=Symantec Trust Network,O=Symantec Corporation,C=US</ds:X509IssuerName>
          <ds:X509SerialNumber>142421751065451577073995987482935596892</ds:X509SerialNumber>
        </ds:X509IssuerSerial>
        <ds:X509Data>
          <ds:X509Certificate>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
TyU0Bbc2VGLlcP8=</ds:X509Certificate>
        </ds:X509Data>
      </ds:KeyInfo>
    </ds:Signature>
    <saml:Subject>
      <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified">C229699</saml:NameID>
      <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" NotOnOrAfter="2017-12-04T13:57:30Z" Recipient="http://my-app.net/saml"/>
      </saml:SubjectConfirmation>
    </saml:Subject>
    <saml:Conditions NotBefore="2017-12-04T13:42:30Z" NotOnOrAfter="2017-12-04T13:57:30Z">
      <saml:AudienceRestriction>
        <saml:Audience>http://my-app.net</saml:Audience>
      </saml:AudienceRestriction>
    </saml:Conditions>
    <saml:AuthnStatement AuthnInstant="2017-12-04T13:47:30Z" SessionIndex="gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
      <saml:AuthnContext>
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
      </saml:AuthnContext>
    </saml:AuthnStatement>
    <saml:AttributeStatement>
      <saml:Attribute Name="UserID" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
        <saml:AttributeValue>D100000</saml:AttributeValue>
      </saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</samlp:Response>
</code>```

It's a requirement that it's a manual implementation targeting netcoreapp2.0 so I have been trying to come up with the proper solution for validating the Signature value that's being provided. This doc, How to: Verify the Digital Signatures of XML Documents, was helpful in explaining some of the process but my implementation of SSO requires additional validations.

To pull the xml form from the SAML Response I have the following chunk:

```<code>var samlResponse = Request.Form["SAMLResponse"];
var toBytes = Convert.FromBase64String(samlResponse);
string decodedString =
Encoding.UTF8.GetString(toBytes);
</code>```

Just for a quick reference without opening the above link this is what the code looks like (using my sample values/variables where applicable):

```<code>CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

// Create a new RSA signing key and save it in the container.
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

// Create a new XML document.
XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(decodedString);

// Verify the signature of the signed XML.
Console.WriteLine("Verifying signature...");
bool result = VerifyXml(xmlDoc, rsaKey);

// Display the results of the signature verification to
// the console.
if (result)
{
    Console.WriteLine("The XML signature is valid.");
}
else
{
    Console.WriteLine("The XML signature is not valid.");
}

public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
    // Check arguments.
    if (Doc == null)
        throw new ArgumentException("Doc");
    if (Key == null)
        throw new ArgumentException("Key");

    // Create a new SignedXml object and pass it
    // the XML document class.
    SignedXml signedXml = new SignedXml(Doc);

    // Find the "Signature" node and create a new
    // XmlNodeList object.
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

    // Throw an exception if no signature was found.
    if (nodeList.Count <= 0)
    {
        throw new CryptographicException("Verification failed: No Signature was found in the document.");
    }

    // This example only supports one signature for
    // the entire XML document.  Throw an exception
    // if more than one signature was found.
    if (nodeList.Count >= 2)
    {
        throw new CryptographicException("Verification failed: More that one signature was found for the document.");
    }

    // Load the first <signature> node.
    signedXml.LoadXml((XmlElement)nodeList[0]);

    // Check the signature and return the result.
    return signedXml.CheckSignature(Key);
}
</code>```

UPDATE: Working solution for my manual implementation of SAML SSO in Asp.Net Core 2.0: First I have the below method named "VerifyXml" to verify the signature of the Xml document that is retrieved from the SAML Response form data. I then verify the X509 Certificate in my AccountController code as @Evk (thanks again for the help) points out that simply verifying the signature is not enough, in this case, to prevent arbitrary SAML Responses from being sent and accepted. On top of verifying those two values, in my case, I also need to validate the "InResponseTo" parameter matches the value generated by my web app (the SP) within a reasonable period of time. Generally, a login shouldn't take a long time so you could, for instance, create a task to forget AuthnRequest IDs that were generated and issued by your web app after a certain amount of time that's passed; say a minute or a time period that's applicable for you (Didn't include this code in the answer).

```<code>public static bool VerifyXml(XmlDocument Doc)
{
    // Check document isn't null.
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature();
 }
/* ******* CONTROLLER CODE ******* */
SignedXml signedXml = new SignedXml(xdoc);
var nsManager = new XmlNamespaceManager(xdoc.NameTable);
nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
var certElement = xdoc.SelectSingleNode("//ds:X509Certificate", nsManager);
/* Convert the received X509 Certificate into a new X509Certificate2 object. */
var certReceived = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
/* Load the pre-shared X509 Certificate from the idP metadata file. I have it stored in a secure database (You DO NOT want this stored in an easily accessible place, especially for production, in the project as it contains sensitive information). */
var loadSafeCert = _context.StoredMetadata.Where(metadata => idPMetadata.Certificate == "Certificate").FirstOrDefault();
/* Create a new X509Certificate2 using the value of the pre-defined certificate. */
var safeCertificate = new X509Certificate2(Convert.FromBase64String(loadSafeCert.ConfigurationValue));
/* Compare the received X509 Certificate value vs the pre-defined X509 Certificate value to ensure the validity. */
if (certReceived.GetPublicKeyString() == safeCertificate.GetPublicKeyString())
{ /* Store/get attributes, authenticate user, etc here */ }
</code>```

答:
Try to verify signature like this (your does not verify for me, but that might be caused by changes made while posting it here):

```<code>public static bool VerifyXml(XmlDocument Doc) {
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    // find signature node
    var certElement = Doc.SelectSingleNode("//ds:X509Certificate", nsManager);
    // find certificate node
    var cert = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature(cert);
}
</code>```

If that doesn't work, also try the same but call

```<code>return signedXml.CheckSignature();
</code>```

instead of

```<code>return signedXml.CheckSignature(cert);
</code>```

Note that just verifying this signature is not enough to ensure that response has not been tampered with. You verify signature using key provided in response itself (X509Data), which means attacker could have intercepted response, extracted information and resigned it with his own key, so signature will be valid, but key it was signed with will be not. So after extracting certificate (or you can use signedXml.CheckSignatureReturningKey method to get public key related to signature) you need to verify that it's valid and that it's certificate you are expecting (for example by comparing its hash with hash of certificate you expect).

Body:
I'm working on a web application that needs to implement a SAML SSO using a third party idP (SP-initiated). I've reached the point where I am receiving the SAMLResponse from the idP which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" IssueInstant="2017-12-04T13:47:30Z" ID="mjmobamignjdlgkpmkiijfbknamlbkadhkjcamhp" Version="2.0">
  <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://idp.com</saml:Issuer>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
  </samlp:Status>
  <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="gkifgihgclegelojncjfgegcddfncgdaefcjgbod" IssueInstant="2017-12-04T13:47:30Z" Version="2.0">
    <saml:Issuer>https://idp.com</saml:Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
        <ds:Reference URI="#gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
          <ds:Transforms>
            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
          </ds:Transforms>
          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
          <ds:DigestValue>nyU3iydIomlY9+D+YO7E6zNyq1A=</ds:DigestValue>
        </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>1AVSFcmgaPMFZvPHYyZDz1oFWzgiMCHI6yMfe6yCSK1pw6bkbZd/yZys8DuySi3Q75bnu3FmbrJQ
L9eEfoXK7kJEut79f9xrBwScNYQ21AZdYh5Rdzm7jRsbugYuQpfUUWasR6U37+bStVPpsCYEo4+C
Y1arLC/9ujj7aGxF7H+EMk7X0L4059+2v711X7a/3biowx2CyNOgjNRcrri3cyX/0soryyCA6/zH
fO2wcQi4udMXcZwXtZpAsluah7DjGp9MSTS5NInKm3Is4VIS9fN3KmKKTJYYZI27N0lFAxgHGVXc
GPWsh4hAd1CqQvuM0P5YlBfgPBD6Mu6tmZ9VLg==</ds:SignatureValue>
      <ds:KeyInfo>
        <ds:X509IssuerSerial>
          <ds:X509IssuerName>CN=Symantec Class 3 Secure Server CA - G4,OU=Symantec Trust Network,O=Symantec Corporation,C=US</ds:X509IssuerName>
          <ds:X509SerialNumber>142421751065451577073995987482935596892</ds:X509SerialNumber>
        </ds:X509IssuerSerial>
        <ds:X509Data>
          <ds:X509Certificate>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
TyU0Bbc2VGLlcP8=</ds:X509Certificate>
        </ds:X509Data>
      </ds:KeyInfo>
    </ds:Signature>
    <saml:Subject>
      <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified">C229699</saml:NameID>
      <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" NotOnOrAfter="2017-12-04T13:57:30Z" Recipient="http://my-app.net/saml"/>
      </saml:SubjectConfirmation>
    </saml:Subject>
    <saml:Conditions NotBefore="2017-12-04T13:42:30Z" NotOnOrAfter="2017-12-04T13:57:30Z">
      <saml:AudienceRestriction>
        <saml:Audience>http://my-app.net</saml:Audience>
      </saml:AudienceRestriction>
    </saml:Conditions>
    <saml:AuthnStatement AuthnInstant="2017-12-04T13:47:30Z" SessionIndex="gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
      <saml:AuthnContext>
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
      </saml:AuthnContext>
    </saml:AuthnStatement>
    <saml:AttributeStatement>
      <saml:Attribute Name="UserID" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
        <saml:AttributeValue>D100000</saml:AttributeValue>
      </saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</samlp:Response>

It's a requirement that it's a manual implementation targeting netcoreapp2.0 so I have been trying to come up with the proper solution for validating the Signature value that's being provided. This doc, How to: Verify the Digital Signatures of XML Documents, was helpful in explaining some of the process but my implementation of SSO requires additional validations.

To pull the xml form from the SAML Response I have the following chunk:

var samlResponse = Request.Form["SAMLResponse"];
var toBytes = Convert.FromBase64String(samlResponse);
string decodedString =
Encoding.UTF8.GetString(toBytes);

Just for a quick reference without opening the above link this is what the code looks like (using my sample values/variables where applicable):

CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

// Create a new RSA signing key and save it in the container.
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

// Create a new XML document.
XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(decodedString);

// Verify the signature of the signed XML.
Console.WriteLine("Verifying signature...");
bool result = VerifyXml(xmlDoc, rsaKey);

// Display the results of the signature verification to
// the console.
if (result)
{
    Console.WriteLine("The XML signature is valid.");
}
else
{
    Console.WriteLine("The XML signature is not valid.");
}

public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
    // Check arguments.
    if (Doc == null)
        throw new ArgumentException("Doc");
    if (Key == null)
        throw new ArgumentException("Key");

    // Create a new SignedXml object and pass it
    // the XML document class.
    SignedXml signedXml = new SignedXml(Doc);

    // Find the "Signature" node and create a new
    // XmlNodeList object.
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

    // Throw an exception if no signature was found.
    if (nodeList.Count <= 0)
    {
        throw new CryptographicException("Verification failed: No Signature was found in the document.");
    }

    // This example only supports one signature for
    // the entire XML document.  Throw an exception
    // if more than one signature was found.
    if (nodeList.Count >= 2)
    {
        throw new CryptographicException("Verification failed: More that one signature was found for the document.");
    }

    // Load the first <signature> node.
    signedXml.LoadXml((XmlElement)nodeList[0]);

    // Check the signature and return the result.
    return signedXml.CheckSignature(Key);
}

UPDATE: Working solution for my manual implementation of SAML SSO in Asp.Net Core 2.0: First I have the below method named "VerifyXml" to verify the signature of the Xml document that is retrieved from the SAML Response form data. I then verify the X509 Certificate in my AccountController code as @Evk (thanks again for the help) points out that simply verifying the signature is not enough, in this case, to prevent arbitrary SAML Responses from being sent and accepted. On top of verifying those two values, in my case, I also need to validate the "InResponseTo" parameter matches the value generated by my web app (the SP) within a reasonable period of time. Generally, a login shouldn't take a long time so you could, for instance, create a task to forget AuthnRequest IDs that were generated and issued by your web app after a certain amount of time that's passed; say a minute or a time period that's applicable for you (Didn't include this code in the answer).

public static bool VerifyXml(XmlDocument Doc)
{
    // Check document isn't null.
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature();
 }
/* ******* CONTROLLER CODE ******* */
SignedXml signedXml = new SignedXml(xdoc);
var nsManager = new XmlNamespaceManager(xdoc.NameTable);
nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
var certElement = xdoc.SelectSingleNode("//ds:X509Certificate", nsManager);
/* Convert the received X509 Certificate into a new X509Certificate2 object. */
var certReceived = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
/* Load the pre-shared X509 Certificate from the idP metadata file. I have it stored in a secure database (You DO NOT want this stored in an easily accessible place, especially for production, in the project as it contains sensitive information). */
var loadSafeCert = _context.StoredMetadata.Where(metadata => idPMetadata.Certificate == "Certificate").FirstOrDefault();
/* Create a new X509Certificate2 using the value of the pre-defined certificate. */
var safeCertificate = new X509Certificate2(Convert.FromBase64String(loadSafeCert.ConfigurationValue));
/* Compare the received X509 Certificate value vs the pre-defined X509 Certificate value to ensure the validity. */
if (certReceived.GetPublicKeyString() == safeCertificate.GetPublicKeyString())
{ /* Store/get attributes, authenticate user, etc here */ }

Body:
Try to verify signature like this (your does not verify for me, but that might be caused by changes made while posting it here):

public static bool VerifyXml(XmlDocument Doc) {
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    // find signature node
    var certElement = Doc.SelectSingleNode("//ds:X509Certificate", nsManager);
    // find certificate node
    var cert = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature(cert);
}

If that doesn't work, also try the same but call

return signedXml.CheckSignature();

instead of

return signedXml.CheckSignature(cert);

Note that just verifying this signature is not enough to ensure that response has not been tampered with. You verify signature using key provided in response itself (X509Data), which means attacker could have intercepted response, extracted information and resigned it with his own key, so signature will be valid, but key it was signed with will be not. So after extracting certificate (or you can use signedXml.CheckSignatureReturningKey method to get public key related to signature) you need to verify that it's valid and that it's certificate you are expecting (for example by comparing its hash with hash of certificate you expect).