问:
Non-standard subsetting of data.frames
One of the quirks of subsetting a data frame is that you have to repeatedly type the name of that data frame when mentioning columns. For example, the data frame cars is mentioned 3 times here:

```<code>cars[cars$speed == 4 & cars$dist < 10, ]
##   speed dist
## 1     4    2
</code>```

The data.table package solves this.

```<code>library(data.table)
dt_cars <- as.data.table(cars)
dt_cars[speed == 4 & dist < 10]
</code>```

As does dplyr.

```<code>library(dplyr)
cars %>% filter(speed == 4, dist < 10)
</code>```

I'd like to know if a solution exists for standard-issue data.frames (that is, not resorting to data.table or dplyr).

I think I'm looking for something like

```<code>cars[MAGIC(speed == 4 & dist < 10), ]
</code>```

or

```<code>MAGIC(cars[speed == 4 & dist < 10, ])
</code>```

where MAGIC is to be determined.

I tried the following, but it gave me an error.

```<code>library(rlang)
cars[locally(speed == 4 & dist < 10), ]
# Error in locally(speed == 4 & dist < 10) : object 'speed' not found
</code>```

答:
subset is the base function which solves this problem. However, like all base R functions which use non-standard evaluation subset does not perform fully hygienic code expansion. So subset() evaluates the wrong variable when used within non-global scopes (such as in lapply loops).

As an example, here we define the variable var in two places, first in the global scope with value 40, then in a local scope with value 30. The use of local() here is for simplicity, however this would behave equivalently inside a function. Intuitively, we would expect subset to use the value 30 in the evaluation. However upon executing the following code we see instead the value 40 is used (so no rows are returned).

```<code>var <- 40

local({
  var <- 30
  dfs <- list(mtcars, mtcars)
  lapply(dfs, subset, mpg > var)
})

#> [[1]]
#>  [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
#> <0 rows> (or 0-length row.names)
#>
#> [[2]]
#>  [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
#> <0 rows> (or 0-length row.names)
</code>```

This happens because the parent.frame() used in subset() is the environment within the body of lapply() rather than the local block. Because all environments eventually inherit from the global environment the variable var is found there with value 40.

Hygienic variable expansion via quasiquotation (as implemented in the rlang package) solves this problem. We can define a variant of subset using tidy evaluation that works properly in all contexts. The code is derived from and largely identical to that of base::subset.data.frame().

```<code>subset2 <- function (x, subset, select, drop = FALSE, ...) {
  r <- if (missing(subset))
    rep_len(TRUE, nrow(x))
  else {
    r <- rlang::eval_tidy(rlang::enquo(subset), x)
    if (!is.logical(r))
      stop("'subset' must be logical")
    r & !is.na(r)
  }
  vars <- if (missing(select))
    TRUE
  else {
    nl <- as.list(seq_along(x))
    names(nl) <- names(x)
    rlang::eval_tidy(rlang::enquo(select), nl)
  }
  x[r, vars, drop = drop]
}
</code>```

This version of subset behaves identically to base::subset.data.frame().

```<code>subset2(mtcars, gear > 4, disp:wt)
#>                 disp  hp drat    wt
#> Porsche 914-2  120.3  91 4.43 2.140
#> Lotus Europa    95.1 113 3.77 1.513
#> Ford Pantera L 351.0 264 4.22 3.170
#> Ferrari Dino   145.0 175 3.62 2.770
#> Maserati Bora  301.0 335 3.54 3.570
</code>```

However subset2() does not suffer the scoping issues of subset. In our previous example the value 30 is used for var, as we would expect from lexical scoping rules.

```<code>local({
  var <- 30
  dfs <- list(mtcars, mtcars)
  lapply(dfs, subset2, mpg > var)
})

#> [[1]]
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
#> Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
#> Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
#> Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2
#>
#> [[2]]
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
#> Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
#> Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
#> Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2
</code>```

This allows non-standard evaluation to be used robustly in all contexts, not just in top level contexts as with previous approaches.

This makes functions which use non-standard evaluation much more useful. Before while they were nice to have for interactive use, you needed to use more verbose standard evaluation functions when writing functions and packages. Now the same function can be used in all contexts without needing to modify the code!

For more details on non-standard evaluation please see Lionel Henry's Tidy evaluation (hygienic fexprs) presentation, the rlang vignette on tidy evaluation and the programming with dplyr vignette.

Title: Non-standard subsetting of data.frames

Body:
One of the quirks of subsetting a data frame is that you have to repeatedly type the name of that data frame when mentioning columns. For example, the data frame cars is mentioned 3 times here:

cars[cars$speed == 4 & cars$dist < 10, ]
##   speed dist
## 1     4    2

The data.table package solves this.

library(data.table)
dt_cars <- as.data.table(cars)
dt_cars[speed == 4 & dist < 10]

As does dplyr.

library(dplyr)
cars %>% filter(speed == 4, dist < 10)

I'd like to know if a solution exists for standard-issue data.frames (that is, not resorting to data.table or dplyr).

I think I'm looking for something like

cars[MAGIC(speed == 4 & dist < 10), ]

or

MAGIC(cars[speed == 4 & dist < 10, ])

where MAGIC is to be determined.

I tried the following, but it gave me an error.

library(rlang)
cars[locally(speed == 4 & dist < 10), ]
# Error in locally(speed == 4 & dist < 10) : object 'speed' not found

Body:
subset is the base function which solves this problem. However, like all base R functions which use non-standard evaluation subset does not perform fully hygienic code expansion. So subset() evaluates the wrong variable when used within non-global scopes (such as in lapply loops).

As an example, here we define the variable var in two places, first in the global scope with value 40, then in a local scope with value 30. The use of local() here is for simplicity, however this would behave equivalently inside a function. Intuitively, we would expect subset to use the value 30 in the evaluation. However upon executing the following code we see instead the value 40 is used (so no rows are returned).

var <- 40

local({
  var <- 30
  dfs <- list(mtcars, mtcars)
  lapply(dfs, subset, mpg > var)
})

#> [[1]]
#>  [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
#> <0 rows> (or 0-length row.names)
#>
#> [[2]]
#>  [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
#> <0 rows> (or 0-length row.names)

This happens because the parent.frame() used in subset() is the environment within the body of lapply() rather than the local block. Because all environments eventually inherit from the global environment the variable var is found there with value 40.

Hygienic variable expansion via quasiquotation (as implemented in the rlang package) solves this problem. We can define a variant of subset using tidy evaluation that works properly in all contexts. The code is derived from and largely identical to that of base::subset.data.frame().

subset2 <- function (x, subset, select, drop = FALSE, ...) {
  r <- if (missing(subset))
    rep_len(TRUE, nrow(x))
  else {
    r <- rlang::eval_tidy(rlang::enquo(subset), x)
    if (!is.logical(r))
      stop("'subset' must be logical")
    r & !is.na(r)
  }
  vars <- if (missing(select))
    TRUE
  else {
    nl <- as.list(seq_along(x))
    names(nl) <- names(x)
    rlang::eval_tidy(rlang::enquo(select), nl)
  }
  x[r, vars, drop = drop]
}

This version of subset behaves identically to base::subset.data.frame().

subset2(mtcars, gear > 4, disp:wt)
#>                 disp  hp drat    wt
#> Porsche 914-2  120.3  91 4.43 2.140
#> Lotus Europa    95.1 113 3.77 1.513
#> Ford Pantera L 351.0 264 4.22 3.170
#> Ferrari Dino   145.0 175 3.62 2.770
#> Maserati Bora  301.0 335 3.54 3.570

However subset2() does not suffer the scoping issues of subset. In our previous example the value 30 is used for var, as we would expect from lexical scoping rules.

local({
  var <- 30
  dfs <- list(mtcars, mtcars)
  lapply(dfs, subset2, mpg > var)
})

#> [[1]]
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
#> Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
#> Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
#> Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2
#>
#> [[2]]
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
#> Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
#> Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
#> Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

