问:
How to structure REGEX in C#
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

```<code>var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);
</code>```

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

答: You should make a replacement of the pattern variable to escape the regex special characters. One of them is the . character. Something similar to pattern.Replace(".", @"\.") but doing all the especial characters.

Title: How to structure REGEX in C#

Body:
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.


来源: stackexchange

问:
Using a created extension method
Here's the method I created:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
</code>```

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

```<code>@Html.MyMenu //doesn't appears to be in the available method selection.
</code>```

What's the reason why I can't call this method like that? Thanks for the help.

答: Wihtout seeing your view code it is hard to say exactly but you are probably missing a reference to MvcApplication1.HelperMethods in the view code. </p>

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Title: Using a created extension method

Body:
Here's the method I created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

@Html.MyMenu //doesn't appears to be in the available method selection.

What's the reason why I can't call this method like that? Thanks for the help.


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答: Add a media query, so that after a certain width of screen the elements will get a margin-bottom that is a percentage instead of px. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour


问:
Google Sheets alternating colors via API
Using the sheets API with Python I'm attempting to format a sheet using alternating colors. In the UI this is found at Format > Alternating colors...

From what I've been able to find this is done via the API using banding. Unfortunately, I haven't been able to find a working example of how this is done. Below is the values dictionary I've constructed, color values aren't important at the moment, I'd just like it to colorize the sheet.

```<code>requests = {
  'bandedRange': {
    'bandedRangeId': 1,
    'range': {
      'sheetId': 0,
      'startRowIndex': 0,
      'endRowIndex': len(values),
      'startColumnIndex': 0,
      'endColumnIndex': 4,
    },
    'rowProperties': {
      'headerColor': {
        'red': 1,
        'green': 0,
        'blue': 1,
        'alpha': 1,
      },
      'firstBandColor': {
        'red': 1,
        'green': 0,
        'blue': 0,
        'alpha': 0,
      },
      'secondBandColor': {
        'red': 0,
        'green': 1,
        'blue': 0,
        'alpha': 0,
      }
    },
  },
  'fields': '*',
}
body = {'requests': requests}
response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute()
</code>```

This fails with the following error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/$spreadsheet_id:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "banded_range" at 'requests': Cannot find field.">
</code>```

I'm fairly certain my issue is the fields value, but I can't find a valid example of what to use here. I get the same error if I omit the fields key entirely.

答:
Per the reference docs for batchUpdate, requests takes an array of Request objects.  Each Request must have exactly one field set, the available fields for banding being:

```<code>  "updateBanding": {
    object(UpdateBandingRequest)
  },
  "addBanding": {
    object(AddBandingRequest)
  },
  "deleteBanding": {
    object(DeleteBandingRequest)
  },
</code>```

There is no field bandedRange, which is what you're trying to set.  That's what the error message (Unknown name "banded_range" at 'requests': Cannot find field.) is saying... though I have no idea why it translated bandedRange to snake_case.

Depending on if you want to add or update the banded range, you'd set either updateBanding with an UpdateBandingRequest object, or addBanding with an AddBandingRequest object.

By adding addBanding to your JSON format. As explained above you will end up creating the below JSON. Also, the key fields is optional.

```<code>  {'addBanding': {
      'bandedRange': {
        'bandedRangeId': 1,
        'range': {
           'sheetId': 0,
            'startRowIndex': 0,
            'endRowIndex': len(values),
            'startColumnIndex': 0,
            'endColumnIndex': 4,
        },
        'rowProperties': {
          'headerColor': {
            'red': 1,
            'green': 0,
            'blue': 1,
            'alpha': 1,
          },
          'firstBandColor': {
            'red': 1,
            'green': 0,
            'blue': 0,
            'alpha': 0,
          },
          'secondBandColor': {
            'red': 0,
            'green': 1,
            'blue': 0,
            'alpha': 0,
          }
        },
      },
    },
   },
</code>```

Body:
Using the sheets API with Python I'm attempting to format a sheet using alternating colors. In the UI this is found at Format > Alternating colors...

From what I've been able to find this is done via the API using banding. Unfortunately, I haven't been able to find a working example of how this is done. Below is the values dictionary I've constructed, color values aren't important at the moment, I'd just like it to colorize the sheet.

requests = {
  'bandedRange': {
    'bandedRangeId': 1,
    'range': {
      'sheetId': 0,
      'startRowIndex': 0,
      'endRowIndex': len(values),
      'startColumnIndex': 0,
      'endColumnIndex': 4,
    },
    'rowProperties': {
      'headerColor': {
        'red': 1,
        'green': 0,
        'blue': 1,
        'alpha': 1,
      },
      'firstBandColor': {
        'red': 1,
        'green': 0,
        'blue': 0,
        'alpha': 0,
      },
      'secondBandColor': {
        'red': 0,
        'green': 1,
        'blue': 0,
        'alpha': 0,
      }
    },
  },
  'fields': '*',
}
body = {'requests': requests}
response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute()

This fails with the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/$spreadsheet_id:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "banded_range" at 'requests': Cannot find field.">

I'm fairly certain my issue is the fields value, but I can't find a valid example of what to use here. I get the same error if I omit the fields key entirely.

Body:
Per the reference docs for batchUpdate, requests takes an array of Request objects.  Each Request must have exactly one field set, the available fields for banding being:

  "updateBanding": {
    object(UpdateBandingRequest)
  },
  "addBanding": {
    object(AddBandingRequest)
  },
  "deleteBanding": {
    object(DeleteBandingRequest)
  },

There is no field bandedRange, which is what you're trying to set.  That's what the error message (Unknown name "banded_range" at 'requests': Cannot find field.) is saying... though I have no idea why it translated bandedRange to snake_case.

Depending on if you want to add or update the banded range, you'd set either updateBanding with an UpdateBandingRequest object, or addBanding with an AddBandingRequest object.

By adding addBanding to your JSON format. As explained above you will end up creating the below JSON. Also, the key fields is optional.

  {'addBanding': {
      'bandedRange': {
        'bandedRangeId': 1,
        'range': {
           'sheetId': 0,
            'startRowIndex': 0,
            'endRowIndex': len(values),
            'startColumnIndex': 0,
            'endColumnIndex': 4,
        },
        'rowProperties': {
          'headerColor': {
            'red': 1,
            'green': 0,
            'blue': 1,
            'alpha': 1,
          },
          'firstBandColor': {
            'red': 1,
            'green': 0,
            'blue': 0,
            'alpha': 0,
          },
          'secondBandColor': {
            'red': 0,
            'green': 1,
            'blue': 0,
            'alpha': 0,
          }
        },
      },
    },
   },


问:
Golang: How to construct a struct for Elasticsearch pipeline attachment
I'm constructing a struct to send a put message to Elasticsearch for pipeline attachment.

This is the json that I'm supposed to send it to ES:

```<code>PUT _ingest/pipeline/attachment
{
    "description": "Process documents",
    "processors": [
        {
            "attachment": {
                "field": "thedata",
                "indexed_chars": -1
            }
        },
        {
            "set": {
                "field": "attachment.title",
                "value": "{{ title }}"
            }
        },
        {
            "set": {
                "field": "attachment.author",
                "value": "{{ author }}"
            }
        },
        {
            "set": {
                "field": "attachment.url",
                "value": "{{ url }}"
            }
        },
        {
            "set": {
                "field": "attachment.cover",
                "value": "{{ cover }}"
            }
        },
        {
            "set": {
                "field": "attachment.page",
                "value": "{{ page }}"
            }
        }
    ]
}
</code>```

