问:
'Specified cast is not valid' error in ASP.net MVC application. Works locally, and for a time after publishing, but then throws the error
My MVC application has worked fine for over a year, but it has now started causing the error below when run online. It works fine locally in debug though.

I made some changes on a Thursday, and it suddenly started causing the error the following Monday (changes were minor, HTML table layout changes). The error is intermittent, and seems to go away for a while (a day or so) if we restart the server. Any ideas what it could be?

Please let me know if you need any more information.

Thanks

Chris

```<code>Server Error in '/ISIS' Application.
--------------------------------------------------------------------------------

Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.SqlClient.SqlBuffer.get_Int32() +4838981
   System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +38
   Read_Target(ObjectMaterializer`1 ) +275
   System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +29
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7667556
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
   ISIS2.Controllers.HomeController.Index() in C:\VS2008\VisualStudio\Projects\ISIS2\ISIS2\Controllers\HomeController.cs:66
   lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
   System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
   System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +395
   System.Web.Mvc.Controller.ExecuteCore() +123
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +145
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
   System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
</code>```

EDIT here is the code for the index in HomeController:

```<code> public ActionResult Index()
        {
            try
            {
            var user = (Staff)Session["CurrentUser"];

                int reminder = 14;
                if (Request.Form["AlertPeriod"] != null)
                {
                    reminder = int.Parse(Request.Form["AlertPeriod"]);
                }
                if (Request.Form["AlertPeriodLower"] != null)
                {
                    reminder -= 14;
                }
                else if (Request.Form["AlertPeriodHigher"] != null)
                {
                    reminder += 14;
                }
                ViewData["AlertPeriod"] = reminder;
                ViewData["Alerts"] = (from a in db.Alerts
                                      where a.AlertType.Text == "StaffNews" &&
                                      ((a.StartDate >= DateTime.Today && a.StartDate <= DateTime.Today.AddDays(reminder)) ||
                                       (a.EndDate >= DateTime.Today && a.EndDate <= DateTime.Today.AddDays(reminder)) ||
                                       (a.StartDate <= DateTime.Today && a.EndDate >= DateTime.Today.AddDays(reminder)))
                                      orderby a.EndDate
                                      select a).ToList();
                ViewData["Targets"] = (from t in db.Targets
                                       where t.StaffID == user.StaffID &&
                                       ((t.TargetContextType.Description == "StudentSet" && !t.Read) || (t.TargetDiscussions.Any(td => td.AuthorIsStudent && !td.Read)))
                                       orderby (t.Enrolment != null ? t.Enrolment.Course.Name : ""), t.DateDue
                                       select t).ToList();

                ViewData["Trips"] = (from t in db.Trips
                                     where t.TripStartDate >= DateTime.Today && t.TripStartDate <= DateTime.Today.AddDays(14) && t.StaffID == user.StaffID
                                     orderby t.TripStartDate
                                     select t);

                ViewData["Attending"] = (from a in db.TripAttendings
                                         where a.Trip.StaffID == user.StaffID
                                         select a);

                return View("Index", user);
            }
            catch (NullReferenceException e)
            {
                return RedirectToAction("NonUserIndex");
            }
        }
</code>```

答: It looks like on Line 66 of your HomeController class you are running a SQL query (via Linq) which is getting a DBNull when it expects an Int32

Body:
My MVC application has worked fine for over a year, but it has now started causing the error below when run online. It works fine locally in debug though.

I made some changes on a Thursday, and it suddenly started causing the error the following Monday (changes were minor, HTML table layout changes). The error is intermittent, and seems to go away for a while (a day or so) if we restart the server. Any ideas what it could be?

Please let me know if you need any more information.

Thanks

Chris

Server Error in '/ISIS' Application.
--------------------------------------------------------------------------------

Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.SqlClient.SqlBuffer.get_Int32() +4838981
   System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +38
   Read_Target(ObjectMaterializer`1 ) +275
   System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +29
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7667556
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
   ISIS2.Controllers.HomeController.Index() in C:\VS2008\VisualStudio\Projects\ISIS2\ISIS2\Controllers\HomeController.cs:66
   lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
   System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
   System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +395
   System.Web.Mvc.Controller.ExecuteCore() +123
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +145
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
   System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

EDIT here is the code for the index in HomeController:

 public ActionResult Index()
        {
            try
            {
            var user = (Staff)Session["CurrentUser"];

                int reminder = 14;
                if (Request.Form["AlertPeriod"] != null)
                {
                    reminder = int.Parse(Request.Form["AlertPeriod"]);
                }
                if (Request.Form["AlertPeriodLower"] != null)
                {
                    reminder -= 14;
                }
                else if (Request.Form["AlertPeriodHigher"] != null)
                {
                    reminder += 14;
                }
                ViewData["AlertPeriod"] = reminder;
                ViewData["Alerts"] = (from a in db.Alerts
                                      where a.AlertType.Text == "StaffNews" &&
                                      ((a.StartDate >= DateTime.Today && a.StartDate <= DateTime.Today.AddDays(reminder)) ||
                                       (a.EndDate >= DateTime.Today && a.EndDate <= DateTime.Today.AddDays(reminder)) ||
                                       (a.StartDate <= DateTime.Today && a.EndDate >= DateTime.Today.AddDays(reminder)))
                                      orderby a.EndDate
                                      select a).ToList();
                ViewData["Targets"] = (from t in db.Targets
                                       where t.StaffID == user.StaffID &&
                                       ((t.TargetContextType.Description == "StudentSet" && !t.Read) || (t.TargetDiscussions.Any(td => td.AuthorIsStudent && !td.Read)))
                                       orderby (t.Enrolment != null ? t.Enrolment.Course.Name : ""), t.DateDue
                                       select t).ToList();

                ViewData["Trips"] = (from t in db.Trips
                                     where t.TripStartDate >= DateTime.Today && t.TripStartDate <= DateTime.Today.AddDays(14) && t.StaffID == user.StaffID
                                     orderby t.TripStartDate
                                     select t);

                ViewData["Attending"] = (from a in db.TripAttendings
                                         where a.Trip.StaffID == user.StaffID
                                         select a);

                return View("Index", user);
            }
            catch (NullReferenceException e)
            {
                return RedirectToAction("NonUserIndex");
            }
        }


来源: stackexchange

问:
C# - Html Agility Pack - Get option tag value that matches text content
I am making an automation application using Html Agility Pack for a website.
Each product on the website has a different html code for size and I'm trying to get that code from a product.

This is the website and an example product: Click here

Here is my current code:

```<code>var webGet = new HtmlWeb();
var doc = webGet.Load(txtLink.Text);

HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//*[contains(@id,'size')]");
foreach (var node in collection)
{
var Size = node.InnerHtml.ToString();
txtLog.Text += Environment.NewLine + Size;
}
</code>```

Here is the response for the example product:

```<code><option value="33455">Small
<option value="33456">Medium
<option value="33457">Large
<option value="33458">XLarge
</code>```

If you don't want to check the website this is what the html code looks like for an item:

```<code><select name="size" id="size"><option value="33455">Small</option>
<option value="33456">Medium</option>
<option value="33457">Large</option>
<option value="33458">XLarge</option>
</select>
</code>```

What I want to happen:

I enter the product link for an item and select a size. If the size selected is found then return the size code for that size only. For example I use the example item and select Medium so the application should return 33456.

答:
One way to achieve this using LINQ and case-insensitive matching:</p>