This allows non-standard evaluation to be used robustly in all contexts, not just in top level contexts as with previous approaches.

This makes functions which use non-standard evaluation much more useful. Before while they were nice to have for interactive use, you needed to use more verbose standard evaluation functions when writing functions and packages. Now the same function can be used in all contexts without needing to modify the code!

For more details on non-standard evaluation please see Lionel Henry's Tidy evaluation (hygienic fexprs) presentation, the rlang vignette on tidy evaluation and the programming with dplyr vignette.


来源: stackexchange

问:
What is equivalent in php of ASP Response.Expires=0
I have this code in an ASP file:

```<code><%@ Language=VBScript %>
<%
    Option Explicit
    Response.Expires = 0
%>
</code>```

My question, what is the equivalent in PHP of the Response.Expires=0?

Thanks for the answers in advance.
Sz.

答:
Remember to use your preferred search engine to find an answer :)

The "equivalent" in php would be session_cache_expire:

```<code>int session_cache_expire ([ string $new_cache_expire ] )
</code>```

Here is the documentation: http://php.net/manual/en/function.session-cache-expire.php

ContentLicense: CC BY-SA 3.0

Body:
I have this code in an ASP file:

<%@ Language=VBScript %>
<%
    Option Explicit
    Response.Expires = 0
%>

My question, what is the equivalent in PHP of the Response.Expires=0?

Thanks for the answers in advance.
Sz.

Body:
Remember to use your preferred search engine to find an answer :)

The "equivalent" in php would be session_cache_expire:

int session_cache_expire ([ string $new_cache_expire ] )

Here is the documentation: http://php.net/manual/en/function.session-cache-expire.php


问:
How do I get the ScreenSize programmatically in android
Android defines screen sizes as Normal Large XLarge etc.

It automatically picks between static resources in appropriate folders. I need this data about the current device in my java code. The DisplayMetrics only gives information about the current device density. Nothing is available regarding screen size.

I did find the ScreenSize enum in grep code here
However this does not seem available to me for 4.0 SDK. Is there a way to get this information?

答:
If you are in a non-activity i.e. Fragment, Adapter, Model class or any other java class that do not extends Activity simply getResources() will not work. You can use getActivity() in fragment or use context that you pass to the corresponding class.

```<code>mContext.getResources()
</code>```

I would recommend making a class say Utils that will have method/Methods for the common work. The benefit for this is you can get desired result with single line of code anywhere in the app calling this method.

Body:
If you are in a non-activity i.e. Fragment, Adapter, Model class or any other java class that do not extends Activity simply getResources() will not work. You can use getActivity() in fragment or use context that you pass to the corresponding class.

mContext.getResources()

I would recommend making a class say Utils that will have method/Methods for the common work. The benefit for this is you can get desired result with single line of code anywhere in the app calling this method.


问:
Rebuilding an ICollection after MVC edit?
If my model Product has a member ICollection<ProductOption> how do I rebuild my Product with the member collection in my Controller.Edit(...) method on post back from Edit?

(We can assume we never add or remove an option, only ever edit.)

Razor:

```<code>@model Models.Products.Product
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_GlobalLayout.cshtml";
}

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
    @Html.HiddenFor(model => model.Id)
    <legend>Product</legend>
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    @foreach (ProductOption option in Model.Options)
    {
        <div style="border:1px solid black; margin: 5px; padding:5px 7px;">
            @Html.Partial("_ProductOptionInput", option)
        </div>
    }
    <p>
        <input type="submit" value="Save" />
    </p>
    </fieldset>
}
</code>```

controller:

```<code>[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    var p = _repository.ById(id);
    UpdateModel<Product>(p);

    _repository.SaveChanges();

    return RedirectToAction("Index");
}
</code>```

partial view:

```<code>@modelModels.Products.ProductOption

@Html.ValidationSummary(true)
<fieldset>
    <legend>ProductOption</legend>
    @Html.HiddenFor(model => model.Id)
    <div class="editor-label">
        @Html.LabelFor(model => model.Term)
    </div>
</fieldset>
</code>```

UPDATE

My FormCollection in ActionResult Edit(int id, FormCollection collection) is essentially a dictionary, so it has the ProductOption values for one of the updated ProductOptions but not the rest of them as the keys (ie the ProductOptions property names) can't be repeated in the dictionary.

答:
I added the following in the Razor view and it works like a charm!</p>

```<code>@Html.EditorFor(model => model.Options.ToList()[0], templateName: "ProductOptionInput", htmlFieldName: "Options[0]")
@Html.EditorFor(model => model.Options.ToList()[1], templateName: "ProductOptionInput", htmlFieldName: "Options[1]")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If my model Product has a member ICollection<ProductOption> how do I rebuild my Product with the member collection in my Controller.Edit(...) method on post back from Edit?

(We can assume we never add or remove an option, only ever edit.)

Razor:

@model Models.Products.Product
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_GlobalLayout.cshtml";
}

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
    @Html.HiddenFor(model => model.Id)
    <legend>Product</legend>

        @Html.LabelFor(model => model.Name)

    @foreach (ProductOption option in Model.Options)
    {

            @Html.Partial("_ProductOptionInput", option)

    }

        <input type="submit" value="Save" />

    </fieldset>
}

controller:

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    var p = _repository.ById(id);
    UpdateModel<Product>(p);

    _repository.SaveChanges();

    return RedirectToAction("Index");
}

partial view:

@modelModels.Products.ProductOption

@Html.ValidationSummary(true)
<fieldset>
    <legend>ProductOption</legend>
    @Html.HiddenFor(model => model.Id)

        @Html.LabelFor(model => model.Term)

</fieldset>

UPDATE

My FormCollection in ActionResult Edit(int id, FormCollection collection) is essentially a dictionary, so it has the ProductOption values for one of the updated ProductOptions but not the rest of them as the keys (ie the ProductOptions property names) can't be repeated in the dictionary.

Body:
I added the following in the Razor view and it works like a charm!

@Html.EditorFor(model => model.Options.ToList()[0], templateName: "ProductOptionInput", htmlFieldName: "Options[0]")
@Html.EditorFor(model => model.Options.ToList()[1], templateName: "ProductOptionInput", htmlFieldName: "Options[1]")


问:
Angular 4 option selected by default in template
I want to have an option selected by default but it only works if I remove the NgModel directive from the select.

```<code><select id="privileges" name="privileges" class="form-control" [(ngModel)]="value" required>
   <option [selected]="(user | async).privileges == Administrador" value="Administrador">Administrador</option>
   <option value="Empleado">Empleado</option>
</select>
</code>```

If I remove the ngmodel directive if it works perfectly but obviously it's not what I need.

答:
[selected]="..." doesn't work with ngModel.

To select a value, assign the value to your value field.
Angular will make the option the selected, where value="..." is equal to the value assigned to the value field used in [(ngModel)]="value".

If the used value is not a string, use [ngValue]="..." instead of [value]="..." or value="{{...}}".

Body:
I want to have an option selected by default but it only works if I remove the NgModel directive from the select.

<select id="privileges" name="privileges" class="form-control" [(ngModel)]="value" required>
   <option [selected]="(user | async).privileges == Administrador" value="Administrador">Administrador</option>
   <option value="Empleado">Empleado</option>
</select>

If I remove the ngmodel directive if it works perfectly but obviously it's not what I need.


问:
OdbcParameter error - size of 0 for varchar(MAX) output parameter
I'm using:

Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
  Dec 28 2012 20:23:12

  Copyright (c) Microsoft Corporation   Enterprise Edition (64-bit) on Windows NT 6.2  (Build 9200: ) (Hypervisor)

I have a stored procedure which has a varchar(MAX) output parameter.

I'm calling it via an OdbcCommand and I've created a VarChar output parameter and added it to the OdbcCommand Parameters list:

```<code>new OdbcParameter("@MaxField", OdbcType.VarChar)
    { Direction = ParameterDirection.Output, Size = -1 })