Do I really need to make a struct and marshal it in order to put the message? (I'm coming from Python). Setting up pipeline is a single time process.

I'm constructing structs like this in Go:

```<code>type AS struct {
    Description string

}

type ASP struct {
    Processors
}

type ASPA struct {
    Attachment []ASPAF `json:"attachment"`
}

type ASPAF struct {
    Field string `json:"field"`
    IndexedChars uint64 `json:"indexed_chars"`
}

type ASPS struct {
    Set []ASPSF `json:"set"`
}

type ASPSF struct {
    Field string `json:"field"`
    Value string `json:"value"`
}
</code>```

If you can see the code, I'm stuck at ASP struct and AS struct for processors and rounding up as attachment struct with description.

Could someone guide me? I'm not even sure if I'm right with the above structs.

Thanks!

答:
I'm able to do this successfully,

I have constructed structs like this:

```<code>type AS struct {
    Description string `json:"description"`
    Processors []ASP `json:"processors"`
}

type ASP struct {
    Attachment ASPA `json:"attachment"`
}

type ASPA struct {
    Field string `json:"field"`
    IndexedChars int64 `json:"indexed_chars"`
}

attachment := &AS{
    Description: "Process documents",
    Processors: []ASP{
        ASP{
            Attachment: ASPA{
                Field: "thedata",
                IndexedChars: -1,
            },
        },
    },
}
</code>```

Then I sent a put request similar to this
https://github.com/DaddyOh/golang-samples/blob/master/httpClient.go

I got the result:

```<code>{"acknowledged":true}
</code>```

Body:
I'm constructing a struct to send a put message to Elasticsearch for pipeline attachment.

This is the json that I'm supposed to send it to ES:

PUT _ingest/pipeline/attachment
{
    "description": "Process documents",
    "processors": [
        {
            "attachment": {
                "field": "thedata",
                "indexed_chars": -1
            }
        },
        {
            "set": {
                "field": "attachment.title",
                "value": "{{ title }}"
            }
        },
        {
            "set": {
                "field": "attachment.author",
                "value": "{{ author }}"
            }
        },
        {
            "set": {
                "field": "attachment.url",
                "value": "{{ url }}"
            }
        },
        {
            "set": {
                "field": "attachment.cover",
                "value": "{{ cover }}"
            }
        },
        {
            "set": {
                "field": "attachment.page",
                "value": "{{ page }}"
            }
        }
    ]
}

Do I really need to make a struct and marshal it in order to put the message? (I'm coming from Python). Setting up pipeline is a single time process.

I'm constructing structs like this in Go:

type AS struct {
    Description string

}

type ASP struct {
    Processors
}

type ASPA struct {
    Attachment []ASPAF `json:"attachment"`
}

type ASPAF struct {
    Field string `json:"field"`
    IndexedChars uint64 `json:"indexed_chars"`
}

type ASPS struct {
    Set []ASPSF `json:"set"`
}

type ASPSF struct {
    Field string `json:"field"`
    Value string `json:"value"`
}

If you can see the code, I'm stuck at ASP struct and AS struct for processors and rounding up as attachment struct with description.

Could someone guide me? I'm not even sure if I'm right with the above structs.

Thanks!

Body:
I'm able to do this successfully,

I have constructed structs like this:

type AS struct {
    Description string `json:"description"`
    Processors []ASP `json:"processors"`
}

type ASP struct {
    Attachment ASPA `json:"attachment"`
}

type ASPA struct {
    Field string `json:"field"`
    IndexedChars int64 `json:"indexed_chars"`
}

attachment := &AS{
    Description: "Process documents",
    Processors: []ASP{
        ASP{
            Attachment: ASPA{
                Field: "thedata",
                IndexedChars: -1,
            },
        },
    },
}

Then I sent a put request similar to this
https://github.com/DaddyOh/golang-samples/blob/master/httpClient.go

I got the result:

{"acknowledged":true}


问:
How to have event only when parent is clicked but not when children (two levels down)
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}</code>```

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

```

Do you know how to fix this behavior?

答:
Try using the .stopPropagation() function on the elements you don't want triggering your parent :

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });

  $( "li.has-submenu li" ).click(function(e) {
        e.stopPropagation();
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}</code>```

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

```

Body:
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});

.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

Do you know how to fix this behavior?

Body:
Try using the .stopPropagation() function on the elements you don't want triggering your parent :

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });

  $( "li.has-submenu li" ).click(function(e) {
        e.stopPropagation();
   });
});

.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
    <li class="has-submenu">
      <a href="#">Overview </a>
      <ul id="submenu" class="nav hide">
        <li class="active">
          <a href="#">Overview </a>
        </li>
        <li>
          <a href="#">Account Settings </a>
        </li>
        <li>
          <a href="#">Tasks </a>
        </li>
        <li>
          <a href="#">
            Help </a>
        </li>
      </ul>
    </li>
    <li>
      <a href="#">Account Settings </a>
    </li>
    <li>
      <a href="#">Tasks </a>
    </li>
    <li>
      <a href="#">Help </a>
    </li>
  </ul>


问:
Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code

```<code>$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}
</code>```

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

```<code>$name       = mysql_real_escape_string($name);
</code>```

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