```<code>var size = "xlarge";
var option = document
    .GetElementbyId("size")
    .ChildNodes
    .Where(x => x.Name == "option"
        && x.NextSibling.InnerText
            .IndexOf(size, StringComparison.OrdinalIgnoreCase) != -1)
    .FirstOrDefault();

var result = option != null
    ? option.Attributes["value"].Value
    : "not found";
Console.WriteLine("{0}: {1}", size, result);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am making an automation application using Html Agility Pack for a website.
Each product on the website has a different html code for size and I'm trying to get that code from a product.

This is the website and an example product: Click here

Here is my current code:

var webGet = new HtmlWeb();
var doc = webGet.Load(txtLink.Text);

HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//*[contains(@id,'size')]");
foreach (var node in collection)
{
var Size = node.InnerHtml.ToString();
txtLog.Text += Environment.NewLine + Size;
}

Here is the response for the example product:

<option value="33455">Small
<option value="33456">Medium
<option value="33457">Large
<option value="33458">XLarge

If you don't want to check the website this is what the html code looks like for an item:

<select name="size" id="size"><option value="33455">Small</option>
<option value="33456">Medium</option>
<option value="33457">Large</option>
<option value="33458">XLarge</option>
</select>

What I want to happen:

I enter the product link for an item and select a size. If the size selected is found then return the size code for that size only. For example I use the example item and select Medium so the application should return 33456.

Body:
One way to achieve this using LINQ and case-insensitive matching:

var size = "xlarge";
var option = document
    .GetElementbyId("size")
    .ChildNodes
    .Where(x => x.Name == "option"
        && x.NextSibling.InnerText
            .IndexOf(size, StringComparison.OrdinalIgnoreCase) != -1)
    .FirstOrDefault();

var result = option != null
    ? option.Attributes["value"].Value
    : "not found";
Console.WriteLine("{0}: {1}", size, result);


问:
Finding the max value of a list of tuples, (applying max to the second value of the tuple)
So I have a list of tuples which I created from zipping two lists like this:

```<code>zipped =list(zip(neighbors, cv_scores))
</code>```

max(zipped) produces
    (49, 0.63941769316909292)    where 49 is the max value.

However, I'm interesting in finding the max value among the latter value of the tuple (the .63941).

How can I do that?

答:
max(zipped)[1]
#returns second element of the tuple

This should solve your problem in case you want to sort your data
and find the maximum you can use itemgetter

```<code>from operator import itemgetter
zipped.sort(key=itemgetter(1), reverse = True)
print(zipped[0][1]) #for maximum
</code>```

Body:
So I have a list of tuples which I created from zipping two lists like this:

zipped =list(zip(neighbors, cv_scores))

max(zipped) produces
    (49, 0.63941769316909292)    where 49 is the max value.

However, I'm interesting in finding the max value among the latter value of the tuple (the .63941).

How can I do that?

Body:
max(zipped)[1]
#returns second element of the tuple

This should solve your problem in case you want to sort your data
and find the maximum you can use itemgetter

from operator import itemgetter
zipped.sort(key=itemgetter(1), reverse = True)
print(zipped[0][1]) #for maximum


问:
How to disable or hide "Today" button for angularui-datepicker based on condition if its weekend
How to hide/disable "Today" button based on condition. Let's say if today is weekend. I want to hide "Today" button.

```<code><div class="form-group">
      <div class="input-group datePicker">
              <input id="dt-date" name="dt-date" class="form-control"
                type="text" size="10" ng-model-options="{updateOn: 'default'}"
                required required-err-message="Date is Required"
                uib-datepicker-popup="{{TestVm.datePickerFormat}}"
                ng-model="TestVm.date"
                is-open="TestVm.dateDatePicker.isOpen"
                datepicker-options="TestVm.datePickerOptions"
                close-text="Close" alt-input-formats="TestVm.datePickerAltInputFormats" />

                <span class="input-group-btn">
                   <button type="button" ng-model-options="{updateOn: 'default'}" class="btn btn-default" ng-click="TestVm.dateDatePicker()">
                   <i class="glyphicon glyphicon-calendar"></i>
                   </button>
                </span>
      </div>
</div>
</code>```

Datepicker options in Angular Controller

```<code>TestVm.datePickerOptions = {
                formatYear: 'yy',
                startingDay: 1,
                showWeeks: false,
                dateDisabled: myDisabledDates
            };
</code>```

Function which disables weekends

```<code>function myDisabledDates(dateAndMode) {

        return (dateAndMode.mode === 'day' && (dateAndMode.date.getDay() === 0 || dateAndMode.date.getDay() === 6)) ;
    }
</code>```

Datepicker Image

答:
The dateDisabled is used to disable the dates in the calendar so you cannot click on them, not to hide the Today button. If you wish to hide the Today button you are going to have to override the template used to display the calendar and give the Today button an ID so that you can reference it and hide it.
From the uid-datepicker documentation

template-url (Default: uib/template/datepicker/datepicker.html) - Add
  the ability to override the template used on the component.

You should copy that template and give it your own name and then reference that. In the template, give the Today button an ID, e.g. ID="myTodayButton".

You will then need to write a function that gets the current day and if it is a weekend then disable or hide the myTodayButton.

Body:
How to hide/disable "Today" button based on condition. Let's say if today is weekend. I want to hide "Today" button.

              <input id="dt-date" name="dt-date" class="form-control"
                type="text" size="10" ng-model-options="{updateOn: 'default'}"
                required required-err-message="Date is Required"
                uib-datepicker-popup="{{TestVm.datePickerFormat}}"
                ng-model="TestVm.date"
                is-open="TestVm.dateDatePicker.isOpen"
                datepicker-options="TestVm.datePickerOptions"
                close-text="Close" alt-input-formats="TestVm.datePickerAltInputFormats" />

                   <button type="button" ng-model-options="{updateOn: 'default'}" class="btn btn-default" ng-click="TestVm.dateDatePicker()">

                   </button>

Datepicker options in Angular Controller

TestVm.datePickerOptions = {
                formatYear: 'yy',
                startingDay: 1,
                showWeeks: false,
                dateDisabled: myDisabledDates
            };

Function which disables weekends

function myDisabledDates(dateAndMode) {

        return (dateAndMode.mode === 'day' && (dateAndMode.date.getDay() === 0 || dateAndMode.date.getDay() === 6)) ;
    }

Datepicker Image


问:
FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri()) return null on Facebook
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

```<code>private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}
</code>```

And then write Call back method

```<code>private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}
</code>```

Then generate service login url

```<code>private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}
</code>```

答:
Building onto Steve's post, I created a "FriendlyFacebookClient" to use in-place of FacebookClient, copied over some of the internal methods, and replaced QueryAccessToken with the following:</p>

```<code>  protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            UriBuilder builder = new UriBuilder("https://graph.facebook.com/oauth/access_token");
            AppendQueryArgs(builder, (IEnumerable<KeyValuePair<string, string>>)new Dictionary<string, string>()
              {
                { "client_id", this.appId},
                { "redirect_uri", FriendlyFacebookClient.NormalizeHexEncoding(returnUrl.AbsoluteUri)},
                { "client_secret",  this.appSecret },
                { "code",  authorizationCode },
                { "scope", "email" }
              });

            using (WebClient webClient = new WebClient())
            {
                var response = webClient.DownloadString(builder.Uri);
                var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
                return data["access_token"];
            }
        }