</code>```

While debugging I can see that the Size field on the parameter is still -1 but when I run the query using OdbcCommand.ExecuteNonQuery() I get the following exception:

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=String[2]: the Size property has an invalid size of 0.

  Source=System.Data

  StackTrace:

         at System.Data.Odbc.OdbcParameter.GetParameterSize(Object value, Int32 offset, Int32 ordinal)

         at System.Data.Odbc.OdbcParameter.PrepareForBind(OdbcCommand command, Int16 ordinal, Int32& parameterBufferSize)

         at System.Data.Odbc.OdbcParameterCollection.CalcParameterBufferSize(OdbcCommand
  command)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

I tried using the OdbcCommandBuilder.DeriveParameters(odbcCommand); to examine the parameter information derived from the stored procedure and it said that the parameter had a Size of 2147483647 - however, if I try and use that value I get a different exception telling me

System.Data.Odbc.OdbcException was unhandled

  ErrorCode=-2146232009

  HResult=-2146232009

  Message=ERROR [42000] [Microsoft][ODBC SQLServer Driver][SQL Server]Invalid parameter 2 (''):  Data type 0x23 is
  a deprecated large object, or LOB, but is marked as output parameter.
  Deprecated types are not supported as output parameters.  Use current
  large object types instead.   Source=SQLSRV32.DLL   StackTrace:

         at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

How should I configure my OdbcCommand output parameter to receive this output from the stored procedure?

This is on an existing, in-production database so trying to change the datatype of the field is sadly the absolute last resort. The field that is being selected is varchar(max).

Edit: If the actual answer is "You just can't" then that would be acceptable - at least I would know for sure.

答:
varchar(max) was introduced in SQL Server 2005 to replace the text type. When the value is less than 8000, it is stored on page like a standard varchar(n), while values above 8000 are stored off page like text.

The use of text or varcha(max) as a parameter is not recommended, and as the message is telling you, it is even not supported for output parameters:

Data type 0x23 is a deprecated large object, or LOB, but is marked as output parameter. Deprecated types are not supported as output parameters. Use current large object types instead.

The best solution is to fix the stored procedure and change the output parameter from varchar(max) to varchar(n). Otherwise, you can use varchar(8000) in your code for the parameter and hope that the stored procedure will never return a value more than 8000. The value 8000 is the maximum for the varchar(n) type.

Also, you may get around it by using a different (older) version of the ODBC driver that doesn't complain about the use of varchar(max) as an output paramter, but that obviously is not the best way to go.

Body:
I'm using:

Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
  Dec 28 2012 20:23:12

  Copyright (c) Microsoft Corporation   Enterprise Edition (64-bit) on Windows NT 6.2  (Build 9200: ) (Hypervisor)

I have a stored procedure which has a varchar(MAX) output parameter.

I'm calling it via an OdbcCommand and I've created a VarChar output parameter and added it to the OdbcCommand Parameters list:

new OdbcParameter("@MaxField", OdbcType.VarChar)
    { Direction = ParameterDirection.Output, Size = -1 })

While debugging I can see that the Size field on the parameter is still -1 but when I run the query using OdbcCommand.ExecuteNonQuery() I get the following exception:

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=String[2]: the Size property has an invalid size of 0.

  Source=System.Data

  StackTrace:

         at System.Data.Odbc.OdbcParameter.GetParameterSize(Object value, Int32 offset, Int32 ordinal)

         at System.Data.Odbc.OdbcParameter.PrepareForBind(OdbcCommand command, Int16 ordinal, Int32& parameterBufferSize)

         at System.Data.Odbc.OdbcParameterCollection.CalcParameterBufferSize(OdbcCommand
  command)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

I tried using the OdbcCommandBuilder.DeriveParameters(odbcCommand); to examine the parameter information derived from the stored procedure and it said that the parameter had a Size of 2147483647 - however, if I try and use that value I get a different exception telling me

System.Data.Odbc.OdbcException was unhandled

  ErrorCode=-2146232009

  HResult=-2146232009

  Message=ERROR [42000] [Microsoft][ODBC SQLServer Driver][SQL Server]Invalid parameter 2 (''):  Data type 0x23 is
  a deprecated large object, or LOB, but is marked as output parameter.
  Deprecated types are not supported as output parameters.  Use current
  large object types instead.   Source=SQLSRV32.DLL   StackTrace:

         at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

How should I configure my OdbcCommand output parameter to receive this output from the stored procedure?

This is on an existing, in-production database so trying to change the datatype of the field is sadly the absolute last resort. The field that is being selected is varchar(max).

Edit: If the actual answer is "You just can't" then that would be acceptable - at least I would know for sure.


问:
How to prevent "0" as the first character and limit number of characters allowed in UITextField using Swift?
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}
</code>```

Thank you for your time.

答:
You can use regex that define a number with <= 10 digits and not starting with 0, then use NSPredicate or NSRegularExpression to validate the entered text. Something like this:</p>

```<code>func isAllowed(str: String?) -> Bool {
    let regexPattern: String = "^((?!(0))[0-9]{0,10})$"
    let predicate = NSPredicate(format:"SELF MATCHES %@", regexPattern)

    return predicate.evaluate(with: str)
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return isAllowed(str: textField.text)
}
</code>```

Body:
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}

Thank you for your time.

Body:
You can use regex that define a number with <= 10 digits and not starting with 0, then use NSPredicate or NSRegularExpression to validate the entered text. Something like this:

func isAllowed(str: String?) -> Bool {
    let regexPattern: String = "^((?!(0))[0-9]{0,10})$"
    let predicate = NSPredicate(format:"SELF MATCHES %@", regexPattern)

    return predicate.evaluate(with: str)
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return isAllowed(str: textField.text)
}


问:
Python: define color curve section
I am trying to replicate the following figure:

The color gradient goes from blue to red and indicates the state of a material. I can currently plot each curve. Each line is defined by two points, and is then simply plotted using pyplot (matplotlib library). I also have a clear idea on how to compute the associated value.

However, it can be noticed, for example for point 9 or 22 on the first figure, that the value is different at the overlapping area. I have currently no clue on how to do that effectively.

The only idea I have comes from this solution. Basically, I have to turn each curve section into a polygon. But it looks very heavy, and prehaps not the best solution in this case.

I am mainly asking for leads that could help me to achieve this, or just a smarter way to look at the problem !

The code that produced this figure:

```<code>import shelve
import matplotlib.pyplot as plt
import os

path = "C:/Users/***/Desktop/Python/PyHugo/"
d = shelve.open(os.path.join(path, 'output.db'))
pointMat = d ['curve']
d.close()

fig=plt.figure()
ax=fig.add_subplot(111)

for matID in pointMat.keys():
    for couple in range(len(pointMat[matID])-1):
        plt.plot([pointMat[matID][couple][0][0],pointMat[matID][couple][1][0]],[pointMat[matID][couple][0][1],pointMat[matID][couple][1][1]])

plt.show()
</code>```

Points are stored in the pointMat dictionnary. Each area has a set of points. An area is a specific material. It is represented on figure one by le black line (around 540). So in the current example there are 2 materials.

The, the first set of points is given by:

```<code>print matPoint[0][0]
</code>```

results : [[20, 20], [0, 40]]. We asked for the first couple of point in the first material.

Edit 1: code added, off-topic question removed

EDIT 2: Instead of plotting the curves, I am mapping the values over a grid (discretisation of the phenomena). The problem has too many variations, and this seemed a better idea. Thank you for the time spend trying to help me !

答:
You need to make your lines semi-transparent using the alpha parameter:

```<code>plt.plot([pointMat[matID][couple][0][0],
         [pointMat[matID][couple][1][0]],
         [pointMat[matID][couple][0][1],
         [pointMat[matID][couple][1][1]],
         alpha=0.7)
</code>```

as an example.

Title: Python: define color curve section

Body:
I am trying to replicate the following figure:

The color gradient goes from blue to red and indicates the state of a material. I can currently plot each curve. Each line is defined by two points, and is then simply plotted using pyplot (matplotlib library). I also have a clear idea on how to compute the associated value.

However, it can be noticed, for example for point 9 or 22 on the first figure, that the value is different at the overlapping area. I have currently no clue on how to do that effectively.

The only idea I have comes from this solution. Basically, I have to turn each curve section into a polygon. But it looks very heavy, and prehaps not the best solution in this case.

I am mainly asking for leads that could help me to achieve this, or just a smarter way to look at the problem !

The code that produced this figure:

import shelve
import matplotlib.pyplot as plt
import os

path = "C:/Users/***/Desktop/Python/PyHugo/"
d = shelve.open(os.path.join(path, 'output.db'))
pointMat = d ['curve']
d.close()

fig=plt.figure()
ax=fig.add_subplot(111)

for matID in pointMat.keys():
    for couple in range(len(pointMat[matID])-1):
        plt.plot([pointMat[matID][couple][0][0],pointMat[matID][couple][1][0]],[pointMat[matID][couple][0][1],pointMat[matID][couple][1][1]])

plt.show()

Points are stored in the pointMat dictionnary. Each area has a set of points. An area is a specific material. It is represented on figure one by le black line (around 540). So in the current example there are 2 materials.

The, the first set of points is given by:

print matPoint[0][0]

results : [[20, 20], [0, 40]]. We asked for the first couple of point in the first material.

Edit 1: code added, off-topic question removed

EDIT 2: Instead of plotting the curves, I am mapping the values over a grid (discretisation of the phenomena). The problem has too many variations, and this seemed a better idea. Thank you for the time spend trying to help me !

Body:
You need to make your lines semi-transparent using the alpha parameter:

plt.plot([pointMat[matID][couple][0][0],
         [pointMat[matID][couple][1][0]],
         [pointMat[matID][couple][0][1],
         [pointMat[matID][couple][1][1]],
         alpha=0.7)

as an example.


问:
Select statement returns 0 rows : impossible
I need a quick help on this one, thanks!

I'm trying to check if a member exists in the database with this code:

public boolean memberExists(int id) {
   try {
      open();
      PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM client WHERE id = ?");
      pstmt.setInt(1,id);
      boolean _res = pstmt.executeQuery().getRow() > 0;
      close();
      return _res;
    }
    catch (SQLException e){ System.out.print(e); }
       return false;
    }
}
```

<p>The method <code>open()</code> gets a new connection and the <code>close()</code> method closes the connection. Pretty straightforward.</p>

<p>The thing that drives me nuts is that it always returns <strong>0 rows</strong>. Even the query <code>SELECT * FROM client</code> returns <strong>0 rows</strong>.</p>

<p>I used <em>sqlitebrowser.exe</em> to inspect my database and the exact same queries returns <strong>the right number of rows</strong>.</p>

<hr>

<p>I think that I already ran into this problem before, but I don't remember what it was exactly. I feel like I'm missing something.</p>

<hr>

<p>Also, in my code, I can <strong>INSERT INTO</strong> the database, but not <strong>SELECT</strong>. This is really strange.</p>

<hr>

<blockquote>
  <p>The <code>open()</code> method.</p>
</blockquote>

<pre class="lang-java prettyprint-override"><code>public DBConnector open() {
    boolean _exists = new File(path).exists();
    try {
        conn = DriverManager.getConnection("jdbc:sqlite:" + path);
        if (!_exists) create();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return this;
}
</code>```

答:
From ResultSet.getRow()  :

Returns: the current row number; 0 if there is no current row

This is the current row number, not the number of rows in the resultset.

You have several ways to get the row count, see :

How do I get the size of a java.sql.ResultSet ?

Body:
I need a quick help on this one, thanks!

I'm trying to check if a member exists in the database with this code:

public boolean memberExists(int id) {
   try {
      open();
      PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM client WHERE id = ?");
      pstmt.setInt(1,id);
      boolean _res = pstmt.executeQuery().getRow() > 0;
      close();
      return _res;
    }
    catch (SQLException e){ System.out.print(e); }
       return false;
    }
}

The method open() gets a new connection and the close() method closes the connection. Pretty straightforward.

The thing that drives me nuts is that it always returns 0 rows. Even the query SELECT * FROM client returns 0 rows.

I used sqlitebrowser.exe to inspect my database and the exact same queries returns the right number of rows.

I think that I already ran into this problem before, but I don't remember what it was exactly. I feel like I'm missing something.

Also, in my code, I can INSERT INTO the database, but not SELECT. This is really strange.

The open() method.