答:
This is a PHP syntax problem.
The parser thinks $name[ is the start of a array reference you have to add curly bracelets to tell the parser where the variable name starts and end:
"[url={$website}]{$name}[/url]"</p>

Title: Sending a slash through mysql

Body:
I'm not sure why this has stumped me. I have the following code

$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

$name       = mysql_real_escape_string($name);

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"


问:
A-frame not picking up a cubemap
I am trying to create a simple animation of falling dices. With below code, I am trying to apply a cubemap to a-box but not able get the desired results.</p>

```<code><!DOCTYPE html>
<html>
    <head>
        <script src="https://aframe.io/releases/0.2.0/aframe.js"></script>

    </head>

    <body>
        <a-scene>
            <a-assets>
               <a-cubemap id="sky">
                    <img src="dice/Dice-1.png">
                    <img src="dice/Dice-2.png">
                    <img src="dice/Dice-3.png">
                    <img src="dice/Dice-4.png">
                    <img src="dice/Dice-5.png">
                    <img src="dice/Dice-6.png">
               </a-cubemap>
            </a-assets>
            <a-entity geometry="primitive: box" material="envMap: #sky"></a-entity>
          </a-scene>
    </body>
</html>
</code>```

答:
As far as i know, environmental maps, using i.e. cubemaps, are used to provide a sphere environment, or work with reflecion/refraction, by providing a map of the surrounding environment.

In Your case, I would use a texture for , or create a custom box made of planes, and texture them accordingly like this:

```<code><a-entity id="dice">
     <a-plane position="-0.5 0 0" rotation="0 -90 0"></a-plane>
     <a-plane position="0.5 0 0" rotation="0 90 0"></a-plane>
     <a-plane position="0 0.5 0" rotation="-90 0 0"></a-plane>
     <a-plane position="0 -0.5 0" rotation="90 0 0"></a-plane>
     <a-plane position="0 0 0.5" rotation="0 0 -90"></a-plane>
     <a-plane position="0 0 -0.5" rotation="0 0 90"></a-plane>

   </a-entity>
</code>```

working fiddle: https://jsfiddle.net/x8dt1jjb/.

Cubemaps:
As I see from multiple sources, cubemaps had many issues:
Like here or here

I found some guy claiming that cubemaps work on all entities except the first one, check out his github,
cubemaps are working on his index.html

Please note, indeed cubemaps on his example are not working on the first entity, so my advice would be copying his cubemap declarations, and create  with your envMap applied, but with scale="0 0 0", or visible="false". When made so, the first entity get's 'bugged' (but invisible, so who cares), and Your entity should work fine.

 Works properly for me, inverted my sources though: http://gftruj.nazwa.pl/cubemap/

Note, that there is an order in which You need to declare faces of Your cubemap, as explained here. Looking at a dice cubemap, you need to get your order straight, for example:

dice-5, dice-2, dice-4, dice-3, dice-6, dice-1

btw I found a cubemap component, didn't tried it yet though.

Title: A-frame not picking up a cubemap

Body:
I am trying to create a simple animation of falling dices. With below code, I am trying to apply a cubemap to a-box but not able get the desired results.

<!DOCTYPE html>

Body:
As far as i know, environmental maps, using i.e. cubemaps, are used to provide a sphere environment, or work with reflecion/refraction, by providing a map of the surrounding environment.

In Your case, I would use a texture for <a-box>, or create a custom box made of planes, and texture them accordingly like this:

<a-entity id="dice">
     <a-plane position="-0.5 0 0" rotation="0 -90 0"></a-plane>
     <a-plane position="0.5 0 0" rotation="0 90 0"></a-plane>
     <a-plane position="0 0.5 0" rotation="-90 0 0"></a-plane>
     <a-plane position="0 -0.5 0" rotation="90 0 0"></a-plane>
     <a-plane position="0 0 0.5" rotation="0 0 -90"></a-plane>
     <a-plane position="0 0 -0.5" rotation="0 0 90"></a-plane>

   </a-entity>

working fiddle: https://jsfiddle.net/x8dt1jjb/.

Cubemaps:
As I see from multiple sources, cubemaps had many issues:
Like here or here

I found some guy claiming that cubemaps work on all entities except the first one, check out his github,
cubemaps are working on his index.html

Please note, indeed cubemaps on his example are not working on the first entity, so my advice would be copying his cubemap declarations, and create <a-entity> with your envMap applied, but with scale="0 0 0", or visible="false". When made so, the first entity get's 'bugged' (but invisible, so who cares), and Your entity should work fine.

 Works properly for me, inverted my sources though: http://gftruj.nazwa.pl/cubemap/

Note, that there is an order in which You need to declare faces of Your cubemap, as explained here. Looking at a dice cubemap, you need to get your order straight, for example:

dice-5, dice-2, dice-4, dice-3, dice-6, dice-1

btw I found a cubemap component, didn't tried it yet though.


问:
Adding noise to image for deep learning, yes or no?
I've been thinking that adding noise to an image can prevent overfitting and also "increase" the dataset by adding variations to it. I'm only trying to add some random 1s to images that has shape (256,256,3) which uses uint8 to represent its color. I don't think that can affect the visualization at all (I showed both images with matplotlib and they seems almost the same) and has only ~0.01 mean difference in the sum of their values.

But it doesn't look to have its advances. After training for a long time it's still not as good as the one doesn't use noises.

Has anyone tried to use noise for image classification tasks like this? Is it eventually better?

答:
There are a couple of works that deal with this problem. Because you make the training set harder the training error will be lower, however your generalization might be better. It has been shown that adding noise can have stability effects for training Generative Adversarial Networks (Adversarial Training).

For classification tasks it is not that cut and dry. Not many works have actually dealt with this topic. The closest one is to my best knowledge is this one from google (https://arxiv.org/pdf/1412.6572.pdf), where they show the limitation of using training without noise. They do report a regularization effect, but not actual better results than using other methods.


问:
doctrine error when do clear before persist
I'm getting the following error

```<code>[Symfony\Component\Debug\Exception\ContextErrorException]
</code>```

Warning: spl_object_hash() expects parameter 1 to be object, array given

after running a 'clear' before a 'persist'.

This is the code.

```<code>    $user = $userRepository->findOneById($userId);
    $dm->clear();
    $dm->persist($user);
    $dm->flush();
</code>```

I know that making a clear just after retrieving the object from the database could be strange. But my inherited code is what it does.

any idea about the problem?

Thank you

答:
Use ->clear() after ->flush()

Official documentation link

Body:
I'm getting the following error

[Symfony\Component\Debug\Exception\ContextErrorException]

Warning: spl_object_hash() expects parameter 1 to be object, array given

after running a 'clear' before a 'persist'.

This is the code.

    $user = $userRepository->findOneById($userId);
    $dm->clear();
    $dm->persist($user);
    $dm->flush();

I know that making a clear just after retrieving the object from the database could be strange. But my inherited code is what it does.

any idea about the problem?

Thank you


问:
Azure App Service (Web App) PCI Compliance
Having a hard time finding a definitive answer regarding Azure App Services (Web App) and PCI Compliance.  PCI Standards 3.1 require that TLS 1.0 be disabled as well as well as block cipher algorithms with block size of 64 bits such as DES and 3DES.  Apparently Azure Web Apps is compliant with PCI Standards 3.0 but, not with 3.1.  Is there any official position from Microsoft as to when they will meet the updated standards (3.1)? for the Web Apps service?  I have been advised that i could use an App Service Environment so as to have the ability to disable TLS 1.0 and outdated ciphers but that (of course) is a premium service and cost more money.  We have client sites that we are hosting in Azure which are failing their PCI Compliance scans due to the above issues.  Is my only solution to move my client sites to an App Service Environment? </p>

答:
Starting April 30, 2018, you'll be able to manage what TLS versions your app service will accept.

I can't find a source to link to, but I did receive an email that included the following:

By April 30, 2018:

Through the Azure portal and Azure Resource Manager templates, you’ll be able to select the minimum-required TLS version (1.1 or 1.2)
  for your app.

We’ll configure App Service apps to require only newer TLS versions (1.1 and 1.2)—two months before the required date.

After June 30, 2018:

All newly created App Service apps will be automatically configured to require TLS 1.2. You’ll still retain the option to configure
  earlier TLS versions for your apps, if necessary, for compatibility
  with older browser clients.

In regards to your question about removing DES and 3DES from the cipher suite, that was scheduled for March 2017 (https://appsvcssl.trafficmanager.net/) and my testing shows that it has been removed (at least from a new web app created in US East).


问:
Acces to variable from another a class that extends activity to a class that extends view
in my code i want to get acces to the value of a variable in another class.
To be more precise I want to get acces to the vallue of the variable points in my class GameArena and overwrite the variable points in my class GameActivity with the value.
Here are the classes:

```<code>public class GameArena extends View {
int points;
public GameArena(Context context) {
    super(context);
    [...]
    points = 0;
}

@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);

  [...]

   invalidate();
}

public void actualizePoints(){

}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    [...]
    points++;
}

}
</code>```

And here is the the GameActivity:

```<code>public class GameActivity extends Activity {

Boolean gameRunning = false;
int round = 0;
int points = 0;
float screenScale;
GameArena gameArena;
FrameLayout gameArenaFrameLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
    startGame();
}

public void startGame(){
    startRound();
}

public void startRound(){
    points = 0;
    startGameArena();
}

public void startGameArena(){
    gameArenaFrameLayout = (FrameLayout)findViewById(R.id.frameLayoutGameArena);
    Log.i("GameArenaFrameLayout", Integer.toString(gameArenaFrameLayout.getWidth()));
    gameArena = new GameArena(this);
    gameArenaFrameLayout.addView(gameArena);
}

public void actualizeScreen(){

}
</code>```

}

Can someone give me a hint how I could solve this problem ?
Thank you.

答:
Use a getter : </p>

```<code>public class GameArena extends View {
    private int points;
    public GameArena(Context context) {
        super(context);
        [...]
        points = 0;
    }

    public int getPoints() {
        return points;
    }
}
</code>```

<p>In Activity : </p>

```<code>gameArena.getPoints();
</code>```

Body:
in my code i want to get acces to the value of a variable in another class.
To be more precise I want to get acces to the vallue of the variable points in my class GameArena and overwrite the variable points in my class GameActivity with the value.
Here are the classes:

public class GameArena extends View {
int points;
public GameArena(Context context) {
    super(context);
    [...]
    points = 0;
}

@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);

  [...]

   invalidate();
}

public void actualizePoints(){

}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    [...]
    points++;
}

}