</code>```

Body:
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}

And then write Call back method

private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}

Then generate service login url

private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}

Body:
Building onto Steve's post, I created a "FriendlyFacebookClient" to use in-place of FacebookClient, copied over some of the internal methods, and replaced QueryAccessToken with the following:

  protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            UriBuilder builder = new UriBuilder("https://graph.facebook.com/oauth/access_token");
            AppendQueryArgs(builder, (IEnumerable<KeyValuePair<string, string>>)new Dictionary<string, string>()
              {
                { "client_id", this.appId},
                { "redirect_uri", FriendlyFacebookClient.NormalizeHexEncoding(returnUrl.AbsoluteUri)},
                { "client_secret",  this.appSecret },
                { "code",  authorizationCode },
                { "scope", "email" }
              });

            using (WebClient webClient = new WebClient())
            {
                var response = webClient.DownloadString(builder.Uri);
                var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
                return data["access_token"];
            }
        }


问:
What kind of feature extractor is used in vowpal wabbit?
In sklearn when we pass sentence to algorithms we can use text features extractors like the countvectorizer, tf-idf vectoriser etc... And we get an array of floats.

But what we get when passed to vowpal wabbit the input file like this one:

```<code>-1 |Words The sun is blue
1 |Words The sun is yellow
</code>```

What is used in internal implementation of vowpal wabbit? How does this text transform?

答:
There are two separate questions here:

Q1: Why can't you (and shouldn't you) use transformations like tf-idf when using vowpal wabbit ?

A1: vowpal wabbit is not a batch learning system, it is an online-learning system. In order to compute measures like tf-idf (term frequency in each document vs the whole corpus) you need to see all the data (corpus) first, and sometimes do multiple passes over the data.  vowpal wabbit as an online/incremental learning system is designed to also work on problems where you don't have the full data ahead of time.  See This answer for a lot more details.

Q2: How does vowpal wabbit "transform" the features it sees ?

A2: It doesn't.  It simply maps each word feature on-the-fly to its hashed location in memory.  The online learning step is driven by a repetitive optimization loop (SGD or BFGS) example by example, to minimize the modeling error. You may select the loss function to optimize for.

However, if you already have the full data you want to train on, nothing prevents you from transforming it (using any other tool) before feeding the transformed values to vowpal wabbit. It's your choice. Depending on the particular data, you may get better or worse results using a transformation pre-pass, than by running multiple passes with vowpal wabbit itself without preliminary transformations (check-out the vw --passes option).

To complete the answer, let's add another related question:

Q3: Can I use pre-transformed (e.g. tf-idf) data with vowpal wabbit ?

A3: Yes, you can. Just use the following (post-transformation) form.  Instead of words, use integers as feature IDs and since any feature can have an optional explicit weight, use the tf-idf floating point as weights, following the : separator in typical SVMlight format:

```<code>-1 |  1:0.534  15:0.123  3:0.27  29:0.066  ...
1  |  3:0.1  102:0.004  24:0.0304  ...
</code>```

The reason this works, is because vw has a nice feature of distinguishing between string and integer-features. It doesn't hash feature-names that look like integers (unless you use the --hash_all option explicitly). Integer feature numbers are used directly as if they were the hash result of the feature.

Body:
In sklearn when we pass sentence to algorithms we can use text features extractors like the countvectorizer, tf-idf vectoriser etc... And we get an array of floats.

But what we get when passed to vowpal wabbit the input file like this one:

-1 |Words The sun is blue
1 |Words The sun is yellow

What is used in internal implementation of vowpal wabbit? How does this text transform?

Body:
There are two separate questions here:

Q1: Why can't you (and shouldn't you) use transformations like tf-idf when using vowpal wabbit ?

A1: vowpal wabbit is not a batch learning system, it is an online-learning system. In order to compute measures like tf-idf (term frequency in each document vs the whole corpus) you need to see all the data (corpus) first, and sometimes do multiple passes over the data.  vowpal wabbit as an online/incremental learning system is designed to also work on problems where you don't have the full data ahead of time.  See This answer for a lot more details.

Q2: How does vowpal wabbit "transform" the features it sees ?

A2: It doesn't.  It simply maps each word feature on-the-fly to its hashed location in memory.  The online learning step is driven by a repetitive optimization loop (SGD or BFGS) example by example, to minimize the modeling error. You may select the loss function to optimize for.

However, if you already have the full data you want to train on, nothing prevents you from transforming it (using any other tool) before feeding the transformed values to vowpal wabbit. It's your choice. Depending on the particular data, you may get better or worse results using a transformation pre-pass, than by running multiple passes with vowpal wabbit itself without preliminary transformations (check-out the vw --passes option).

To complete the answer, let's add another related question:

Q3: Can I use pre-transformed (e.g. tf-idf) data with vowpal wabbit ?

A3: Yes, you can. Just use the following (post-transformation) form.  Instead of words, use integers as feature IDs and since any feature can have an optional explicit weight, use the tf-idf floating point as weights, following the : separator in typical SVMlight format:

-1 |  1:0.534  15:0.123  3:0.27  29:0.066  ...
1  |  3:0.1  102:0.004  24:0.0304  ...

The reason this works, is because vw has a nice feature of distinguishing between string and integer-features. It doesn't hash feature-names that look like integers (unless you use the --hash_all option explicitly). Integer feature numbers are used directly as if they were the hash result of the feature.


问:
Lodash template return function says data undefined
I am working on a code gen tool, and I am using Lodash to template the output files.  When I try running the resultant function from _.template(XXX) I get

"AppData" (the name of the template variable) is not defined.

I have tried to call temp below with and without the AppData variable and both give me

"ReferenceError: AppData is not defined"

```<code>templates.forEach((template) => {
      let temp = _.template(template, { AppData: AppData });
      output = temp(AppData);
    });
</code>```

This is the AppData object:

```<code>let AppData = { clientId: clientId,
                appId: applicationId,
                intents: ['Testing1',
                          'Testing2',
                          'Testing3',
                          'Testing4'
                         ]};
</code>```

Here is one of the 3 templates:

```<code><% _.each(AppData.intents, function( intent ){ %>
<transition event="<%=intent%>" target="<%=intent%>">
<state id="<%=intent%>">
<onentry>
<assign location="href_answer" expr="tfs.getKBAPIUrl(DNIS, environment, '<%=intent%>')"/>
<assign location="reason" expr="'<%=intent%>'"/>
<script><![CDATA[presentAnswer(href_answer,reason);]]></script>
</onentry>
  </state>
<% }) %>
</code>```

Stack is not letting me post the output, but it's the function representing the finished template.

答:
Perhaps you should step back and get the lodash to first do the templating first and then once you get the templating work, then introduce more complexity...

```<code>var tfsStr = document.querySelector('#tfs-template').textContent;
var compiled = _.template(tfsStr, {
  intents: AppData.intents,
  _: _
});
</code>```

I did a little codepen to test the templating

Body:
I am working on a code gen tool, and I am using Lodash to template the output files.  When I try running the resultant function from _.template(XXX) I get

"AppData" (the name of the template variable) is not defined.

I have tried to call temp below with and without the AppData variable and both give me

"ReferenceError: AppData is not defined"

templates.forEach((template) => {
      let temp = _.template(template, { AppData: AppData });
      output = temp(AppData);
    });

This is the AppData object:

let AppData = { clientId: clientId,
                appId: applicationId,
                intents: ['Testing1',
                          'Testing2',
                          'Testing3',
                          'Testing4'
                         ]};

Here is one of the 3 templates:

<% _.each(AppData.intents, function( intent ){ %>
<transition event="<%=intent%>" target="<%=intent%>">
<state id="<%=intent%>">
<onentry>
<assign location="href_answer" expr="tfs.getKBAPIUrl(DNIS, environment, '<%=intent%>')"/>
<assign location="reason" expr="'<%=intent%>'"/>

</onentry>
  </state>
<% }) %>

Stack is not letting me post the output, but it's the function representing the finished template.

Body:
Perhaps you should step back and get the lodash to first do the templating first and then once you get the templating work, then introduce more complexity...

var tfsStr = document.querySelector('#tfs-template').textContent;
var compiled = _.template(tfsStr, {
  intents: AppData.intents,
  _: _
});

I did a little codepen to test the templating


问:
Session cookies working on all subdomains
i have my site set up like this:

```<code>RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]
</code>```

what this does is if user visits: test.example.com, it will show contents of folder: example.com/user/profile.php?name=test. if someone goes to lol.example.com, it will show page: example.com/user/profile.php?name=lol

Question 1:

right now, I have a problem with it. if i go to test.example.com/login, it will show my domain root file. how can i make it so that it will show things from /user folder? for example: test.example.com/login will show example.com/user/login and test.example.com/register will show example.com/user/register?

Question 2: SOLVED

right now if i log in on the subdomain, the session cookie (PHP) is only set for the subdomain. how can i make the cookies work for the whole site with (example.com) domain?

thanks

UPDATE: for example: test.example.com/pathtofile should get the contents of example.com/user/pathtofile. "pathtofile" should be dynamic. i just want the path to look in the folder /user, not the root folder.

答:
Try something like this</p>

```<code>RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]
RewriteRule (.*) /user/$1 [L]
</code>```

Body:
i have my site set up like this:

RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]

what this does is if user visits: test.example.com, it will show contents of folder: example.com/user/profile.php?name=test. if someone goes to lol.example.com, it will show page: example.com/user/profile.php?name=lol

Question 1:

right now, I have a problem with it. if i go to test.example.com/login, it will show my domain root file. how can i make it so that it will show things from /user folder? for example: test.example.com/login will show example.com/user/login and test.example.com/register will show example.com/user/register?

Question 2: SOLVED

right now if i log in on the subdomain, the session cookie (PHP) is only set for the subdomain. how can i make the cookies work for the whole site with (example.com) domain?

thanks

UPDATE: for example: test.example.com/pathtofile should get the contents of example.com/user/pathtofile. "pathtofile" should be dynamic. i just want the path to look in the folder /user, not the root folder.

Body:
Try something like this

RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]
RewriteRule (.*) /user/$1 [L]


问:
How to Change Global Variable With Function?
I am trying to create a "Choose your own adventure" style game in Python where the user inserts various numbers that correspond with an action that will dictate what part of the story is told next. When the user inserts an invalid option, nothing I tried to make a function to simplify the endless if/else statements but I am having difficulties. I have a "step" variable that changes and leads to different circumstances and my function successfully changes the step variable but then the if/else statements don't trigger. Any help would be greatly appreciated!</p>

```<code>step = 7

def stepchange():
  global step
  b = step
  while step == b:
    a = input()
    if a == 1:
      global step
      step = b + .1
    if a == 2:
      global step
      step = b + .2
    if a ==3:
      global step
      step = b + .3

global step
if step == 7.1:
   print("Step 7.1")

global step
if step == 7.2:
    print("Step 7.2")

global step
if step ==7.3:
    print("Step 7.3")
</code>```

答:
As mentioned in the comments, float comparisons are tricky. Since you are getting text input, you might as well continue with text.

```<code>step = "7"