public DBConnector open() {
    boolean _exists = new File(path).exists();
    try {
        conn = DriverManager.getConnection("jdbc:sqlite:" + path);
        if (!_exists) create();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return this;
}


问:
Injecting Generic type parameters with AutoFac
I think I am really confused about what I can do with AutoFac, can someone please put me on track.

I have a base type

```<code>class PersonBase{
    public string SaySomething(){
       return "I am base";
    }
}
</code>```

I derive two concrete classes

```<code>class FakePerson : PersonBase{
    public override string SaySomething(){
       return "I'm so Fake";
    }
}

class RealPerson : PersonBase{
    public override string SaySomething(){
       return "I am For Real";
    }
}
</code>```

Create a generic class, PersonHandler, to deal with different types of people and would like the PersonHandler to instantiate the person at the appropriate time, so I do not want an instance of Person injected, just need to derived type

```<code>class PersonHandler<T>
    where T : PersonBase, new() {

    T _Person;

    public DoWork(){
        _Person = new T();
        _Person.SaySomething();
    }
}
</code>```

Now I try to use the handler, after registering the types as detailed next, with varying results.

```<code>var ph = contrainer.Resolve<PersonHandler<PersonBase>>();
ph.DoWork();
</code>```

I attempted to register the types as follows

```<code>1. vBuilder.RegisterType<PersonHandler<FakePerson>>().As<PersonHandler<PersonBase>>();
</code>```

This gives me an error stating the PersonHandler<FakePerson> is not assignable to PersonHandler<PersonBase> (or the other way around I don't recal which)

```<code>2. vBuilder.RegisterGeneric<typeof(PersonHandler<>)>
   vBuilder.RegisterType<FakePerson>().As<PersonBase>();
</code>```

This does not resolve PersonBase to FakePerson, but just gives PersonHandler<PersonBase>, So it results in "I am Base"

```<code>3. vBuilder.RegisterGeneric(typeof(PersonHandler<FakePerson>)).As(typeof(PersonHandler<PersonBase>));
</code>```

This given an error saying that PersonHandler<FakePerson> is not an open type

So now I have been chasing my tale all day and, frankly, it is getting quit tedious,

PLEASE HELP

答:
When you resolve a service that is registered with an open generic type (such as PersonHandler<>) you need to specify the exact closed type that you want to handle, and Autofac will generate one for you.

In this case, you called container.Resolve<PersonHandler<PersonBase>>() so you were returned a PersonHandler<PersonBase>. Now, if you look at your PersonHandler class, and substitute PersonBase for T, the resulting DoWork method looks like this:

```<code>public DoWork(){
    _Person = new PersonBase();
    _Person.SaySomething();
}
</code>```

So the SaySomething() call uses the method on the base class.

I'm not sure exactly what you are trying to do, but it looks like you want to decide which concrete PersonBase implementation to use during registration. If this is the case, you might try using the Delegate Factory feature of Autofac instead:

```<code>class PersonHandler
{
    private readonly Func<PersonBase> createPerson;

    public PersonHandler(Func<PersonBase> createPerson)
    {
        this.createPerson = createPerson;
    }

    public void DoWork()
    {
        PersonBase pb = this.createPerson();
        Console.WriteLine(pb.SaySomething());
    }
}
</code>```

Then you can register your classes as follows:

```<code>ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<RealPerson>().As<PersonBase>();
builder.RegisterType<PersonHandler>();
var context = builder.Build();
var handler = context.Resolve<PersonHandler>();
handler.DoWork();
</code>```

By varying the second line of this code, you can register whichever type of PersonBase you actually want to use in the program.

Body:
I think I am really confused about what I can do with AutoFac, can someone please put me on track.

I have a base type

class PersonBase{
    public string SaySomething(){
       return "I am base";
    }
}

I derive two concrete classes

class FakePerson : PersonBase{
    public override string SaySomething(){
       return "I'm so Fake";
    }
}

class RealPerson : PersonBase{
    public override string SaySomething(){
       return "I am For Real";
    }
}

Create a generic class, PersonHandler, to deal with different types of people and would like the PersonHandler to instantiate the person at the appropriate time, so I do not want an instance of Person injected, just need to derived type

class PersonHandler<T>
    where T : PersonBase, new() {

    T _Person;

    public DoWork(){
        _Person = new T();
        _Person.SaySomething();
    }
}

Now I try to use the handler, after registering the types as detailed next, with varying results.

var ph = contrainer.Resolve<PersonHandler<PersonBase>>();
ph.DoWork();

I attempted to register the types as follows

1. vBuilder.RegisterType<PersonHandler<FakePerson>>().As<PersonHandler<PersonBase>>();

This gives me an error stating the PersonHandler<FakePerson> is not assignable to PersonHandler<PersonBase> (or the other way around I don't recal which)

2. vBuilder.RegisterGeneric<typeof(PersonHandler<>)>
   vBuilder.RegisterType<FakePerson>().As<PersonBase>();

This does not resolve PersonBase to FakePerson, but just gives PersonHandler<PersonBase>, So it results in "I am Base"

3. vBuilder.RegisterGeneric(typeof(PersonHandler<FakePerson>)).As(typeof(PersonHandler<PersonBase>));

This given an error saying that PersonHandler<FakePerson> is not an open type

So now I have been chasing my tale all day and, frankly, it is getting quit tedious,

PLEASE HELP

Body:
When you resolve a service that is registered with an open generic type (such as PersonHandler<>) you need to specify the exact closed type that you want to handle, and Autofac will generate one for you.

In this case, you called container.Resolve<PersonHandler<PersonBase>>() so you were returned a PersonHandler<PersonBase>. Now, if you look at your PersonHandler class, and substitute PersonBase for T, the resulting DoWork method looks like this:

public DoWork(){
    _Person = new PersonBase();
    _Person.SaySomething();
}

So the SaySomething() call uses the method on the base class.

I'm not sure exactly what you are trying to do, but it looks like you want to decide which concrete PersonBase implementation to use during registration. If this is the case, you might try using the Delegate Factory feature of Autofac instead:

class PersonHandler
{
    private readonly Func<PersonBase> createPerson;

    public PersonHandler(Func<PersonBase> createPerson)
    {
        this.createPerson = createPerson;
    }

    public void DoWork()
    {
        PersonBase pb = this.createPerson();
        Console.WriteLine(pb.SaySomething());
    }
}

Then you can register your classes as follows:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<RealPerson>().As<PersonBase>();
builder.RegisterType<PersonHandler>();
var context = builder.Build();
var handler = context.Resolve<PersonHandler>();
handler.DoWork();

By varying the second line of this code, you can register whichever type of PersonBase you actually want to use in the program.


问:
Base64 decode and uncompress a string
I have a String which is first zipped (not gzip) and then base64 encoded.
I want to have the plain text again. Following code

```<code>private void decode_decompress(String string) {
    byte[] decodedBytes = Base64.decodeBase64(string.getBytes());
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(true);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
    try {
        inflaterOutputStream.write(decodedBytes);
        inflaterOutputStream.close();
        byte[] output2 = stream.toByteArray();
        logger.info("Data: {}", output2.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

throws an exception:

```<code>java.util.zip.ZipException: invalid stored block lengths
        at java.util.zip.InflaterOutputStream.write(InflaterOutputStream.java:273)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:97)
        at de.martinm.tools.EBICS.DSTools.decode_decompress(DSTools.java:87)
        at de.martinm.tools.EBICS.DSTools.process(DSTools.java:77)
        at de.martinm.tools.EBICS.DSTools.main(DSTools.java:100)
</code>```

I guess, I'm mixing up again input/output inflate/deflate

Here is the data which is compressed and base64 encoded:

eJx1U2tzqjAQ/SsO96NTw1PBQTr4qlgtyqvVL3cihEehiSYg1l9/rd46dZx+y549Ocme3dUfDx9FY48oywjucUKL5xoIhyTKcNLjfG/8oHINVkIcwYJg1OMw4R4N3c0SDMuKokW1eUafNo0QHcISNk5qmPW4tCy3XQDqum6hTRayFqEJcHle4C6MbnRLqqUzQ+R5HvAaOHEiliV/vtlnjR5XUdw90S5hd8Lz8jfhwLJf9ATwNp+5YYo+4EOGvyoJ0ekWy7rsDM5ICMtz7b/+uXH/Ljgf/7JvG1oHFnF3tlg4JoZ+OQewqJChR6zruOZNPCdRVVTMMOebJcxHZRJ1kqeDJJqfR6IQJDdngt1cBt5ncYKnO8d99Tp9gYoweT2O40BUatURhWKZvVHV7E8102XHXTDN5ZI1vZyX6KKeSm+SmK9VlQZ5nZeKvd8X7aPUmRztxdp8rtaZom1kJlsRqsK95RSS7RJ7AYOQbg6S2vZXrjWA6S5vqzlWYCG/z947YgXjcOasFuF8/JKs34nngCGYIVBukJd9jLHftuQSmfV6LJFg2CQrU5Ze4qJYpR1/b5qD2MaOvSv27Z1PV4GA+p1U1IDFWLJaifGEKmGKxZ3lq5Ox0EHb1G++JvGIpaSayxYd9J2kfO7nhXiw4XYYD3fyJsbC8kmDVv2iJZqqaAtnn/d08MPkL8NHh+1plHFpmEtzcM5ekXN00yBw075rg4PLxhgmz7d1cAf/gG5GAdISI2oNjVHfGried5K/QrrPfqYUHfwH7sSu62b8A39iR+Y=

答:
This solved the issue:</p>

```<code>private void decode_decompress(String string) {
    byte[] decodedBytes = Base64.decodeBase64(string);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(false);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
    try {
        inflaterOutputStream.write(decodedBytes);
        inflaterOutputStream.close();
        String data = stream.toString();
        logger.info("Data: {}", data);
    } catch (IOException e) {
        logger.error(string, e);
    }
}
</code>```

Title: Base64 decode and uncompress a string

Body:
I have a String which is first zipped (not gzip) and then base64 encoded.
I want to have the plain text again. Following code

private void decode_decompress(String string) {
    byte[] decodedBytes = Base64.decodeBase64(string.getBytes());
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(true);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
    try {
        inflaterOutputStream.write(decodedBytes);
        inflaterOutputStream.close();
        byte[] output2 = stream.toByteArray();
        logger.info("Data: {}", output2.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

throws an exception:

java.util.zip.ZipException: invalid stored block lengths
        at java.util.zip.InflaterOutputStream.write(InflaterOutputStream.java:273)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:97)
        at de.martinm.tools.EBICS.DSTools.decode_decompress(DSTools.java:87)
        at de.martinm.tools.EBICS.DSTools.process(DSTools.java:77)
        at de.martinm.tools.EBICS.DSTools.main(DSTools.java:100)

I guess, I'm mixing up again input/output inflate/deflate

Here is the data which is compressed and base64 encoded:

eJx1U2tzqjAQ/SsO96NTw1PBQTr4qlgtyqvVL3cihEehiSYg1l9/rd46dZx+y549Ocme3dUfDx9FY48oywjucUKL5xoIhyTKcNLjfG/8oHINVkIcwYJg1OMw4R4N3c0SDMuKokW1eUafNo0QHcISNk5qmPW4tCy3XQDqum6hTRayFqEJcHle4C6MbnRLqqUzQ+R5HvAaOHEiliV/vtlnjR5XUdw90S5hd8Lz8jfhwLJf9ATwNp+5YYo+4EOGvyoJ0ekWy7rsDM5ICMtz7b/+uXH/Ljgf/7JvG1oHFnF3tlg4JoZ+OQewqJChR6zruOZNPCdRVVTMMOebJcxHZRJ1kqeDJJqfR6IQJDdngt1cBt5ncYKnO8d99Tp9gYoweT2O40BUatURhWKZvVHV7E8102XHXTDN5ZI1vZyX6KKeSm+SmK9VlQZ5nZeKvd8X7aPUmRztxdp8rtaZom1kJlsRqsK95RSS7RJ7AYOQbg6S2vZXrjWA6S5vqzlWYCG/z947YgXjcOasFuF8/JKs34nngCGYIVBukJd9jLHftuQSmfV6LJFg2CQrU5Ze4qJYpR1/b5qD2MaOvSv27Z1PV4GA+p1U1IDFWLJaifGEKmGKxZ3lq5Ox0EHb1G++JvGIpaSayxYd9J2kfO7nhXiw4XYYD3fyJsbC8kmDVv2iJZqqaAtnn/d08MPkL8NHh+1plHFpmEtzcM5ekXN00yBw075rg4PLxhgmz7d1cAf/gG5GAdISI2oNjVHfGried5K/QrrPfqYUHfwH7sSu62b8A39iR+Y=

Body:
This solved the issue:

private void decode_decompress(String string) {
    byte[] decodedBytes = Base64.decodeBase64(string);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(false);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
    try {
        inflaterOutputStream.write(decodedBytes);
        inflaterOutputStream.close();
        String data = stream.toString();
        logger.info("Data: {}", data);
    } catch (IOException e) {
        logger.error(string, e);
    }
}


问:
Uri mapping and uri routing
I'm reading a book on Silverlight 4. It uses terms "uri mapping" and "uri routing", but I can't see any difference. They seem to me as the same thing. Please somebody explain the difference.

btw. When I want to use "nice" url's, I use UriMapper class and define some mappings, so I expect this is "uri mapping". So where is any special "uri routing" class and how it differs from UriMapper?

citation:
"In addition to Uri Mapping, the navigation framework in Silverlight supports Uri Routing. For example if you placed all of your navigation views in a subdirectory named Views, you can follow a naming convention that you set. Then setup Uri Routes such as the following:

```<code><nav:UriMapping Uri="{}{p}" MappedUri="/Views/{p}.xaml" />
</code>```

"

[Note that this is my very first question on this forum. I hope it's all right.]

答:
UriMapper is a concept in the Silverlight Navigation Framework (System.Windows.Controls.Navigation.dll, in the Silverlight SDK).  "URI routing" is typically referring to the feature in ASP.NET, but it depends on how that author is using it - they may simply be using two terms to refer to the same feature.

If you can show some example sentences from the book that are confusing you, that may help.

Title: Uri mapping and uri routing

Body:
I'm reading a book on Silverlight 4. It uses terms "uri mapping" and "uri routing", but I can't see any difference. They seem to me as the same thing. Please somebody explain the difference.

btw. When I want to use "nice" url's, I use UriMapper class and define some mappings, so I expect this is "uri mapping". So where is any special "uri routing" class and how it differs from UriMapper?

citation:
"In addition to Uri Mapping, the navigation framework in Silverlight supports Uri Routing. For example if you placed all of your navigation views in a subdirectory named Views, you can follow a naming convention that you set. Then setup Uri Routes such as the following:

"

[Note that this is my very first question on this forum. I hope it's all right.]


问:
Nesting a http request inside list of promises
I have a service function that returns a list of promises:

```<code>getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

, which I'm calling inside my controller:

```<code>validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}
</code>```

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

答:
If you return a promise from the then the caller of the original promise will wait until the nested promise is resolved. It does not matter if the caller was your service using $q.all or something else, it is chained.

This shows just the relevant code, it located in your service with everything else being unchanged.

```<code>userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    .then((result) => {
       // additional manipulation if needed on result
       // second call to http and return the resulting promise
       return this.$http.doSomething('');
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a service function that returns a list of promises:

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

, which I'm calling inside my controller:

validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

Body:
If you return a promise from the then the caller of the original promise will wait until the nested promise is resolved. It does not matter if the caller was your service using $q.all or something else, it is chained.

This shows just the relevant code, it located in your service with everything else being unchanged.

userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    .then((result) => {
       // additional manipulation if needed on result
       // second call to http and return the resulting promise
       return this.$http.doSomething('');
    });


问:
MS Project: Loop through filtered tasks
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

```<code>Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next
</code>```

答:
Could it be that you just need to adjust the line

```<code>Dim b As Task
</code>```

to

```<code>Dim b As Filter
</code>```

According to the docs TaskFilters returns a collection of Filters

I hope this solves the issue. If you need more help with your current problem, please ask another question or edit your current one to clarify where you need help.

Title: MS Project: Loop through filtered tasks

Body:
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next

Body:
Could it be that you just need to adjust the line

Dim b As Task

to

Dim b As Filter

According to the docs TaskFilters returns a collection of Filters

I hope this solves the issue. If you need more help with your current problem, please ask another question or edit your current one to clarify where you need help.


问:
Display multiple images in one IPython Notebook cell?
If I have multiple images (loaded as NumPy arrays) how can I display the in one IPython Notebook cell?

I know that I can use plt.imshow(ima) to display one image… but I want to show more than one at a time.

I have tried:

```<code> for ima in images:
     display(Image(ima))
</code>```

But I just get a broken image link:

答:
```<code>from matplotlib.pyplot import figure, imshow, axis
from matplotlib.image import imread

mypath='.'
hSize = 5
wSize = 5
col = 4

def showImagesMatrix(list_of_files, col=10):
    fig = figure( figsize=(wSize, hSize))
    number_of_files = len(list_of_files)
    row = number_of_files/col
    if (number_of_files%col != 0):
        row += 1
    for i in range(number_of_files):
        a=fig.add_subplot(row,col,i+1)
        image = imread(mypath+'/'+list_of_files[i])
        imshow(image,cmap='Greys_r')
        axis('off')

showImagesMatrix(listOfImages,col)
</code>```

based on @Michael answer

Body:
If I have multiple images (loaded as NumPy arrays) how can I display the in one IPython Notebook cell?

I know that I can use plt.imshow(ima) to display one image… but I want to show more than one at a time.

I have tried:

 for ima in images:
     display(Image(ima))

But I just get a broken image link:

Body:
from matplotlib.pyplot import figure, imshow, axis
from matplotlib.image import imread

mypath='.'
hSize = 5
wSize = 5
col = 4

def showImagesMatrix(list_of_files, col=10):
    fig = figure( figsize=(wSize, hSize))
    number_of_files = len(list_of_files)
    row = number_of_files/col
    if (number_of_files%col != 0):
        row += 1
    for i in range(number_of_files):
        a=fig.add_subplot(row,col,i+1)
        image = imread(mypath+'/'+list_of_files[i])
        imshow(image,cmap='Greys_r')
        axis('off')

showImagesMatrix(listOfImages,col)

based on @Michael answer


问:
Disabled <input> that allows text selection?
Is it possible for a disabled <input> tag to support text selection?

答: You could use the ReadOnly attribute.</p>

Body: You could use the ReadOnly attribute.


问:
Generating human readable SWIFT messages using Prowide-Core?
I'm using Prowide-Core for SWIFT message handling. At the moment I use the JSON methods to produce human readable versions of my messages if I need to dump them out. This produces output like this:

```<code>...
}, {
  "97A" : ":SAFE//0123-0123456-55-000"
}, {
...
</code>```

I.e. I get alphanumeric codes, like 97A, for the field names.

However it I look at Field97A.java:471 I can see that it (and all other fields) know their more human readable names (Qualifier and Account in the case of 97A).

I've tried looking for some toString() like method that makes use of this information to produce something even more readable than the JSON output but haven't found anything yet.

Is there such a method on SwiftMessage or one of the related classes? Or has someone written something nice that can traverse a message and print it out using the information returned by getComponentLabels() etc?

答:
SwiftTagListBlock provides a toJson method that iterates over Tag objects:

```<code>     public String toJson() {
         final StringBuilder sb = new StringBuilder();
         sb.append("[ \n");
         if (this.tags != null && !this.tags.isEmpty()) {
             for (int i=0;i<this.tags.size();i++) {
                 final Tag t = this.tags.get(i);
                 sb.append("{ \"").append(t.getName()).append("\" : \"").append(escapeJson(t.getValue())).append("\" }");
                 if (i+1<this.tags.size()) {
                     sb.append(',');
                 }
                 sb.append('\n');
             }

         }
         sb.append("]");
         return sb.toString();
      }
</code>```

You could tweak the source code and call the asField() method of Tag, in order to have access to the Field representation and use the information required for your output.

Body:
I'm using Prowide-Core for SWIFT message handling. At the moment I use the JSON methods to produce human readable versions of my messages if I need to dump them out. This produces output like this:

...
}, {
  "97A" : ":SAFE//0123-0123456-55-000"
}, {
...

I.e. I get alphanumeric codes, like 97A, for the field names.

However it I look at Field97A.java:471 I can see that it (and all other fields) know their more human readable names (Qualifier and Account in the case of 97A).

I've tried looking for some toString() like method that makes use of this information to produce something even more readable than the JSON output but haven't found anything yet.

Is there such a method on SwiftMessage or one of the related classes? Or has someone written something nice that can traverse a message and print it out using the information returned by getComponentLabels() etc?

Body:
SwiftTagListBlock provides a toJson method that iterates over Tag objects:

     public String toJson() {
         final StringBuilder sb = new StringBuilder();
         sb.append("[ \n");
         if (this.tags != null && !this.tags.isEmpty()) {
             for (int i=0;i<this.tags.size();i++) {
                 final Tag t = this.tags.get(i);
                 sb.append("{ \"").append(t.getName()).append("\" : \"").append(escapeJson(t.getValue())).append("\" }");
                 if (i+1<this.tags.size()) {
                     sb.append(',');
                 }
                 sb.append('\n');
             }

         }
         sb.append("]");
         return sb.toString();
      }

You could tweak the source code and call the asField() method of Tag, in order to have access to the Field representation and use the information required for your output.


问:
return object of getContext
When I did the view.getContext from onClick(View view), I observed that not always it gives the host activity object.

So,when does view.getContext() from onClick(View view) returns ContextThemeWrapper object or when it returns host activity object or any other object?

答:
Context is an interface to global information about an application environment.

Activity class extends ContextThemeWrapper, if you want your activity as a parameter, you need to cast the context to your activity or create your Interface between your components.

If you want to know why, you need to read the source code:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/LayoutInflater.java

At line 758:

```<code>if (themeResId != 0) {
     context = new ContextThemeWrapper(context, themeResId);
}
</code>```

And at line 908:

```<code>if (hasThemeOverride) {
        context = new ContextThemeWrapper(context, themeResId);
}
</code>```

So... if you want to pass your activity as parameter, you shouldn't use context.

Title: return object of getContext

Body:
Context is an interface to global information about an application environment.

Activity class extends ContextThemeWrapper, if you want your activity as a parameter, you need to cast the context to your activity or create your Interface between your components.

If you want to know why, you need to read the source code:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/LayoutInflater.java

At line 758:

if (themeResId != 0) {
     context = new ContextThemeWrapper(context, themeResId);
}

And at line 908:

if (hasThemeOverride) {
        context = new ContextThemeWrapper(context, themeResId);
}

So... if you want to pass your activity as parameter, you shouldn't use context.


问:
How to set a proportional width to subviews in UIStackView(Horizontal)
I'm having 2 views in Horizontal Stack View and the Distribution Style of that is Fill Proportionally. If One view set hidden as TRUE another view occupies all the space but when both the views are appearing Stack View is giving them a equal width instead giving proportional width. But where to specify the width proportions for the Stack View.</p>

答:
UIStackView works purely on Autolayout, setting their frames or frames for their subviews wont work.
Simplest way is to use Anchors.

```<code>[self.subViews.widthAnchor constraintEqualToConstant:50.0].active = YES;
</code>```

Then the stackView will adjust itself accordingly.

Body:
UIStackView works purely on Autolayout, setting their frames or frames for their subviews wont work.
Simplest way is to use Anchors.

[self.subViews.widthAnchor constraintEqualToConstant:50.0].active = YES;

Then the stackView will adjust itself accordingly.


问:
TypeScript - why compiler allows undefined class attributes with explicit type specified?
Why code below compiles?

```<code>class Foo {
  public readonly foo: string;
}

const f = new Foo();
console.log(f.foo);  // undefined
</code>```

Even with all these --strictNullChecks and --noImplicit* it compiles and output undefined.

答:
Looking through the typescript issues, I have found that you have to use --strict mode to see compile error on your code.

Github Issue topic(Please search for below text)

mhegazy commented on Apr 22

  Reopening this issue. New plan, look into adding the check under a new
  flag (on by default under --strict).

Body:
Why code below compiles?

class Foo {
  public readonly foo: string;
}

const f = new Foo();
console.log(f.foo);  // undefined

Even with all these --strictNullChecks and --noImplicit* it compiles and output undefined.


问:
Linq to entities: cast result to multiple listed complex types
I'm trying to create a single linq query which populates the following models in the CompanyViewModel constructor:

```<code>public class CompanyViewModel
{
    public IList<CompanyUserViewModel> CompanyUsers { get; set; }
    ...
}

public class CompanyUserViewModel
{
    public User User { get; set; }
    public IList<UserOperationViewModel> UsersOperations { get; set; }
}

public class UserOperationViewModel
{
    public Operation Operation { get; set; }
    public int Permission { get; set; }
}
</code>```

Currently I've got the following query:

```<code>return db.Users.Where(u => u.CompanyId == companyId)
               .Select(u => new CompanyUserViewModel {
                    User = u,
                    UsersOperations = db.UsersInOperations
                        .Where(uo => uo.UserId == uo.UserId)
                        .Select(uo => new UserOperationViewModel{
                             Operation = uo.Operation,
                             Permission = uo.Permission
                        }).ToList()
                }).ToList();
</code>```

Which builds, but when the page runs I get

```<code>LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[WoodCo.Models.BusinessObject.UserOperationViewModel] ToList[UserOperationViewModel](System.Collections.Generic.IEnumerable`1[WoodCo.Models.BusinessObject.UserOperationViewModel])' method, and this method cannot be translated into a store expression.
</code>```

What does one do?

答: Change your view model properties to use IEnumerable<T> instead of IList<T and remove the .ToList() calls.

Body:
I'm trying to create a single linq query which populates the following models in the CompanyViewModel constructor:

public class CompanyViewModel
{
    public IList<CompanyUserViewModel> CompanyUsers { get; set; }
    ...
}

public class CompanyUserViewModel
{
    public User User { get; set; }
    public IList<UserOperationViewModel> UsersOperations { get; set; }
}

public class UserOperationViewModel
{
    public Operation Operation { get; set; }
    public int Permission { get; set; }
}

Currently I've got the following query:

return db.Users.Where(u => u.CompanyId == companyId)
               .Select(u => new CompanyUserViewModel {
                    User = u,
                    UsersOperations = db.UsersInOperations
                        .Where(uo => uo.UserId == uo.UserId)
                        .Select(uo => new UserOperationViewModel{
                             Operation = uo.Operation,
                             Permission = uo.Permission
                        }).ToList()
                }).ToList();

Which builds, but when the page runs I get

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[WoodCo.Models.BusinessObject.UserOperationViewModel] ToList[UserOperationViewModel](System.Collections.Generic.IEnumerable`1[WoodCo.Models.BusinessObject.UserOperationViewModel])' method, and this method cannot be translated into a store expression.

What does one do?


问:
JMeter GUI - execute using NewDriver failed to view Function Helper Dialog
I try to test a new function in JMeter.

I download JMeter 3.3 code and add plugins including JMeterPluginsCMD

I also download jmeter-plugins-extras-1.4.0.jar with HttpSimpleTableControlGui class

I execute NewDriver which opens JMeter GUI, I try to open Options -> Function Helper Dialog but I have no functions

log:

```<code>2017-11-13 16:16:56,661 WARN o.a.j.g.u.MenuFactory: Could not instantiate class: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
java.lang.ClassNotFoundException: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_25]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_25]
    at org.apache.jmeter.gui.util.MenuFactory.initializeMenus(MenuFactory.java:499) [core/:?]
    at org.apache.jmeter.gui.util.MenuFactory.<clinit>(MenuFactory.java:169) [core/:?]
    at org.apache.jmeter.control.gui.WorkBenchGui.createPopupMenu(WorkBenchGui.java:119) [core/:?]
    at org.apache.jmeter.gui.tree.JMeterTreeNode.createPopupMenu(JMeterTreeNode.java:159) [core/:?]
    at org.apache.jmeter.gui.action.EditCommand.doAction(EditCommand.java:46) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
2017-11-13 16:16:59,670 ERROR o.a.j.g.a.ActionRouter: Error processing org.apache.jmeter.gui.action.CreateFunctionDialog@45e37a7e
java.lang.NullPointerException: null
    at org.apache.jmeter.functions.gui.FunctionHelper.initParameterPanel(FunctionHelper.java:165) ~[core/:?]
    at org.apache.jmeter.functions.gui.FunctionHelper.setVisible(FunctionHelper.java:228) ~[core/:?]
    at org.apache.jmeter.gui.action.CreateFunctionDialog.doAction(CreateFunctionDialog.java:50) ~[core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
</code>```

答:
The recommended way of installing JMeter Plugins and keeping them up-to-date is using JMeter Plugins Manager

I do confirm that brand new JMeter 3.3 and HTTP Simple Table Server work fine together without any issues with The Function Helper Dialog.

So my expectations are in:

Your installation is broken, you should have:

jmeter-plugins-table-server-2.2.jar in "lib/ext" folder

jmeter-plugins-cmn-jmeter-0.4.jar in "lib" folder

JMeter restart is required to pick any .jars up

(most likely) Your function implementation is flaky. If this is the case you will need to provide your function code along with the question.

Body:
I try to test a new function in JMeter.

I download JMeter 3.3 code and add plugins including JMeterPluginsCMD

I also download jmeter-plugins-extras-1.4.0.jar with HttpSimpleTableControlGui class

I execute NewDriver which opens JMeter GUI, I try to open Options -> Function Helper Dialog but I have no functions

log:

2017-11-13 16:16:56,661 WARN o.a.j.g.u.MenuFactory: Could not instantiate class: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
java.lang.ClassNotFoundException: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_25]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_25]
    at org.apache.jmeter.gui.util.MenuFactory.initializeMenus(MenuFactory.java:499) [core/:?]
    at org.apache.jmeter.gui.util.MenuFactory.<clinit>(MenuFactory.java:169) [core/:?]
    at org.apache.jmeter.control.gui.WorkBenchGui.createPopupMenu(WorkBenchGui.java:119) [core/:?]
    at org.apache.jmeter.gui.tree.JMeterTreeNode.createPopupMenu(JMeterTreeNode.java:159) [core/:?]
    at org.apache.jmeter.gui.action.EditCommand.doAction(EditCommand.java:46) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
2017-11-13 16:16:59,670 ERROR o.a.j.g.a.ActionRouter: Error processing org.apache.jmeter.gui.action.CreateFunctionDialog@45e37a7e
java.lang.NullPointerException: null
    at org.apache.jmeter.functions.gui.FunctionHelper.initParameterPanel(FunctionHelper.java:165) ~[core/:?]
    at org.apache.jmeter.functions.gui.FunctionHelper.setVisible(FunctionHelper.java:228) ~[core/:?]
    at org.apache.jmeter.gui.action.CreateFunctionDialog.doAction(CreateFunctionDialog.java:50) ~[core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]


问:
VSCode hide top-right icons
I'm a big fan of VScode's minimalist approach, but one thing is bugging me. I would like to hide editor-tab icons.

The icons are from extensions: git-lens & hexdump for VScode. Also the split-editor icon would be nice to hide.

答:
Extension Custom CSS and JS Loader

.tabs-and-actions-container .editor-actions {
    display: none !important;
}
```

<p>Optionally, show them on hover:</p>

<pre class="lang-css prettyprint-override"><code>.tabs-and-actions-container:hover .editor-actions {
    display: flex !important;
}
</code>```

Title: VSCode hide top-right icons

Body:
Extension Custom CSS and JS Loader

.tabs-and-actions-container .editor-actions {
    display: none !important;
}

Optionally, show them on hover:

.tabs-and-actions-container:hover .editor-actions {
    display: flex !important;
}


问:
Why are these responsive images not filling the wrapper?
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

```<code><div class="Wrapper">
  <img
    src="//via.placeholder.com/250x150"
    srcset="
      //via.placeholder.com/100x150 100w,
      //via.placeholder.com/250x150 250w,
      //via.placeholder.com/500x150 500w,
      //via.placeholder.com/750x150 750w,
      //via.placeholder.com/1000x150 1000w,
      //via.placeholder.com/1250x150 1250w,
      //via.placeholder.com/1500x150 1500w"
    sizes="(min-width: 30em) 30rem, 100vw"
  >
</div>
</code>```

With this css (there is more, but this is the minimum to reproduce):

```<code>html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}
</code>```

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/

答:
So apparently:

When used in sizes or media queries, em and rem are both specced to mean "the user's default font-size.

The actual em or rem that controls how the image is laid out on the page can end up different if your CSS changes it

This means one should not change the default size of em if they want to give the image preloader truthful information

So the em and rem in the sizes attribute do not correspond to the em and rem in your css. Which is why the size of the image doesn't correspond to its container. Ridiculous.

See: https://stackoverflow.com/a/30675128/5918874

Body:
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

With this css (there is more, but this is the minimum to reproduce):

html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/


问:
How to start SQL Server Agent etl job after complete Oracle process
I have Oracle source and SQL Server. Every day at 12.00 AM Oracle data populate for oracle database tables, after that sql server agent jobs run manually by me after Oracle Data Extraction completed. for SQL Server databases, I want to automate this process. when oracle data population completed i need to run sql server agent jobs automatically, how can i do this.</p>

答:
You write a little program that will monitor the oracle process and when it "sees" that is has completed (probably successfully - you skipped that part) it starts the sql server job. Now - how do you do that? How do you know that the process both completed and successfully? Go figure it out based on what functionality Oracle offers and (perhaps) the characteristics of the output that signify success. </p>

<p>Perhaps you can vastly simplify things and schedule some sort of "do it" job that will look for "good" output. Schedule it for a time that is more than sufficient for the oracle process to complete. Do some checking and if things look good, start the other job. </p>

Body:
You write a little program that will monitor the oracle process and when it "sees" that is has completed (probably successfully - you skipped that part) it starts the sql server job. Now - how do you do that? How do you know that the process both completed and successfully? Go figure it out based on what functionality Oracle offers and (perhaps) the characteristics of the output that signify success.

Perhaps you can vastly simplify things and schedule some sort of "do it" job that will look for "good" output. Schedule it for a time that is more than sufficient for the oracle process to complete. Do some checking and if things look good, start the other job.