And here is the the GameActivity:

public class GameActivity extends Activity {

Boolean gameRunning = false;
int round = 0;
int points = 0;
float screenScale;
GameArena gameArena;
FrameLayout gameArenaFrameLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
    startGame();
}

public void startGame(){
    startRound();
}

public void startRound(){
    points = 0;
    startGameArena();
}

public void startGameArena(){
    gameArenaFrameLayout = (FrameLayout)findViewById(R.id.frameLayoutGameArena);
    Log.i("GameArenaFrameLayout", Integer.toString(gameArenaFrameLayout.getWidth()));
    gameArena = new GameArena(this);
    gameArenaFrameLayout.addView(gameArena);
}

public void actualizeScreen(){

}

}

Can someone give me a hint how I could solve this problem ?
Thank you.

Body:
Use a getter :

public class GameArena extends View {
    private int points;
    public GameArena(Context context) {
        super(context);
        [...]
        points = 0;
    }

    public int getPoints() {
        return points;
    }
}

In Activity :

gameArena.getPoints();


问:
C# - textbox don't need to wait until the end?
I have this code :

```<code>private void button2_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    logBox.Text += "My text";

    try
    {
        ping thing;
    }
    catch
    {
    }
}
</code>```

How can I show the logBox.Text += before doing the try ? Actually, need to wait the end of the thread to show the text in my logbox...

I don't want wait the app doing the try and show directly the logBox.Text when I click on the button.

Thanks for helping me.

答:
You can use Task.Factory to achieve that. Example from the docs:

```<code>using System;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task[] tasks = new Task[2];
      String[] files = null;
      String[] dirs = null;
      String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      tasks[0] = Task.Factory.StartNew( () => files = Directory.GetFiles(docsDirectory));
      tasks[1] = Task.Factory.StartNew( () => dirs = Directory.GetDirectories(docsDirectory));

      Task.Factory.ContinueWhenAll(tasks, completedTasks => {
                                             Console.WriteLine("{0} contains: ", docsDirectory);
                                             Console.WriteLine("   {0} subdirectories", dirs.Length);
                                             Console.WriteLine("   {0} files", files.Length);
                                          } );
   }
}
// The example displays output like the following:
//       C:\Users\<username>\Documents contains:
//          24 subdirectories
//          16 files
</code>```

Just put your task creation into the event handler you are using.

Body:
I have this code :

private void button2_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    logBox.Text += "My text";

    try
    {
        ping thing;
    }
    catch
    {
    }
}

How can I show the logBox.Text += before doing the try ? Actually, need to wait the end of the thread to show the text in my logbox...

I don't want wait the app doing the try and show directly the logBox.Text when I click on the button.

Thanks for helping me.

Body:
You can use Task.Factory to achieve that. Example from the docs:

using System;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task[] tasks = new Task[2];
      String[] files = null;
      String[] dirs = null;
      String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      tasks[0] = Task.Factory.StartNew( () => files = Directory.GetFiles(docsDirectory));
      tasks[1] = Task.Factory.StartNew( () => dirs = Directory.GetDirectories(docsDirectory));

      Task.Factory.ContinueWhenAll(tasks, completedTasks => {
                                             Console.WriteLine("{0} contains: ", docsDirectory);
                                             Console.WriteLine("   {0} subdirectories", dirs.Length);
                                             Console.WriteLine("   {0} files", files.Length);
                                          } );
   }
}
// The example displays output like the following:
//       C:\Users\<username>\Documents contains:
//          24 subdirectories
//          16 files

Just put your task creation into the event handler you are using.


问:
How to get CNTK Parallel Speedup on SequenceToSequence Example
I cloned the CNTK repository last week and built it using Nvidia-docker running on a p2.8xlarge instance on AWS. Everything appears to be working, except that I'm not getting a speedup from running multiple GPUs when enabling 1-bit SGD. I'm running the CMUDict Sequence2Sequence_distributed.py example. Here is my transcript when I run it on one GPU:

```<code>root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# python Sequence2Sequence_Distributed.py
Selected GPU[0] Tesla K80 as the process wide default device.
ping [requestnodes (before change)]: 1 nodes pinging each other
ping [requestnodes (after change)]: 1 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 1 out of 1 MPI nodes on a single host (1 requested); we (0) are in (participating)
ping [mpihelper]: 1 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
Finished Epoch[1 of 160]: [Training] loss = 4.234002 * 64, metric = 98.44% * 64 3.014s ( 21.2 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.231473 * 71, metric = 85.92% * 71 1.013s ( 70.1 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.227827 * 61, metric = 81.97% * 61 0.953s ( 64.0 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.227088 * 68, metric = 86.76% * 68 0.970s ( 70.1 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.222957 * 62, metric = 88.71% * 62 0.922s ( 67.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.221479 * 63, metric = 84.13% * 63 0.950s ( 66.3 samples/s);
</code>```

Here's the transcript when I run two GPUs:

```<code>root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# mpiexec --allow-run-as-root --npernode 2 python Sequence2Sequence_Distributed.py -q 1

Selected GPU[0] Tesla K80 as the process wide default device.
Selected CPU as the process wide default device.
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (0) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (1) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
</code>```

Here's an error message -- does this mean the GPUs are not being utilized when I run the job as two MPI processes? How would I fix this?

```<code>NcclComm: disabled, at least one rank using CPU device
NcclComm: disabled, at least one rank using CPU device
</code>```

You can see the number of samples/s is down:

```<code>Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.377s ( 13.6 samples/s);
Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.877s ( 12.4 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.196s ( 30.5 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.197s ( 30.5 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.667s ( 27.6 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.666s ( 27.6 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
</code>```

答:
I was a able to fix the initial issue by getting Nvidia-docker to take multiple GPUs by telling the nvidia-docker which GPUs to use; for example -- if you want to set 2 GPUs, then use:</p>

```<code>NV_GPU=0,1 nvidia-docker run ....
</code>```

Body:
I cloned the CNTK repository last week and built it using Nvidia-docker running on a p2.8xlarge instance on AWS. Everything appears to be working, except that I'm not getting a speedup from running multiple GPUs when enabling 1-bit SGD. I'm running the CMUDict Sequence2Sequence_distributed.py example. Here is my transcript when I run it on one GPU:

root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# python Sequence2Sequence_Distributed.py
Selected GPU[0] Tesla K80 as the process wide default device.
ping [requestnodes (before change)]: 1 nodes pinging each other
ping [requestnodes (after change)]: 1 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 1 out of 1 MPI nodes on a single host (1 requested); we (0) are in (participating)
ping [mpihelper]: 1 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
Finished Epoch[1 of 160]: [Training] loss = 4.234002 * 64, metric = 98.44% * 64 3.014s ( 21.2 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.231473 * 71, metric = 85.92% * 71 1.013s ( 70.1 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.227827 * 61, metric = 81.97% * 61 0.953s ( 64.0 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.227088 * 68, metric = 86.76% * 68 0.970s ( 70.1 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.222957 * 62, metric = 88.71% * 62 0.922s ( 67.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.221479 * 63, metric = 84.13% * 63 0.950s ( 66.3 samples/s);

Here's the transcript when I run two GPUs:

root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# mpiexec --allow-run-as-root --npernode 2 python Sequence2Sequence_Distributed.py -q 1

Selected GPU[0] Tesla K80 as the process wide default device.
Selected CPU as the process wide default device.
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (0) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (1) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

Here's an error message -- does this mean the GPUs are not being utilized when I run the job as two MPI processes? How would I fix this?

NcclComm: disabled, at least one rank using CPU device
NcclComm: disabled, at least one rank using CPU device

You can see the number of samples/s is down:

Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.377s ( 13.6 samples/s);
Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.877s ( 12.4 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.196s ( 30.5 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.197s ( 30.5 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.667s ( 27.6 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.666s ( 27.6 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);

Body:
I was a able to fix the initial issue by getting Nvidia-docker to take multiple GPUs by telling the nvidia-docker which GPUs to use; for example -- if you want to set 2 GPUs, then use:

NV_GPU=0,1 nvidia-docker run ....


问:
Installing XHProf on Ubuntu Server
I have tried the following tutorials, as well as others:

http://akyl.net/how-install-xhprof-profiler-ubuntu

http://erichogue.ca/2011/03/linux/profiling-a-php-application/

I am continually getting the following error message(s):

```<code>running: make
/bin/bash /tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/libtool --mode=compile cc  -I. -I/tmp/pear/install/xhprof/extension -DPHP_ATOM_INC -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/include -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/main -I/tmp/pear/install/xhprof/extension -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64  -DHAVE_CONFIG_H  -g -O2   -c /tmp/pear/install/xhprof/extension/xhprof.c -o xhprof.lo
libtool: compile:  cc -I. -I/tmp/pear/install/xhprof/extension -DPHP_ATOM_INC -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/include -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/main -I/tmp/pear/install/xhprof/extension -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -g -O2 -c /tmp/pear/install/xhprof/extension/xhprof.c  -fPIC -DPIC -o .libs/xhprof.o
In file included from /usr/include/php5/main/php.h:33:0,
                 from /tmp/pear/install/xhprof/extension/xhprof.c:27:
/usr/include/php5/main/php_config.h:2396:0: warning: "_GNU_SOURCE" redefined [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:24:0: note: this is the location of the previous definition
/tmp/pear/install/xhprof/extension/xhprof.c:236:1: warning: 'visibility' attribute ignored [-Wattributes]
/tmp/pear/install/xhprof/extension/xhprof.c:240:28: warning: 'visibility' attribute ignored [-Wattributes]
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_get_function_name':
/tmp/pear/install/xhprof/extension/xhprof.c:898:10: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:909:13: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:911:13: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:930:34: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c:963:9: warning: passing argument 1 of 'hp_get_base_filename' discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:856:14: note: expected 'char *' but argument is of type 'const char *'
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_execute_internal':
/tmp/pear/install/xhprof/extension/xhprof.c:1650:24: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c:1651:59: error: 'struct <anonymous>' has no member named 'return_reference'
/tmp/pear/install/xhprof/extension/xhprof.c:1652:25: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_compile_file':
/tmp/pear/install/xhprof/extension/xhprof.c:1683:3: warning: passing argument 1 of 'hp_get_base_filename' discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:856:14: note: expected 'char *' but argument is of type 'const char *'
make: *** [xhprof.lo] Error 1
ERROR: `make' failed
</code>```

Basically, 'make' is not able to run. How do I get past this?

答:
I got the same issue, got it fixed using these steps:

Download "xhprof" package:

cd /extension/

phpize

./configure --with-php-config=

make

make install

make test

Now add below lines in php.ini:

[xhprof]

extension=xhprof.so

xhprof.output_dir="directory_for_storing_xhprof_runs"

Now: apache restart

Title: Installing XHProf on Ubuntu Server

Body:
I have tried the following tutorials, as well as others:

http://akyl.net/how-install-xhprof-profiler-ubuntu

http://erichogue.ca/2011/03/linux/profiling-a-php-application/

I am continually getting the following error message(s):

running: make
/bin/bash /tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/libtool --mode=compile cc  -I. -I/tmp/pear/install/xhprof/extension -DPHP_ATOM_INC -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/include -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/main -I/tmp/pear/install/xhprof/extension -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64  -DHAVE_CONFIG_H  -g -O2   -c /tmp/pear/install/xhprof/extension/xhprof.c -o xhprof.lo
libtool: compile:  cc -I. -I/tmp/pear/install/xhprof/extension -DPHP_ATOM_INC -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/include -I/tmp/pear/install/pear-build-fieldnation1Iqjyy/xhprof-0.9.2/main -I/tmp/pear/install/xhprof/extension -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -g -O2 -c /tmp/pear/install/xhprof/extension/xhprof.c  -fPIC -DPIC -o .libs/xhprof.o
In file included from /usr/include/php5/main/php.h:33:0,
                 from /tmp/pear/install/xhprof/extension/xhprof.c:27:
/usr/include/php5/main/php_config.h:2396:0: warning: "_GNU_SOURCE" redefined [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:24:0: note: this is the location of the previous definition
/tmp/pear/install/xhprof/extension/xhprof.c:236:1: warning: 'visibility' attribute ignored [-Wattributes]
/tmp/pear/install/xhprof/extension/xhprof.c:240:28: warning: 'visibility' attribute ignored [-Wattributes]
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_get_function_name':
/tmp/pear/install/xhprof/extension/xhprof.c:898:10: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:909:13: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:911:13: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:930:34: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c:963:9: warning: passing argument 1 of 'hp_get_base_filename' discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:856:14: note: expected 'char *' but argument is of type 'const char *'
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_execute_internal':
/tmp/pear/install/xhprof/extension/xhprof.c:1650:24: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c:1651:59: error: 'struct <anonymous>' has no member named 'return_reference'
/tmp/pear/install/xhprof/extension/xhprof.c:1652:25: error: 'znode_op' has no member named 'u'
/tmp/pear/install/xhprof/extension/xhprof.c: In function 'hp_compile_file':
/tmp/pear/install/xhprof/extension/xhprof.c:1683:3: warning: passing argument 1 of 'hp_get_base_filename' discards 'const' qualifier from pointer target type [enabled by default]
/tmp/pear/install/xhprof/extension/xhprof.c:856:14: note: expected 'char *' but argument is of type 'const char *'
make: *** [xhprof.lo] Error 1
ERROR: `make' failed

Basically, 'make' is not able to run. How do I get past this?


问:
How can I dispose a view when navigating away with Prism?
I'm experimenting with Prism and have created a simple application consisting of a main window with a Prism region, along with two "child" views (and VMs). Each of these child views has a button, and clicking this simply navigates to the other view, e.g.:

```<code>_regionManager.RequestNavigate("MainWindowRegion", "HomeView");
</code>```

The child views and view models implement IDisposable, and have been given a "Transient" lifetime in my DI container. Additionally the views implement IRegionMemberLifetime (KeepAlive = false).

Despite all this, the views aren't getting disposed (until I close the application). What am I missing? How do I dispose of a view when I navigate away from it?

Or would it be simpler to register the child views as singletons and initialise them whenever I navigate to them?

答: If you are expecting your IDisposable methods to fire and that is what you are using to determine if your views are being "disposed" then you're doing it wrong. That's not how it works.  The GC will do its job when it is ready. If you are using IRegionMemberLifetime then you are doing what you need to in order to remove the view from the region and have it available for GC.  You'll want to do some research on IDisposable and how it works in WPF.</p>

Body:
I'm experimenting with Prism and have created a simple application consisting of a main window with a Prism region, along with two "child" views (and VMs). Each of these child views has a button, and clicking this simply navigates to the other view, e.g.:

_regionManager.RequestNavigate("MainWindowRegion", "HomeView");

The child views and view models implement IDisposable, and have been given a "Transient" lifetime in my DI container. Additionally the views implement IRegionMemberLifetime (KeepAlive = false).

Despite all this, the views aren't getting disposed (until I close the application). What am I missing? How do I dispose of a view when I navigate away from it?

Or would it be simpler to register the child views as singletons and initialise them whenever I navigate to them?


问:
Object required error when using textbox
```<code>Private Sub TextBox1_Change()
Slide2.TextBox2.Value = Slide2.TextBox1.Value * 0.0225
Slide2.TextBox3.Value = Slide2.TextBox1.Value * 0.1
End Sub
</code>```

Everytime i run the presentation i get an object required error on line 2. I am fairly new to VBA so have no idea how to deal with it

答:
There are any number of problems with your code as written.  This will work, assuming, as Tim asks, that there IS a shape named TextBox1 on Slide 2:

```<code>Private Sub TextBox1_Change()

With ActivePresentation.Slides(2).Shapes("TextBox1")
    .OLEFormat.Object.Text = CStr(CDbl(.OLEFormat.Object.Text) * 0.0225)
End With

End Sub
</code>```

A bit of explanation:

ActivePresentation.Slides(2).Shapes("TextBox1")

There might be more than one presentation open, so you have to tell VBA which one to look at, in this case the Active presentation, the one you're looking at right now.

.Slides(2)

This is the correct syntax to refer to the second slide in the presentation, and from there you need to specify which Shape on the slide you want to work with, so

.Shapes("TextBox1")

Since it's an ActiveX shape and not a normal PPT shape, you have to access its properties in a rather odd way:

.OLEFormat.Object.PropertyName

In this case, the property name in question is Text ... the text in the textbox.

Then we convert the text in the text box to a number (using CDbl) before doing arithmetic on it, and then convert the result back to a string to stuff into the textbox.

VBA will try to do these string to number, number to string conversions for you automatically, but it's generally better practice to be explicit about what you want rather than going with what VBA ASS-U-MEs you want.

Body:
Private Sub TextBox1_Change()
Slide2.TextBox2.Value = Slide2.TextBox1.Value * 0.0225
Slide2.TextBox3.Value = Slide2.TextBox1.Value * 0.1
End Sub

Everytime i run the presentation i get an object required error on line 2. I am fairly new to VBA so have no idea how to deal with it

Body:
There are any number of problems with your code as written.  This will work, assuming, as Tim asks, that there IS a shape named TextBox1 on Slide 2:

Private Sub TextBox1_Change()

With ActivePresentation.Slides(2).Shapes("TextBox1")
    .OLEFormat.Object.Text = CStr(CDbl(.OLEFormat.Object.Text) * 0.0225)
End With

End Sub

A bit of explanation:

ActivePresentation.Slides(2).Shapes("TextBox1")

There might be more than one presentation open, so you have to tell VBA which one to look at, in this case the Active presentation, the one you're looking at right now.

.Slides(2)

This is the correct syntax to refer to the second slide in the presentation, and from there you need to specify which Shape on the slide you want to work with, so

.Shapes("TextBox1")

Since it's an ActiveX shape and not a normal PPT shape, you have to access its properties in a rather odd way:

.OLEFormat.Object.PropertyName

In this case, the property name in question is Text ... the text in the textbox.

Then we convert the text in the text box to a number (using CDbl) before doing arithmetic on it, and then convert the result back to a string to stuff into the textbox.

VBA will try to do these string to number, number to string conversions for you automatically, but it's generally better practice to be explicit about what you want rather than going with what VBA ASS-U-MEs you want.


问:
ruby read lines from string variable using character count
I have been using to split the file content based on the character count, since one of my application which doesn't support for any number of characters. So I have to split the content based on the character count and update it multiple times based on the total character count.

```<code>c_max = 50000
f = File.new(filename)
u_count = (c_count / c_max.to_f).ceil
i = 1
while i <= u_count do
    u_characters = f.sysread(c_max)
    # do stuffs
    i+=1
end
</code>```

But its not working when I use strings instead of filename.

```<code>content=File.read(filename)
#doing some stuffs on the contents
irb(main):006:0> content.sysread(10)
NoMethodError: undefined method `sysread' for #<String:0x7f5f2eedd368>
        from (irb):6
        from :0
irb(main):007:0>
</code>```

答:
If you are trying to limit the number of characters IO#each_line can help you with this e.g.

```<code>c_max = 100
File.open(filename) do |file|
  file.each_line(c_max) do |characters|
    # characters is now a string that is 100 characters long
    # do something with characters
  end
end
</code>```

Or to handle a String you can make it a StringIO and #each_line will work too (Please note String#each_line will not work as it only accepts a separator (String) and not a character limit (Fixnum) this is why we need StringIO)

```<code>s = "THIS IS A STRING"
StringIO.open(s) do |strio|
  strio.each_line(2) do |characters|
    # characters is now a string that is 2 characters long
    # do something with characters
  end
end
</code>```

So let's handle both options Update: (Based on comment discussion with @CarySwoveland - Thanks for pushing me further)

```<code>def do_stuff(line)
  # common functionality goes here
  puts line
end

# return is a StringIO or File
# leaks file descriptor handle as you wish
def my_method(s,sep_or_char_limit=100)
  target = s.to_s # leverage a little duck typing
  target_class = File.file?(target) ? File : StringIO
  target_class.open(target) do |io|
    io.each_line(sep_or_char_limit, &method(:do_stuff))
  end
end
</code>```

Since this uses Enumerator functionality it will also help with memory consumption since the whole File need not be read into memory first or the whole String does not need to be split into a temporary Array.

There is additional hidden functionality here as well. You asked for limitation by characters but this will also allow for a separator if you prefer. e.g.

```<code># Using a Character Limit
my_method("THIS IS A STRING",2)
# TH
# IS
#  I
# S
# A
# ST
# RI
# NG

# Using a separator
my_method("THIS IS A STRING",' ')
# THIS
# IS
# A
# STRING
</code>```

Body:
I have been using to split the file content based on the character count, since one of my application which doesn't support for any number of characters. So I have to split the content based on the character count and update it multiple times based on the total character count.

c_max = 50000
f = File.new(filename)
u_count = (c_count / c_max.to_f).ceil
i = 1
while i <= u_count do
    u_characters = f.sysread(c_max)
    # do stuffs
    i+=1
end

But its not working when I use strings instead of filename.

content=File.read(filename)
#doing some stuffs on the contents
irb(main):006:0> content.sysread(10)
NoMethodError: undefined method `sysread' for #<String:0x7f5f2eedd368>
        from (irb):6
        from :0
irb(main):007:0>

Body:
If you are trying to limit the number of characters IO#each_line can help you with this e.g.

c_max = 100
File.open(filename) do |file|
  file.each_line(c_max) do |characters|
    # characters is now a string that is 100 characters long
    # do something with characters
  end
end

Or to handle a String you can make it a StringIO and #each_line will work too (Please note String#each_line will not work as it only accepts a separator (String) and not a character limit (Fixnum) this is why we need StringIO)

s = "THIS IS A STRING"
StringIO.open(s) do |strio|
  strio.each_line(2) do |characters|
    # characters is now a string that is 2 characters long
    # do something with characters
  end
end

So let's handle both options Update: (Based on comment discussion with @CarySwoveland - Thanks for pushing me further)

def do_stuff(line)
  # common functionality goes here
  puts line
end

# return is a StringIO or File
# leaks file descriptor handle as you wish
def my_method(s,sep_or_char_limit=100)
  target = s.to_s # leverage a little duck typing
  target_class = File.file?(target) ? File : StringIO
  target_class.open(target) do |io|
    io.each_line(sep_or_char_limit, &method(:do_stuff))
  end
end

Since this uses Enumerator functionality it will also help with memory consumption since the whole File need not be read into memory first or the whole String does not need to be split into a temporary Array.

There is additional hidden functionality here as well. You asked for limitation by characters but this will also allow for a separator if you prefer. e.g.

# Using a Character Limit
my_method("THIS IS A STRING",2)
# TH
# IS
#  I
# S
# A
# ST
# RI
# NG

# Using a separator
my_method("THIS IS A STRING",' ')
# THIS
# IS
# A
# STRING


问:
How to put a service in a component and that is displayed in the html? In angular 2
How to put a service in a component and that is displayed in the html by @Input?

Until the moment I carry this code but I have not received success

This is Service

import {
  Injectable
} from '@angular/core';
import Rx from 'Rx';

@Injectable()
export class TiempoService {

  tiempoTranscurrido: number;

  constructor() {}

  ngOnInit() {

  }
  tiempoTotal() {
    Rx.Observable.interval(1000).subscribe(segundos => {
      this.tiempoTranscurrido = segundos * 1000;
    })
  }
}```
</div>
</div>
</p>

<p>This is component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  TiempoService
} from "app/servicios/tiempo.service"

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  @Input() tiemposervice: TiempoService;
  constructor() {}

  ngOnInit() {

  }

}</code>```

this is html

        Tiempo transcurrido

{{tiempoTranscurrido | date:'mm:ss'}}

```

I would greatly appreciate your help

答:
It's best to avoid subscribing ("unwrapping") the observable into a scalar value in the service. Instead, have the service just provide the observable itself, suitably mapped, and consume it in the component. You can consume it directly in the template with the async pipe.

```<code>// service
tiempotransCurrido$() {
  return Rx.Observable.interval(1000).map(segundos => segundos * 1000);
}

// component
tiempotransCurrido$ = tiempoService.tiempotransCurrido$();

// template
<h5>{{tiempotransCurrido$ | async | date:'mm:ss'}}</h5>
</code>```

Body:
How to put a service in a component and that is displayed in the html by @Input?

Until the moment I carry this code but I have not received success

This is Service

import {
  Injectable
} from '@angular/core';
import Rx from 'Rx';

@Injectable()
export class TiempoService {

  tiempoTranscurrido: number;

  constructor() {}

  ngOnInit() {

  }
  tiempoTotal() {
    Rx.Observable.interval(1000).subscribe(segundos => {
      this.tiempoTranscurrido = segundos * 1000;
    })
  }
}

This is component

import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  TiempoService
} from "app/servicios/tiempo.service"

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  @Input() tiemposervice: TiempoService;
  constructor() {}

  ngOnInit() {

  }

}

this is html

        Tiempo transcurrido

{{tiempoTranscurrido | date:'mm:ss'}}

I would greatly appreciate your help

Body:
It's best to avoid subscribing ("unwrapping") the observable into a scalar value in the service. Instead, have the service just provide the observable itself, suitably mapped, and consume it in the component. You can consume it directly in the template with the async pipe.

// service
tiempotransCurrido$() {
  return Rx.Observable.interval(1000).map(segundos => segundos * 1000);
}

// component
tiempotransCurrido$ = tiempoService.tiempotransCurrido$();

// template
<h5>{{tiempotransCurrido$ | async | date:'mm:ss'}}</h5>


答:
Modify your code to following:

```<code>private void button2_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    logBox.Text += "My text";
    logBox.Refresh();//This will display the modifications

    try
    {
        ping thing;
    }
    catch
    {
    }
}
</code>```

CAUTION:

The way this answer solves the problem is not recommended. This doesn't really make your code much responsive and the output is also not guaranteed in some edge cases. In general, it is not recommended to use the way suggested here.

Using Background Thread or Task is better way to go. The Task-way is already explained in other answer. Also, the comments under question are explaining the same.

I am copying some of the comments (as comments are second class members):

If you want the UI thread to update before "ping thing" completes, you can't do "ping thing" on the UI thread. Do it in a Task. – 15ee8f99-57ff-4f92-890c-b56153

..........and that long-running tasks like this should generally be done on a background thread. – Cody Gray

Hanging the UI is an anti-pattern too. – 15ee8f99-57ff-4f92-890c-b56153

Any piece of code that you know is going to take at least a few seconds, should be done asynchronously so that you don't block the UI thread (you'll know when this happens because your program will freeze). Give this a read: msdn.microsoft.com/library/hh191443(vs.110).aspx – ThePerplexedOne

Title: C# - textbox don't need to wait until the end?

Body:
Modify your code to following:

private void button2_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    logBox.Text += "My text";
    logBox.Refresh();//This will display the modifications

    try
    {
        ping thing;
    }
    catch
    {
    }
}

CAUTION:

The way this answer solves the problem is not recommended. This doesn't really make your code much responsive and the output is also not guaranteed in some edge cases. In general, it is not recommended to use the way suggested here.

Using Background Thread or Task is better way to go. The Task-way is already explained in other answer. Also, the comments under question are explaining the same.

I am copying some of the comments (as comments are second class members):

If you want the UI thread to update before "ping thing" completes, you can't do "ping thing" on the UI thread. Do it in a Task. – 15ee8f99-57ff-4f92-890c-b56153

..........and that long-running tasks like this should generally be done on a background thread. – Cody Gray

Hanging the UI is an anti-pattern too. – 15ee8f99-57ff-4f92-890c-b56153

Any piece of code that you know is going to take at least a few seconds, should be done asynchronously so that you don't block the UI thread (you'll know when this happens because your program will freeze). Give this a read: msdn.microsoft.com/library/hh191443(vs.110).aspx – ThePerplexedOne

OwnerDisplayName: anon

LastEditorDisplayName: anon

ContentLicense: CC BY-SA 4.0


问:
opencart admin session not working in localhost. it is redirecting to localhost/admin
I am using Opencart 2.3.0.2, and just installed in localhost and also created a database. during installation i gave username and password for admin. but admin side is not getting.
 when i write ther url localhost/mysitename/admin it is redirecting to localhost/admin..</p>

答:
You need to open the .htaccess file and change the line that says where your eshop is installed.

By default is:

```<code>RewriteBase /
</code>```

But in your case you need to change it to:

```<code>RewriteBase /mysitename/
</code>```

Body:
You need to open the .htaccess file and change the line that says where your eshop is installed.

By default is:

RewriteBase /

But in your case you need to change it to:

RewriteBase /mysitename/


问:
Various vertex format and vbo
I use a rendering loop as follow;

Orphan the data and map the buffer.

Record the command and write the generated vertex in the buffer.

Unmap the buffer.

Iterate over the commands that can change states, bind textures or draw.

At the moment I use a single interleaved vertex format (SoA) that has all the attribute any of my shaders can use.

```<code>struct OneSizeFitAllVertex
{
    float pos[3];
    float uv0[2];
    float uv1[2];
    float col[4];
};
</code>```

When using simpler shader that only use the position and color for example, I would only write the attribute that I care about in the mapped memory and the shader code would simply ignore all the unused attributes.

Because this feel wasteful, I am considering using different vertex format for each of my shaders.

Simple objects rendered using the simple shader would use SimpleVertex:

```<code>struct SimpleVertex
{
    float pos[3];
    float col[4];
};
</code>```

While others, multi-textured objects, would be rendered using multitexture shader and use MultitextureVertex:

```<code>struct MultitextureVertex
{
    float pos[3];
    float uv0[2];
    float uv1[2];
};
</code>```

How should I handle these different format?

Should I write all the vertex of different format in the same mapped buffer and change my AttribPointers before drawing? This would save some space.

Should I map a different buffers for each vertex formats? Perhaps more efficient.

Or should I keep the 'one size fit all' vertex format? This is easier.

I am curious to learn what is the best practice in this situation.
Thanks.

答:
There can be a lot of variations based on your underlying system architecture, but let's assume you're using a discrete GPU (e.g., AMD or NVIDIA) with dedicated graphics memory.

You don't mention if you interleave your attributes in an array of structures (AoS) (perhaps something like the following):

```<code>struct Vertex {
    float position[3];
    float normal[3];
    float uv[2];
    ...
};
</code>```

or group similar attributes together (commonly called a structure of arrays or (SoA))

```<code>struct VertexAttributes {
    float positions[N][3];
    float normals[N][3];
    float uv[N][2];
    ...
};
</code>```

This is relevant given you're buffer-mapping approach.  When you map in an entire buffer, the GPU likely needs to copy its version of the buffer to the CPU, who provides you the pointer to update the values.  When you unmap the buffer, the driver will copy the buffer back to the GPU.  With the AoS layout and your technique, you'll touch small subsections of the entire buffer, and since the GPU driver doesn't know which bits of memory you've updated, it's only recourse is to copy the entire thing back to the GPU.  Depending on the size, this can have significant impact at several levels (poor CPU cache-read utilization, consuming lots of CPU-to-GPU bus bandwidth, etc.).  Unfortunately, there aren't good alternatives if you're only updating a small fraction of your vertex attributes.  However, if you're updating all of the attributes, this approach is okay (although it's often recommended to use glBufferSubData or similar commands, which save the read back from the GPU to the CPU).

Conversely, if you're using the SoA approach, mapping the entire buffer in will cause the similar problems, but the situation can be better.  Since the values for a specific attribute are contiguous in memory, you can use something like glMapBufferRange to only map in the memory you need (but again, I'd still recommend using glBufferSubData for the previously stated reasons).  Given your current scenario, this is what I'd recommend.

Title: Various vertex format and vbo

Body:
I use a rendering loop as follow;

Orphan the data and map the buffer.

Record the command and write the generated vertex in the buffer.

Unmap the buffer.

Iterate over the commands that can change states, bind textures or draw.

At the moment I use a single interleaved vertex format (SoA) that has all the attribute any of my shaders can use.

struct OneSizeFitAllVertex
{
    float pos[3];
    float uv0[2];
    float uv1[2];
    float col[4];
};

When using simpler shader that only use the position and color for example, I would only write the attribute that I care about in the mapped memory and the shader code would simply ignore all the unused attributes.

Because this feel wasteful, I am considering using different vertex format for each of my shaders.

Simple objects rendered using the simple shader would use SimpleVertex:

struct SimpleVertex
{
    float pos[3];
    float col[4];
};

While others, multi-textured objects, would be rendered using multitexture shader and use MultitextureVertex:

struct MultitextureVertex
{
    float pos[3];
    float uv0[2];
    float uv1[2];
};

How should I handle these different format?

Should I write all the vertex of different format in the same mapped buffer and change my AttribPointers before drawing? This would save some space.

Should I map a different buffers for each vertex formats? Perhaps more efficient.

Or should I keep the 'one size fit all' vertex format? This is easier.

I am curious to learn what is the best practice in this situation.
Thanks.

Body:
There can be a lot of variations based on your underlying system architecture, but let's assume you're using a discrete GPU (e.g., AMD or NVIDIA) with dedicated graphics memory.

You don't mention if you interleave your attributes in an array of structures (AoS) (perhaps something like the following):

struct Vertex {
    float position[3];
    float normal[3];
    float uv[2];
    ...
};

or group similar attributes together (commonly called a structure of arrays or (SoA))

struct VertexAttributes {
    float positions[N][3];
    float normals[N][3];
    float uv[N][2];
    ...
};

This is relevant given you're buffer-mapping approach.  When you map in an entire buffer, the GPU likely needs to copy its version of the buffer to the CPU, who provides you the pointer to update the values.  When you unmap the buffer, the driver will copy the buffer back to the GPU.  With the AoS layout and your technique, you'll touch small subsections of the entire buffer, and since the GPU driver doesn't know which bits of memory you've updated, it's only recourse is to copy the entire thing back to the GPU.  Depending on the size, this can have significant impact at several levels (poor CPU cache-read utilization, consuming lots of CPU-to-GPU bus bandwidth, etc.).  Unfortunately, there aren't good alternatives if you're only updating a small fraction of your vertex attributes.  However, if you're updating all of the attributes, this approach is okay (although it's often recommended to use glBufferSubData or similar commands, which save the read back from the GPU to the CPU).

Conversely, if you're using the SoA approach, mapping the entire buffer in will cause the similar problems, but the situation can be better.  Since the values for a specific attribute are contiguous in memory, you can use something like glMapBufferRange to only map in the memory you need (but again, I'd still recommend using glBufferSubData for the previously stated reasons).  Given your current scenario, this is what I'd recommend.


问:
How does this reinterpret_cast work? (Porting C++ to Java)
I have some C++ code I'm trying to port to Java, that looks like this:

```<code>struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}
</code>```

What is the reinterpret_cast doing?

答: you have a pointer to unsigned char right? Now imagine that the bits pointed to by the pointer are treated as though it were an object of type foostruct. That's what reinterpret_cast does - it reinterprets the bit pattern to be a memory representation of another type...  </p>

Body:
I have some C++ code I'm trying to port to Java, that looks like this:

struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}

What is the reinterpret_cast doing?


问:
when I use use pipe when the command is stored in a string, the pipe will be recognized as '|', why?
I excute bash shell like this

```<code>cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd
</code>```

the result is

```<code>sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here
</code>```

I konw 'eval' can work
but I want to know why it can't

答:
maybe what you need is a function

```<code>function cmd {
    cat tmp1.list tmp2.list | sort > tmp3.list
}

cmd
</code>```

also aliases works string with but they used in interactive shell.

Body:
I excute bash shell like this

cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd

the result is

sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here

I konw 'eval' can work
but I want to know why it can't

Body:
maybe what you need is a function

function cmd {
    cat tmp1.list tmp2.list | sort > tmp3.list
}

cmd

also aliases works string with but they used in interactive shell.