def stepchange():
    global step
    b = step
    a = input()
    if a == "1":
        step = b + ".1"
    if a == "2":
        step = b + ".2"
    if a =="3":
        step = b + ".3"

if step == "7.1":
    print("Step 7.1")
elif step == "7.2":
    print("Step 7.2")
elif step == "7.3":
    print("Step 7.3")
</code>```

Body:
I am trying to create a "Choose your own adventure" style game in Python where the user inserts various numbers that correspond with an action that will dictate what part of the story is told next. When the user inserts an invalid option, nothing I tried to make a function to simplify the endless if/else statements but I am having difficulties. I have a "step" variable that changes and leads to different circumstances and my function successfully changes the step variable but then the if/else statements don't trigger. Any help would be greatly appreciated!

step = 7

def stepchange():
  global step
  b = step
  while step == b:
    a = input()
    if a == 1:
      global step
      step = b + .1
    if a == 2:
      global step
      step = b + .2
    if a ==3:
      global step
      step = b + .3

global step
if step == 7.1:
   print("Step 7.1")

global step
if step == 7.2:
    print("Step 7.2")

global step
if step ==7.3:
    print("Step 7.3")

Body:
As mentioned in the comments, float comparisons are tricky. Since you are getting text input, you might as well continue with text.

step = "7"

def stepchange():
    global step
    b = step
    a = input()
    if a == "1":
        step = b + ".1"
    if a == "2":
        step = b + ".2"
    if a =="3":
        step = b + ".3"

if step == "7.1":
    print("Step 7.1")
elif step == "7.2":
    print("Step 7.2")
elif step == "7.3":
    print("Step 7.3")


问:
Tsql -> filter data 6 months from today, date field in table is YYYYMM
I need some help.
Currently is March 2017.
how do I extract all records 6 months ago from February 2017 until end of this year. the date format in my table is in YYYYMM

Here is my sql statement

```<code>select columns from budget
where month_number > = DATEADD(MONTH, -6, CURRENT_TIMESTAMP);
</code>```

the output I am getting is as below:

```<code>+------------+-------+--------------+
| month_name | month | month_number |
+------------+-------+--------------+
| January    |     1 |       201601 |
| February   |     2 |       201602 |
| March      |     3 |       201603 |
| April      |     4 |       201604 |
| May        |     5 |       201605 |
| June       |     6 |       201606 |
| July       |     7 |       201607 |
| August     |     8 |       201608 |
| September  |     9 |       201609 |
| October    |    10 |       201610 |
| November   |    11 |       201611 |
| December   |    12 |       201612 |
| January    |     1 |       201701 |
| February   |     2 |       201702 |
| March      |     3 |       201703 |
| April      |     4 |       201704 |
| July       |     7 |       201707 |
| December   |    12 |       201712 |
+------------+-------+--------------+
</code>```

I am not getting the right output. I am still getting data from Jan 2016 onwards. Please help

Thanks

答:
```<code> Select *
 From  Budget
 Where month_number>= convert(varchar(6),DATEADD(MONTH, -6, CURRENT_TIMESTAMP),112)
 Order By month_number
</code>```

If 2012+

```<code>Select *
 From  Budget
 Where month_number>=  format(DATEADD(MONTH, -6, CURRENT_TIMESTAMP),'yyyyMM')
 Order By month_number
</code>```

Returns

```<code>month_name  month   month_number
September   9       201609
October     10      201610
November    11      201611
December    12      201612
January     1       201701
February    2       201702
March       3       201703
April       4       201704
July        7       201707
December    12      201712
</code>```

Body:
I need some help.
Currently is March 2017.
how do I extract all records 6 months ago from February 2017 until end of this year. the date format in my table is in YYYYMM

Here is my sql statement

select columns from budget
where month_number > = DATEADD(MONTH, -6, CURRENT_TIMESTAMP);

the output I am getting is as below:

+------------+-------+--------------+
| month_name | month | month_number |
+------------+-------+--------------+
| January    |     1 |       201601 |
| February   |     2 |       201602 |
| March      |     3 |       201603 |
| April      |     4 |       201604 |
| May        |     5 |       201605 |
| June       |     6 |       201606 |
| July       |     7 |       201607 |
| August     |     8 |       201608 |
| September  |     9 |       201609 |
| October    |    10 |       201610 |
| November   |    11 |       201611 |
| December   |    12 |       201612 |
| January    |     1 |       201701 |
| February   |     2 |       201702 |
| March      |     3 |       201703 |
| April      |     4 |       201704 |
| July       |     7 |       201707 |
| December   |    12 |       201712 |
+------------+-------+--------------+

I am not getting the right output. I am still getting data from Jan 2016 onwards. Please help

Thanks

Body:
 Select *
 From  Budget
 Where month_number>= convert(varchar(6),DATEADD(MONTH, -6, CURRENT_TIMESTAMP),112)
 Order By month_number

If 2012+

Select *
 From  Budget
 Where month_number>=  format(DATEADD(MONTH, -6, CURRENT_TIMESTAMP),'yyyyMM')
 Order By month_number

Returns

month_name  month   month_number
September   9       201609
October     10      201610
November    11      201611
December    12      201612
January     1       201701
February    2       201702
March       3       201703
April       4       201704
July        7       201707
December    12      201712


问:
How to create the model class for the following JSON data and parse it?
My JSON data

```<code>{
 "addon_items" : [
                     {
                      "aname" : "",
                      "id" : "2588",
                      "name" : "Plain Nan",
                      "order" : "1",
                      "aid" : "259",
                      "Sub_Add_Items" : "",
                      "icon" : "",
                      "status" : "1",
                      "next" : "0",
                      "price" : "0.60"
                     },
                     {
                      "aname" : "",
                      "id" : "2589",
                      "name" : "Pitta Bread",
                      "order" : "2",
                      "aid" : "259",
                      "Sub_Add_Items" : "",
                      "icon" : "",
                      "status" : "1",
                      "next" : "0",
                      "price" : "0.00"
                    }

                   ],

 "addon" : {
             "description" : "Please choose your Nan bread",
             "aname" : "",
             "id" : "259",
             "icon" : "",
             "limit" : "1",
             "special_addon" : "",
             "next" : "165"
           }
 }
</code>```

I created three class models named AddOnResponse, AddOn, AddOnItems like this:

AddOnResponse class model

```<code>class AddOnResponse {

var addon: Array<String>?
var addonitems: Array<AnyObject>?

init(addon:Array<String>?,addonitems: Array<AnyObject>?){
    self.addon = addon
    self.addonitems = addonitems
 }
}
</code>```

AddOn class model

```<code>class AddOn {

var id: Int?
var icon: String?
var desc: String?
var limit: Int?
var next: Int?
var aname: String?
var specialaddon: Int?

init(id: Int?,icon: String?,desc: String?,limit: Int?,next: Int?,aname: String?,specialaddon: Int?){

    self.id = id
    self.icon = icon
    self.desc = desc
    self.limit = limit
    self.next = next
    self.aname = aname
    self.specialaddon = specialaddon

  }
 }
</code>```

AddOnItems class model

```<code>class AddOnItems {

var id: Int?
var aid: Int?
var name: String?
var price: Int?
var order: Int?
var status: Int?
var next: Int?
var aname: String?
var subaddItems: Int?
var icon: String?

init(id: Int?,aid: Int?,name: String?,price: Int?,order: Int?,status: Int?,next: Int?,aname: String?,subaddItems: Int?,icon: String?){
    self.id = id
    self.aid = aid
    self.name = name
    self.price = price
    self.order = order
    self.status = status
    self.next = next
    self.aname = aname
    self.subaddItems = subaddItems
    self.icon = icon
   }
 }
</code>```

Now I am fetching my JSON data using Alamofire but when accepting dat into class model using object I am getting nil value.

```<code>    var addonResponses = [AddOnResponse]()

    Alamofire.request(.GET, myAddOnUrl)
        .validate()
        .responseJSON
        {   response in
            switch response.result
            {
            case .Success:
                if let value = response.result.value{
                    let json = JSON(value)
                    print(json)
                    print(json["addon"].arrayValue)

           for(_,content) in json{
               let addOnRes = AddOnResponse(addon:content["addon"].arrayValue,
                               addonitems:content["addon_items"].Arrayobject)

                        print(self.addonResponses.count)
                        print(addOnRes.addon)
                        print(addOnRes.addonitems)
                    }
                }
</code>```

The addon and addonitems data are coming nil, why?

答:
```<code>import Foundation
import SwiftyJSON

class UserInfo {

    var mobile : Int?
    var userid : Int?
    var email : String?
    var name : String?

    init() {

    }

    init(json : JSON){
        mobile = json["phone_number"].intValue
        userid = json["id"].intValue
        email = json["email"].stringValue
        name = json["name"].stringValue
    }

}
</code>```

Body:
My JSON data

{
 "addon_items" : [
                     {
                      "aname" : "",
                      "id" : "2588",
                      "name" : "Plain Nan",
                      "order" : "1",
                      "aid" : "259",
                      "Sub_Add_Items" : "",
                      "icon" : "",
                      "status" : "1",
                      "next" : "0",
                      "price" : "0.60"
                     },
                     {
                      "aname" : "",
                      "id" : "2589",
                      "name" : "Pitta Bread",
                      "order" : "2",
                      "aid" : "259",
                      "Sub_Add_Items" : "",
                      "icon" : "",
                      "status" : "1",
                      "next" : "0",
                      "price" : "0.00"
                    }

                   ],

 "addon" : {
             "description" : "Please choose your Nan bread",
             "aname" : "",
             "id" : "259",
             "icon" : "",
             "limit" : "1",
             "special_addon" : "",
             "next" : "165"
           }
 }

I created three class models named AddOnResponse, AddOn, AddOnItems like this:

AddOnResponse class model

class AddOnResponse {

var addon: Array<String>?
var addonitems: Array<AnyObject>?

init(addon:Array<String>?,addonitems: Array<AnyObject>?){
    self.addon = addon
    self.addonitems = addonitems
 }
}

AddOn class model

class AddOn {

var id: Int?
var icon: String?
var desc: String?
var limit: Int?
var next: Int?
var aname: String?
var specialaddon: Int?

init(id: Int?,icon: String?,desc: String?,limit: Int?,next: Int?,aname: String?,specialaddon: Int?){

    self.id = id
    self.icon = icon
    self.desc = desc
    self.limit = limit
    self.next = next
    self.aname = aname
    self.specialaddon = specialaddon

  }
 }

AddOnItems class model

class AddOnItems {

var id: Int?
var aid: Int?
var name: String?
var price: Int?
var order: Int?
var status: Int?
var next: Int?
var aname: String?
var subaddItems: Int?
var icon: String?

init(id: Int?,aid: Int?,name: String?,price: Int?,order: Int?,status: Int?,next: Int?,aname: String?,subaddItems: Int?,icon: String?){
    self.id = id
    self.aid = aid
    self.name = name
    self.price = price
    self.order = order
    self.status = status
    self.next = next
    self.aname = aname
    self.subaddItems = subaddItems
    self.icon = icon
   }
 }

Now I am fetching my JSON data using Alamofire but when accepting dat into class model using object I am getting nil value.

    var addonResponses = [AddOnResponse]()

    Alamofire.request(.GET, myAddOnUrl)
        .validate()
        .responseJSON
        {   response in
            switch response.result
            {
            case .Success:
                if let value = response.result.value{
                    let json = JSON(value)
                    print(json)
                    print(json["addon"].arrayValue)

           for(_,content) in json{
               let addOnRes = AddOnResponse(addon:content["addon"].arrayValue,
                               addonitems:content["addon_items"].Arrayobject)

                        print(self.addonResponses.count)
                        print(addOnRes.addon)
                        print(addOnRes.addonitems)
                    }
                }

The addon and addonitems data are coming nil, why?


问:
Swift 3.1 deprecates initialize(). How can I achieve the same thing?
Objective-C declares a class function, initialize(), that is run once for each class, before it is used. It is often used as an entry point for exchanging method implementations (swizzling), among other things.

Swift 3.1 deprecates this function with a warning:

Method 'initialize()' defines Objective-C class method 'initialize',
  which is not guaranteed to be invoked by Swift and will be disallowed
  in future versions

How can this be resolved, while still maintaining the same behaviour and features that I currently implement using the initialize() entry point?

答:
A slight addition to @JordanSmith's excellent class which ensures that each awake() is only called once:

```<code>protocol SelfAware: class {
    static func awake()
}

@objc class NothingToSeeHere: NSObject {

    private static let doOnce: Any? = {
        _harmlessFunction()
    }()

    static func harmlessFunction() {
        _ = NothingToSeeHere.doOnce
    }

    private static func _harmlessFunction() {
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount { (types[index] as? SelfAware.Type)?.awake() }
        types.deallocate(capacity: typeCount)
    }
}
</code>```

Body:
A slight addition to @JordanSmith's excellent class which ensures that each awake() is only called once:

protocol SelfAware: class {
    static func awake()
}

@objc class NothingToSeeHere: NSObject {

    private static let doOnce: Any? = {
        _harmlessFunction()
    }()

    static func harmlessFunction() {
        _ = NothingToSeeHere.doOnce
    }

    private static func _harmlessFunction() {
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount { (types[index] as? SelfAware.Type)?.awake() }
        types.deallocate(capacity: typeCount)
    }
}

ContentLicense: CC BY-SA 4.0


问:
Specific output pattern of array in java
I've figured out how to create an array in which the output look like this:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

where every other row is "backwards"

`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;

public class Question2 {

```<code>public static void main(String[] args) {

//Title
    System.out.println("[----------------------]");
    System.out.println("[     Array Pattern    ]");
    System.out.println("[----------------------]");
    System.out.println("");
//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;
    for(int i=0;i<array.length;i++)
        for(int j=0;j<array.length;j++)
              {
                 array[i][j]=inc;
                 inc++;
              }

    //replace all square brackets in array display & format into order

            //replace all commas in array display

    String a = Arrays.toString(array);
    a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
    System.out.println(a);`
</code>```

答:
This loop will do it:

```<code>int reverse = 0;

for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
      {
          if(i%2 == 0){
            if(j == 0){
                inc = reverse;
                if(i > 0 )inc = inc + num + 1;
            }
            array[i][j]=inc;
            inc++;
          }
          else{
              if(j == 0)reverse = inc + num - 1;
              array[i][j]=reverse;
              reverse--;
          }
      }
</code>```

Every other row it place numbers in a descending order.

Also to print out the numbers with tabs between them use:

```<code>String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replace(", ", "\t").replaceAll("[\\[\\],]", "");
System.out.println(a);
</code>```

This will stop a table forming diagonally.

Body:
I've figured out how to create an array in which the output look like this:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

where every other row is "backwards"

`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;

public class Question2 {

public static void main(String[] args) {

//Title
    System.out.println("[----------------------]");
    System.out.println("[     Array Pattern    ]");
    System.out.println("[----------------------]");
    System.out.println("");
//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;
    for(int i=0;i<array.length;i++)
        for(int j=0;j<array.length;j++)
              {
                 array[i][j]=inc;
                 inc++;
              }

    //replace all square brackets in array display & format into order

            //replace all commas in array display

    String a = Arrays.toString(array);
    a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
    System.out.println(a);`

Body:
This loop will do it:

int reverse = 0;

for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
      {
          if(i%2 == 0){
            if(j == 0){
                inc = reverse;
                if(i > 0 )inc = inc + num + 1;
            }
            array[i][j]=inc;
            inc++;
          }
          else{
              if(j == 0)reverse = inc + num - 1;
              array[i][j]=reverse;
              reverse--;
          }
      }

Every other row it place numbers in a descending order.

Also to print out the numbers with tabs between them use:

String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replace(", ", "\t").replaceAll("[\\[\\],]", "");
System.out.println(a);

This will stop a table forming diagonally.


问:
Photoshop Script - Get name of visible Layer in Group/Layerset
i'm stuck with a script that detects which layer is visible in a (sub)layerset (aka Group) with the name "Color".

The script below checks for all visible layers and selects them. I can't get it working to do the same thing ONLY in the mentioned layerset.

Any help would be highly appreciated!

#target photoshop
app.bringToFront();

main();
function main(){
if(!documents.length) return;
var Vis = getVisLayers();
deselectLayers();
for(var a in Vis){
    selectLayerById(Number(Vis[a]),true);
    }
}
function getVisLayers(){
   var ref = new ActionReference();
   ref.putEnumerated( charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
   var count = executeActionGet(ref).getInteger(charIDToTypeID('NmbL')) +1;
   var Names=[];
try{
    activeDocument.backgroundLayer;
var i = 0; }catch(e){ var i = 1; };
   for(i;i<count;i++){
       if(i == 0) continue;
        ref = new ActionReference();
        ref.putIndex( charIDToTypeID( 'Lyr ' ), i );
        var desc = executeActionGet(ref);
        var layerName = desc.getString(charIDToTypeID( 'Nm  ' ));
        var Id = desc.getInteger(stringIDToTypeID( 'layerID' ));
        if(layerName.match(/^<\/Layer group/) ) continue;
        var layerType = typeIDToStringID(desc.getEnumerationValue( stringIDToTypeID( 'layerSection' )));
        var isLayerSet =( layerType == 'layerSectionContent') ? false:true;
        var vis = desc.getBoolean(charIDToTypeID( "Vsbl" ));
        if(!isLayerSet && vis) Names.push(Id);
   };
return Names;
};
function selectLayerById(ID, add) {
    add = (add == undefined)  ? add = false : add;
   var ref = new ActionReference();
   ref.putIdentifier(charIDToTypeID('Lyr '), ID);
   var desc = new ActionDescriptor();
   desc.putReference(charIDToTypeID('null'), ref);
   if (add) {
      desc.putEnumerated(stringIDToTypeID('selectionModifier'), stringIDToTypeID('selectionModifierType'), stringIDToTypeID('addToSelection'));
   }
   desc.putBoolean(charIDToTypeID('MkVs'), false);
   executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
}
function deselectLayers() {
    var desc01 = new ActionDescriptor();
        var ref01 = new ActionReference();
        ref01.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
    desc01.putReference( charIDToTypeID('null'), ref01 );
    executeAction( stringIDToTypeID('selectNoLayers'), desc01, DialogModes.NO );
};```

enter image description here

答:
Thanks to @Ghoul Fool i finally managed to get this working. I changed the code a bit as i only need to check which layer is visible and store this name as a variable. Would be great if someone more skilled could correct my code for others who will use it or parts of it.

Thanks again

```<code>// Checking which layer is visible in layeset (group) "Colors" in "Mockup.psd" aka mockupDoc and store it's name for later use in the "save" part.
var front = mockupDoc.layerSets.getByName("Front");
var colors = front.layerSets.getByName("Colors");
for (var m = colors.layers.length - 1; m >= 0; m--)
{
  var theLayer = colors.layers[m];
  if (theLayer.typename == "ArtLayer")
 {
    if (theLayer.visible == true)
    {
      // Sets a variable for the name of the visible Layer in the "Colors" Group, so i can use it later as a part of the Filename when saving.
      var activeColor = theLayer.name;
    }
  }
};
</code>```

Body:
i'm stuck with a script that detects which layer is visible in a (sub)layerset (aka Group) with the name "Color".

The script below checks for all visible layers and selects them. I can't get it working to do the same thing ONLY in the mentioned layerset.

Any help would be highly appreciated!

#target photoshop
app.bringToFront();

main();
function main(){
if(!documents.length) return;
var Vis = getVisLayers();
deselectLayers();
for(var a in Vis){
    selectLayerById(Number(Vis[a]),true);
    }
}
function getVisLayers(){
   var ref = new ActionReference();
   ref.putEnumerated( charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
   var count = executeActionGet(ref).getInteger(charIDToTypeID('NmbL')) +1;
   var Names=[];
try{
    activeDocument.backgroundLayer;
var i = 0; }catch(e){ var i = 1; };
   for(i;i<count;i++){
       if(i == 0) continue;
        ref = new ActionReference();
        ref.putIndex( charIDToTypeID( 'Lyr ' ), i );
        var desc = executeActionGet(ref);
        var layerName = desc.getString(charIDToTypeID( 'Nm  ' ));
        var Id = desc.getInteger(stringIDToTypeID( 'layerID' ));
        if(layerName.match(/^<\/Layer group/) ) continue;
        var layerType = typeIDToStringID(desc.getEnumerationValue( stringIDToTypeID( 'layerSection' )));
        var isLayerSet =( layerType == 'layerSectionContent') ? false:true;
        var vis = desc.getBoolean(charIDToTypeID( "Vsbl" ));
        if(!isLayerSet && vis) Names.push(Id);
   };
return Names;
};
function selectLayerById(ID, add) {
    add = (add == undefined)  ? add = false : add;
   var ref = new ActionReference();
   ref.putIdentifier(charIDToTypeID('Lyr '), ID);
   var desc = new ActionDescriptor();
   desc.putReference(charIDToTypeID('null'), ref);
   if (add) {
      desc.putEnumerated(stringIDToTypeID('selectionModifier'), stringIDToTypeID('selectionModifierType'), stringIDToTypeID('addToSelection'));
   }
   desc.putBoolean(charIDToTypeID('MkVs'), false);
   executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
}
function deselectLayers() {
    var desc01 = new ActionDescriptor();
        var ref01 = new ActionReference();
        ref01.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
    desc01.putReference( charIDToTypeID('null'), ref01 );
    executeAction( stringIDToTypeID('selectNoLayers'), desc01, DialogModes.NO );
};

enter image description here

Body:
Thanks to @Ghoul Fool i finally managed to get this working. I changed the code a bit as i only need to check which layer is visible and store this name as a variable. Would be great if someone more skilled could correct my code for others who will use it or parts of it.

Thanks again

// Checking which layer is visible in layeset (group) "Colors" in "Mockup.psd" aka mockupDoc and store it's name for later use in the "save" part.
var front = mockupDoc.layerSets.getByName("Front");
var colors = front.layerSets.getByName("Colors");
for (var m = colors.layers.length - 1; m >= 0; m--)
{
  var theLayer = colors.layers[m];
  if (theLayer.typename == "ArtLayer")
 {
    if (theLayer.visible == true)
    {
      // Sets a variable for the name of the visible Layer in the "Colors" Group, so i can use it later as a part of the Filename when saving.
      var activeColor = theLayer.name;
    }
  }
};


问:
ProgressDialog created from onCreateDialog stops animating on second run
I create a ProgressDialog in onCreateDialog() like so:

```<code>protected Dialog onCreateDialog(int id) {
  if (id == DIALOG_PROGRESS_ID)
  {
      ProgressDialog dialog = new ProgressDialog(this);
      dialog.setMessage(getResources().getString(R.string.MyLabel));
      dialog.setCancelable(false);
      dialog.setIndeterminate(true);
      return dialog;
  }
}
</code>```

Android, in its wisdom (or serious lack of it) decides to cache every dialog created through onCreateDialog(). Because of that, any subsequent call to showDialog(DIALOG_PROGRESS_ID) results in the same ProgressDialog instance being used but the animation has stopped working.

I've tried to re-set indeterminate in onPrepareDialog(), but that doesn't do anything. There is likewise no obvious method to call on the dialog instance that will reset the animation.

```<code>protected void onPrepareDialog(int id, Dialog dialog)
{
  //This doesn't do anything
  if (id == DIALOG_PROGRESS_ID)
     ((ProgressDialog)dialog).setIndeterminate(true);
  super.onPrepareDialog(id, dialog);
}
</code>```

EDIT: But maybe there is a way to get the ProgressBar itself and start it animating? so I tried the following after I asked this question:

```<code>@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
  if (id == DIALOG_PROGRESS_ID)
  {
     ProgressBar p = (ProgressBar) dialog.findViewById(android.R.id.progress);
     if (p.getAnimation() != null)
        p.startAnimation(p.getAnimation());
  }
  super.onPrepareDialog(id, dialog);
</code>```

}

But it didn't work either!

So, does anyone know if there is a way to restart animation on a ProgressDialog? If not, is there a way that I can force every showDialog() call to call onCreateDialog()? (this second question was answered by @TuomasR, but after pondering it I don't think this is a very good solution to my problem)

答:
Ha! Got it... was also struggling with this. But calling:

```<code>removeDialog(DIALOG_PROGRESS_ID)
</code>```

immediately after

```<code>dismissDialog(...)
</code>```

removes it from the (presumed) dialog cache for the Activity and forces a call to onCreateDialog. Create a new ProgressDialog in onCreateDialog and the spinner animates everytime (for me at least).

Body:
I create a ProgressDialog in onCreateDialog() like so:

protected Dialog onCreateDialog(int id) {
  if (id == DIALOG_PROGRESS_ID)
  {
      ProgressDialog dialog = new ProgressDialog(this);
      dialog.setMessage(getResources().getString(R.string.MyLabel));
      dialog.setCancelable(false);
      dialog.setIndeterminate(true);
      return dialog;
  }
}

Android, in its wisdom (or serious lack of it) decides to cache every dialog created through onCreateDialog(). Because of that, any subsequent call to showDialog(DIALOG_PROGRESS_ID) results in the same ProgressDialog instance being used but the animation has stopped working.

I've tried to re-set indeterminate in onPrepareDialog(), but that doesn't do anything. There is likewise no obvious method to call on the dialog instance that will reset the animation.

protected void onPrepareDialog(int id, Dialog dialog)
{
  //This doesn't do anything
  if (id == DIALOG_PROGRESS_ID)
     ((ProgressDialog)dialog).setIndeterminate(true);
  super.onPrepareDialog(id, dialog);
}

EDIT: But maybe there is a way to get the ProgressBar itself and start it animating? so I tried the following after I asked this question:

@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
  if (id == DIALOG_PROGRESS_ID)
  {
     ProgressBar p = (ProgressBar) dialog.findViewById(android.R.id.progress);
     if (p.getAnimation() != null)
        p.startAnimation(p.getAnimation());
  }
  super.onPrepareDialog(id, dialog);

}

But it didn't work either!

So, does anyone know if there is a way to restart animation on a ProgressDialog? If not, is there a way that I can force every showDialog() call to call onCreateDialog()? (this second question was answered by @TuomasR, but after pondering it I don't think this is a very good solution to my problem)

Body:
Ha! Got it... was also struggling with this. But calling:

removeDialog(DIALOG_PROGRESS_ID)

immediately after

dismissDialog(...)

removes it from the (presumed) dialog cache for the Activity and forces a call to onCreateDialog. Create a new ProgressDialog in onCreateDialog and the spinner animates everytime (for me at least).


问:
Knockout Observable array not being observed?
Let me start with a screencast of the current behaviour. As you can see, when I add a role for the user jbrown, the role doesn't show where it should!

But if I navigate away to another user, then back to jbrown, the role(s) does show!

Here is the ViewModel in question:

```<code>function UsersViewModel() {
  var self = this;
  // data with some removed for brevity
  self.isLoaded = ko.observable(false);
  self.selectedUser = ko.observable();
  self.SelectedUserHasRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.selectedUser().roles().length > 0;
    }
    return false;
  });

  self.UserHasAllAvailableRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.userAvailableRoles().length === 0;
    }
    return false;
  });

  // isLoaded gets set to true when AJAX call to server
  // is a success and data is returned

  // operations with some removed for brevity
  self.setCurrentUser = function (user) {
    const newRolesArray = self.roles().filter(function (role) {
      return !contains(user.roles(), role);
    });
    self.userAvailableRoles(newRolesArray);
    self.selectedUser(user);
  }

  self.addUser = function () {
    self.users.push(new User({ Username: this.newUsernameText() }));
    self.newUsernameText('');
    self.NewUserFormIsVisible(false);
    self.AddRolesFormIsVisible(true);
    self.setCurrentUser(self.users()[self.users().length - 1]);
  };

  self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    self.AddRolesFormIsVisible(false);
    $.post('http://localhost:23926/admin/acl/addusertorole', { username: self.selectedUser().name(), role: self.selectedRole().name() },
    function () {
      console.log('user role created at db!');
    },
    'json');
  }
}
</code>```

And here is the HTML markup in question:

```<code><!-- ko if: isLoaded -->
  <!-- ko if: SelectedUserHasRoles() -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: name()"></div>
  </div>
  <!-- /ko -->
<!-- /ko -->
</code>```

My Observable array of roles must be getting populated because as you saw, when I navigate away and back, I can see the roles I've added.

What am I missing?

答:
You're trying to push the new role to the underlying, untracked, array instead of the observable array.

```<code>self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    ...
}
</code>```

You just need to remove the set of parenthesis after "roles" so that it looks like:

```<code>self.selectedUser().roles.push(new Role({ Name: self.selectedRole().name() }));
</code>```

Body:
Let me start with a screencast of the current behaviour. As you can see, when I add a role for the user jbrown, the role doesn't show where it should!

But if I navigate away to another user, then back to jbrown, the role(s) does show!

Here is the ViewModel in question:

function UsersViewModel() {
  var self = this;
  // data with some removed for brevity
  self.isLoaded = ko.observable(false);
  self.selectedUser = ko.observable();
  self.SelectedUserHasRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.selectedUser().roles().length > 0;
    }
    return false;
  });

  self.UserHasAllAvailableRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.userAvailableRoles().length === 0;
    }
    return false;
  });

  // isLoaded gets set to true when AJAX call to server
  // is a success and data is returned

  // operations with some removed for brevity
  self.setCurrentUser = function (user) {
    const newRolesArray = self.roles().filter(function (role) {
      return !contains(user.roles(), role);
    });
    self.userAvailableRoles(newRolesArray);
    self.selectedUser(user);
  }

  self.addUser = function () {
    self.users.push(new User({ Username: this.newUsernameText() }));
    self.newUsernameText('');
    self.NewUserFormIsVisible(false);
    self.AddRolesFormIsVisible(true);
    self.setCurrentUser(self.users()[self.users().length - 1]);
  };

  self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    self.AddRolesFormIsVisible(false);
    $.post('http://localhost:23926/admin/acl/addusertorole', { username: self.selectedUser().name(), role: self.selectedRole().name() },
    function () {
      console.log('user role created at db!');
    },
    'json');
  }
}

And here is the HTML markup in question:

My Observable array of roles must be getting populated because as you saw, when I navigate away and back, I can see the roles I've added.

What am I missing?

Body:
You're trying to push the new role to the underlying, untracked, array instead of the observable array.

self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    ...
}

You just need to remove the set of parenthesis after "roles" so that it looks like:

self.selectedUser().roles.push(new Role({ Name: self.selectedRole().name() }));


答:
The problem is that Python compares tuples lexicographically so it orders on the first item and only if these are equivalent, it compares the second and so on.

You can however use the key= in the max(..) function, to compare on the second element:

```<code>max(zipped,<b>key=lambda x:x[1]</b>)</code>```

Note 1: Note that you do not have to construct a list(..) if you are only interested in the maximum value. You can use
  max(zip(neighbors,cv_scores),key=lambda x:x[1]).

Note 2: Finding the max(..) runs in O(n) (linear time) whereas sorting a list runs in O(n log n).

Title: Finding the max value of a list of tuples, (applying max to the second value of the tuple)

Body:
So I have a list of tuples which I created from zipping two lists like this:

zipped =list(zip(neighbors, cv_scores))

max(zipped) produces
    (49, 0.63941769316909292)    where 49 is the max value.

However, I'm interesting in finding the max value among the latter value of the tuple (the .63941).

How can I do that?

Body:
The problem is that Python compares tuples lexicographically so it orders on the first item and only if these are equivalent, it compares the second and so on.

You can however use the key= in the max(..) function, to compare on the second element:

max(zipped,key=lambda x:x[1])

Note 1: Note that you do not have to construct a list(..) if you are only interested in the maximum value. You can use
  max(zip(neighbors,cv_scores),key=lambda x:x[1]).

Note 2: Finding the max(..) runs in O(n) (linear time) whereas sorting a list runs in O(n log n).


答:
Instead of

```<code>self.selectedUser().roles().push(
</code>```

do

```<code>self.selectedUser().roles.push(
</code>```

That will use the ObservableArray member function push rather than the underlying array's push. The difference is that Knockout only notices the changes made through its member functions.

Title: Knockout Observable array not being observed?

Body:
Instead of

self.selectedUser().roles().push(

do

self.selectedUser().roles.push(

That will use the ObservableArray member function push rather than the underlying array's push. The difference is that Knockout only notices the changes made through its member functions.


问:
Date to weekday (internationalization) prefer returning numbers
How can I convert the date into weekday in numeric form?
Similar question here:Find the day of a week

When run on my computer, the out put look like this:

```<code>> weekdays.Date(as.Date("2016-12-31"))
[1] "星期六"
</code>```

But I am designing a program that will be dispatched to people from all over the world.

Same code run on different computer might give different result:

```<code>> weekdays.Date(as.Date("2016-12-31"))
[1] "Saturday"
</code>```

This makes the situation complicated if I need to consider putting a translation chunk in my code.

I wonder if there is a way that, when doing the conversion it returns weekdays in numbers. For instance, Monday is 1, Tuesday is 2 ..., Sunday is 7.

答:
From strptime help...

format(as.Date("2017-03-12"),"%u")

Body:
How can I convert the date into weekday in numeric form?
Similar question here:Find the day of a week

When run on my computer, the out put look like this:

> weekdays.Date(as.Date("2016-12-31"))
[1] "星期六"

But I am designing a program that will be dispatched to people from all over the world.

Same code run on different computer might give different result:

> weekdays.Date(as.Date("2016-12-31"))
[1] "Saturday"

This makes the situation complicated if I need to consider putting a translation chunk in my code.

I wonder if there is a way that, when doing the conversion it returns weekdays in numbers. For instance, Monday is 1, Tuesday is 2 ..., Sunday is 7.


问:
ASP.NET remove URLs from string (regex)
Already checked here: C# Remove URL from String and here and here Remove URLs from text string.

I tried the regular expression from the last post:

Regex.Replace(txt, "!\b(((ht|f)tp(s?))\://)?(www.|[a-z].)[a-z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-z0-9\.\,\;\?\\'\\\\\+&%\$#\=~_\-]+))*\b!i", "")

And I also tried the regex to which is referred:

^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$

But both do not remove the urls.

I want to remove all URLs from a string using VB. These URLs are not in an a tag.

Example string:

This is https://www.example.com/an-example-url and http://www.example.com/and-some-friendlyurl?utm_campaign=test&id=4.
.Themes.

Desired result:

This is and .
.Themes.

答:
Give this Regex a try...

```<code> (http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#]
</code>```

You can combine this with a Replace and remove the matches. If you do not want the matches removed you also have each section of that match you can do what you want with them.

This has been tested and can be tried here.

Title: ASP.NET remove URLs from string (regex)

Body:
Give this Regex a try...

 (http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#]

You can combine this with a Replace and remove the matches. If you do not want the matches removed you also have each section of that match you can do what you want with them.

This has been tested and can be tried here.


问:
How to have for loop that iterates through indexes as in objective-C (Swift)?
I am developing a Google Maps app and I have the following code:

```<code>func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for marker in markersArray {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}
</code>```

As you can see I would like to increment the index by one every time so all coordinates get inserted. How do I achieve this?

答:
```<code>    func drawPolygon(){
    var cord: Array<CLLocationCoordinate2D> = []
    let path = GMSMutablePath()
    // get path for polygon
//initailizing i = 0;
    var i = 0
    for marker in markersArray {
    let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
    let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
    path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
    path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
//incrementing i with +1
    i = i+1;
    }
    }
</code>```

Body:
I am developing a Google Maps app and I have the following code:

func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for marker in markersArray {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}

As you can see I would like to increment the index by one every time so all coordinates get inserted. How do I achieve this?


问:
Can't Read Registry Key
give the code below, lastuser string returns null, however, if I use regedit to look at this key it has data associated with it. Is LoggedOnSAMuser a restricted key?</p>

```<code>public static string lastlogon()
    {
        string lastuser;
        RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI",false);
        if (registryKey != null)
        {
            lastuser = (string) registryKey.GetValue("LastLoggedOnSAMUser");
        }
        else lastuser = "Unknown User";
        return (lastuser);
    }
</code>```

答:
This seems to work on Windows 7</p>

```<code>    RegistryKey thisKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
    RegistryKey thisSubkey = thisKey.OpenSubKey(@"SOFTWARE\\fred", false);
    _url = (string)thisSubkey.GetValue("_url", "*");
    _port = (string)thisSubkey.GetValue("_port", 0);
</code>```

Title: Can't Read Registry Key

Body:
give the code below, lastuser string returns null, however, if I use regedit to look at this key it has data associated with it. Is LoggedOnSAMuser a restricted key?

public static string lastlogon()
    {
        string lastuser;
        RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI",false);
        if (registryKey != null)
        {
            lastuser = (string) registryKey.GetValue("LastLoggedOnSAMUser");
        }
        else lastuser = "Unknown User";
        return (lastuser);
    }

Body:
This seems to work on Windows 7

    RegistryKey thisKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
    RegistryKey thisSubkey = thisKey.OpenSubKey(@"SOFTWARE\\fred", false);
    _url = (string)thisSubkey.GetValue("_url", "*");
    _port = (string)thisSubkey.GetValue("_port", 0);


问:
Observable and Angular2
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

```<code>delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}
</code>```

This is how interface looks like IDeliveryCountry:

```<code>export interface IDeliveryCountry {
  iso: string;
  name: string;
}
</code>```

This is how Service looks like:

```<code>_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}
</code>```

json file with data looks like this:

```<code>[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]
</code>```

My html file is just a simple ngFor loop:

```<code><div *ngFor='let dev of delivery'>{{dev.iso}}</div>
</code>```

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

```<code>{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}
</code>```

I want data to only have one country with iso and name property for it. So my html file looks like following:

```<code><div>{{delivery.iso}}</div>
</code>```

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

答:
You should first of all use:

```<code>{{delivery.country.iso}}
</code>```

The undefined error you are getting, is because the data is coming async, so use the safe navigation operator to avoid this:

```<code>{{delivery?.country?.iso}}
</code>```

Demo

Optionally you could extract the data that is inside country, so you can shorten your code in your template from {{delivery?.country?.iso}} to just {{delivery?.iso}}, this can be done like so:

```<code>.map(res => res.json().country) // extract the data from the object country
</code>```

Title: Observable and Angular2

Body:
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}

This is how interface looks like IDeliveryCountry:

export interface IDeliveryCountry {
  iso: string;
  name: string;
}

This is how Service looks like:

_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}

json file with data looks like this:

[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]

My html file is just a simple ngFor loop:

{{dev.iso}}

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}

I want data to only have one country with iso and name property for it. So my html file looks like following:

{{delivery.iso}}

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

Body:
You should first of all use:

{{delivery.country.iso}}

The undefined error you are getting, is because the data is coming async, so use the safe navigation operator to avoid this:

{{delivery?.country?.iso}}

Demo

Optionally you could extract the data that is inside country, so you can shorten your code in your template from {{delivery?.country?.iso}} to just {{delivery?.iso}}, this can be done like so:

.map(res => res.json().country) // extract the data from the object country


问:
Look for a property in List of object using Hamcrest matcher
I have a Java POJO.

```<code>public class Emp {
    private String name;
    private int id;
}
</code>```

I have a list of employees (target):

```<code> List<Emp> target = new ArrayList<Emap>();
 // Add emp object in list
 assertThat(target, containsInAnyOrder(????));
</code>```

In containsInAnyOrder, I have to use something like i.e. hasProperty("name" , is(equalTo("John")). I have to check for a specific property in the list for specific value so what should be the syntax. I did not find any example of "containsInAnyOrder" with List of objects.

答:
If your object-to-compare is always as simple as a Java Pojo, then maybe you can take a look of EqualsBuilder from Apache Commons Lang3. In particular, this method:

```<code>public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients)
</code>```

You can implement your own "equals" matcher which delegates the comparison to reflectionEquals.

To do that, you subclass the TypeSafeDiagnosingMatcher<T> class from Hamcrest.

```<code>class ReflectiveEqualsMatcher<T> extends TypeSafeDiagnosingMatcher<T> {

    private final T other;

    public ReflectiveEqualsMatcher(T divisor) {
        this.other = divisor;
    }

    @Override
    protected boolean matchesSafely(T me, Description description) {
        return EqualsBuilder.reflectionEquals(me, other, true);
    }

    @Override
    public void describeTo(Description description) {
    }

    public static <T> ReflectiveEqualsMatcher<T> same(T other) {
        return new ReflectiveEqualsMatcher(other);
    }
}
</code>```

To use it:

```<code>//static import ReflectiveEqualsMatcher.same first
assertThat(target, containsInAnyOrder(same(obj1), same(obj2), same(obj3)));
</code>```

Body:
I have a Java POJO.

public class Emp {
    private String name;
    private int id;
}

I have a list of employees (target):

 List<Emp> target = new ArrayList<Emap>();
 // Add emp object in list
 assertThat(target, containsInAnyOrder(????));

In containsInAnyOrder, I have to use something like i.e. hasProperty("name" , is(equalTo("John")). I have to check for a specific property in the list for specific value so what should be the syntax. I did not find any example of "containsInAnyOrder" with List of objects.

Body:
If your object-to-compare is always as simple as a Java Pojo, then maybe you can take a look of EqualsBuilder from Apache Commons Lang3. In particular, this method:

public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients)

You can implement your own "equals" matcher which delegates the comparison to reflectionEquals.

To do that, you subclass the TypeSafeDiagnosingMatcher<T> class from Hamcrest.

class ReflectiveEqualsMatcher<T> extends TypeSafeDiagnosingMatcher<T> {

    private final T other;

    public ReflectiveEqualsMatcher(T divisor) {
        this.other = divisor;
    }

    @Override
    protected boolean matchesSafely(T me, Description description) {
        return EqualsBuilder.reflectionEquals(me, other, true);
    }

    @Override
    public void describeTo(Description description) {
    }

    public static <T> ReflectiveEqualsMatcher<T> same(T other) {
        return new ReflectiveEqualsMatcher(other);
    }
}

To use it:

//static import ReflectiveEqualsMatcher.same first
assertThat(target, containsInAnyOrder(same(obj1), same(obj2), same(obj3)));