问:
substr_len with HTML, show first X chars and a "See more" link (jquery.readmore Plugin)
I'm using a plugin to show only the first 500 characters of a text... But it's not working with some HTML, I can't reproduce it but I think it could have to be with an  tag, or a
 or maybe an
 /

It just shows the whole text AND the "See More" link...

Any idea?

This is the code

```<code>(function ($) {
$.fn.readmore = function (settings) {

$('.home_excerpt').removeClass('home_excerpt');

var opts =  $.extend({}, $.fn.readmore.defaults, settings);

this.each(function () {
  $(this).data("opts", opts);
  if ($(this).html().length > opts.substr_len) {
    abridge($(this));
    linkage($(this));
  }
});

function linkage(elem) {
  elem.append(elem.data("opts").more_link);
  $(".text_seemore").click( function () {
    $(this).hide();
    $(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").show();
    return false;
  });
}

function abridge(elem) {
  var opts = elem.data("opts");
  var txt = elem.html();
  var len = opts.substr_len;
  var dots = "<span>" + opts.ellipses + "</span>";
  var charAtLen = txt.substr(len, 1);
  while (len < txt.length && !/\s/.test(charAtLen)) {
      len++;
      charAtLen = txt.substr(len, 1);
  }
  var shown = txt.substring(0, len) + dots;
  var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
  elem.html(shown + hidden);
}

return this;
};

$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '<br /><a href="#" class="text_seemore">See More</a>'
};

 })(jQuery);
</code>```

答:
It seems that in your abridge() function you're trying to avoid cutting a word in half, if I'm reading your code right. The problem is that if there isn't any whitespace after the desired length, you will just return the whole thing, but you're not checking afterwards if that's the case. That means you will return the full text AND put the more link in too.

As you're processing HTML, the above is a usual case if you're having single word lines, tables with single word cells, etc., of if you're using   as whitespace.

The bigger problem is that you're cutting the HTML as string, which will almost certainly result in broken markup. You can easily cut tags in half, strip block elements' closing tags, and so on. See if you can use elem.text() to process it as pure string, or if you want to keep the formatting, see if you can extract the first paragraph, or something similar.

You can of course implement some advanced method of checking and closing stripped tags, but it might not worth the trouble. I'd check if there's a plugin out there which already does what you need.

Body:
I'm using a plugin to show only the first 500 characters of a text... But it's not working with some HTML, I can't reproduce it but I think it could have to be with an  tag, or a
 or maybe an
 /

It just shows the whole text AND the "See More" link...

Any idea?

This is the code

(function ($) {
$.fn.readmore = function (settings) {

$('.home_excerpt').removeClass('home_excerpt');

var opts =  $.extend({}, $.fn.readmore.defaults, settings);

this.each(function () {
  $(this).data("opts", opts);
  if ($(this).html().length > opts.substr_len) {
    abridge($(this));
    linkage($(this));
  }
});

function linkage(elem) {
  elem.append(elem.data("opts").more_link);
  $(".text_seemore").click( function () {
    $(this).hide();
    $(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").show();
    return false;
  });
}

function abridge(elem) {
  var opts = elem.data("opts");
  var txt = elem.html();
  var len = opts.substr_len;
  var dots = "" + opts.ellipses + "";
  var charAtLen = txt.substr(len, 1);
  while (len < txt.length && !/\s/.test(charAtLen)) {
      len++;
      charAtLen = txt.substr(len, 1);
  }
  var shown = txt.substring(0, len) + dots;
  var hidden = '' + txt.substring(len, txt.length) + '';
  elem.html(shown + hidden);
}

return this;
};

$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '
See More'
};

 })(jQuery);

Body:
It seems that in your abridge() function you're trying to avoid cutting a word in half, if I'm reading your code right. The problem is that if there isn't any whitespace after the desired length, you will just return the whole thing, but you're not checking afterwards if that's the case. That means you will return the full text AND put the more link in too.

As you're processing HTML, the above is a usual case if you're having single word lines, tables with single word cells, etc., of if you're using &nbsp; as whitespace.

The bigger problem is that you're cutting the HTML as string, which will almost certainly result in broken markup. You can easily cut tags in half, strip block elements' closing tags, and so on. See if you can use elem.text() to process it as pure string, or if you want to keep the formatting, see if you can extract the first paragraph, or something similar.

You can of course implement some advanced method of checking and closing stripped tags, but it might not worth the trouble. I'd check if there's a plugin out there which already does what you need.


来源: stackexchange

问:
How do I filter through an array list and return results that match the filter parameter?
I have a list that I'm filtering through to return results that are either, lessThan, greaterThan or equals to a particular value. But the function that does the comparison returns boolean values.

queryModifiers is an object of key value pairs that specifies what key within the data set is being compared and also the type of comparison.

const queryModifiers = {
price: "greaterThan",
weight: "lessThan",
}

const list = [
{
      '2104a7bd-5e78-49ce-a1f6-0699ac98f264': {
        additionalPrices: 0,
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        completeDate: 'Invalid date',
        createdAt: '2019-09-08 16:41:43',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-14 16:39:25',
        driver: 'Robert Kaszkiewicz',
        dropOff: 'Avenida Callao 1234, Buenos Aires, Argentina',
        height: 23,
        isPreparingTrailer: true,
        isSmsSent: true,
        isTrailerReady: true,
        key: '2104a7bd-5e78-49ce-a1f6-0699ac98f264',
        notes: '',
        pickUp: 'Poprad, Slovakia',
        price: 1400,
        quantity: 2,
        trailer: 'einzeln',
        vehicle: 'Sattel',
        vehicleClass: 'Mega',
        vehicleId: '12313',
        vehicleReadyDate: '2019-09-27 16:41:22',
        weight: 123
      },
      '388113f5-3927-4fe3-80d5-f2fcf1c7cedd': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-09-26 18:32:18',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-20 18:31:45',
        driver: 'Michal Kucharski',
        dropOff: 'Logroño, Spain',
        height: 0,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '388113f5-3927-4fe3-80d5-f2fcf1c7cedd',
        notes: '',
        orderId: '',
        pickUp: '16671 Butano Place, Fontana, CA, USA',
        price: 0,
        quantity: 1,
        trailer: '2er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: 'efgefg',
        vehicleReadyDate: '2019-09-27 18:32:08',
        weight: 0
      },
      '795e7531-8655-4e38-a576-e13483922607': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-10-07 14:59:28',
        createdBy: 'test@test.com',
        deliveryDate: '2019-10-09 14:54:44',
        driver: 'Pawel Marczyk',
        dropOff: 'München, Germany',
        height: 1150,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '795e7531-8655-4e38-a576-e13483922607',
        notes: 'alle fertig, vorher anrufen',
        orderId: '',
        pickUp: 'Soest, Germany',
        price: 5000,
        quantity: 10,
        trailer: '3er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: '1121+23+24',
        vehicleReadyDate: '2019-10-07 14:55:19',
        weight: 20000
      },
] // list is an array of objects

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    console.log(result); // result here returns boolean (true or false);
                })
        );
```

Where value is the parameter by which the list is being queried with e.g 100

compareValue is the data[key] value from the list that corresponds with the parameter being compared.

and modifier is the comparison method e.g greaterThan, lessThan or equals.

I want result to return list items that match and not boolean (which are actually correct when matched with the dataset).

答:
It's not entirely clear what you're asking, but it seems to be that the console.log you have is returning a boolean, but you are expecting it to return a value, since you are trying to filter the list?

But actually, you probably do want it to return a boolean where it is. It is inside of an every function, which itself is inside of a filter function. The way every works is each iteration should return true or false (and if there are any falses, the whole thing returns false), and the way filter works is for each item, if you return true the item is saved into the resulting array. They both expect a boolean return.

```<code>list.filter(
    item => Object.entries(queryModifiers)
         .every(([filterKey, filterVal]) => {
             const compareValue = item[filterKey];
             const value = Object.values(queryKeys);
             const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                })
        );
</code>```

Line by line:

list.filter : filter the list

item => Object.entries(queryModifiers) : set each item in the list to item, and then get the key pairs of the object, queryModifiers (which you haven't included here, by the way)

.every(([filterKey, filterVal]) => { : return true or false (i.e. keep or discard this item) if all of the queryModifiers key pairs sent into this function return true

const compareValue = item[filterKey]; : prepare a value

const value = Object.values(queryKeys); : prepare a value

const result = handleFilterModifier( ... ) : determine a true/false result

At this point result should be true or false, signifying whether this key/pair of queryModifiers passes your test, and it should be returned, i.e. return result; If all of them do, then the every function will return true, which means this iteration of the filter function will be included in the result.

So basically:

```<code>const resultList = list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    return result;
                })
        );
console.log(resultList);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list that I'm filtering through to return results that are either, lessThan, greaterThan or equals to a particular value. But the function that does the comparison returns boolean values.

queryModifiers is an object of key value pairs that specifies what key within the data set is being compared and also the type of comparison.

const queryModifiers = {
price: "greaterThan",
weight: "lessThan",
}

const list = [
{
      '2104a7bd-5e78-49ce-a1f6-0699ac98f264': {
        additionalPrices: 0,
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        completeDate: 'Invalid date',
        createdAt: '2019-09-08 16:41:43',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-14 16:39:25',
        driver: 'Robert Kaszkiewicz',
        dropOff: 'Avenida Callao 1234, Buenos Aires, Argentina',
        height: 23,
        isPreparingTrailer: true,
        isSmsSent: true,
        isTrailerReady: true,
        key: '2104a7bd-5e78-49ce-a1f6-0699ac98f264',
        notes: '',
        pickUp: 'Poprad, Slovakia',
        price: 1400,
        quantity: 2,
        trailer: 'einzeln',
        vehicle: 'Sattel',
        vehicleClass: 'Mega',
        vehicleId: '12313',
        vehicleReadyDate: '2019-09-27 16:41:22',
        weight: 123
      },
      '388113f5-3927-4fe3-80d5-f2fcf1c7cedd': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-09-26 18:32:18',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-20 18:31:45',
        driver: 'Michal Kucharski',
        dropOff: 'Logroño, Spain',
        height: 0,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '388113f5-3927-4fe3-80d5-f2fcf1c7cedd',
        notes: '',
        orderId: '',
        pickUp: '16671 Butano Place, Fontana, CA, USA',
        price: 0,
        quantity: 1,
        trailer: '2er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: 'efgefg',
        vehicleReadyDate: '2019-09-27 18:32:08',
        weight: 0
      },
      '795e7531-8655-4e38-a576-e13483922607': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-10-07 14:59:28',
        createdBy: 'test@test.com',
        deliveryDate: '2019-10-09 14:54:44',
        driver: 'Pawel Marczyk',
        dropOff: 'München, Germany',
        height: 1150,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '795e7531-8655-4e38-a576-e13483922607',
        notes: 'alle fertig, vorher anrufen',
        orderId: '',
        pickUp: 'Soest, Germany',
        price: 5000,
        quantity: 10,
        trailer: '3er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: '1121+23+24',
        vehicleReadyDate: '2019-10-07 14:55:19',
        weight: 20000
      },
] // list is an array of objects

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    console.log(result); // result here returns boolean (true or false);
                })
        );

Where value is the parameter by which the list is being queried with e.g 100

compareValue is the data[key] value from the list that corresponds with the parameter being compared.

and modifier is the comparison method e.g greaterThan, lessThan or equals.

I want result to return list items that match and not boolean (which are actually correct when matched with the dataset).

Body:
It's not entirely clear what you're asking, but it seems to be that the console.log you have is returning a boolean, but you are expecting it to return a value, since you are trying to filter the list?

But actually, you probably do want it to return a boolean where it is. It is inside of an every function, which itself is inside of a filter function. The way every works is each iteration should return true or false (and if there are any falses, the whole thing returns false), and the way filter works is for each item, if you return true the item is saved into the resulting array. They both expect a boolean return.

list.filter(
    item => Object.entries(queryModifiers)
         .every(([filterKey, filterVal]) => {
             const compareValue = item[filterKey];
             const value = Object.values(queryKeys);
             const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                })
        );

Line by line:

list.filter : filter the list

item => Object.entries(queryModifiers) : set each item in the list to item, and then get the key pairs of the object, queryModifiers (which you haven't included here, by the way)

.every(([filterKey, filterVal]) => { : return true or false (i.e. keep or discard this item) if all of the queryModifiers key pairs sent into this function return true

const compareValue = item[filterKey]; : prepare a value

const value = Object.values(queryKeys); : prepare a value

const result = handleFilterModifier( ... ) : determine a true/false result

At this point result should be true or false, signifying whether this key/pair of queryModifiers passes your test, and it should be returned, i.e. return result; If all of them do, then the every function will return true, which means this iteration of the filter function will be included in the result.

So basically:

const resultList = list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    return result;
                })
        );
console.log(resultList);


问:
Extract residuals from models fit in purrr
I grouped my data and fit a model to each group and I would like to have the residuals for each group. I can see the residuals for each model with RStudio's viewer, but I cannot figure out how to extract them. Extracting one set of residuals can be done like diamond_mods[[3]][[1]][["residuals"]], but how do I use purrr to extract the set from every group (along with broom to end up with a nice tibble)?

Below is how far I've gotten:

```<code>library(tidyverse)
library(purrr)
library(broom)

fit_mod <- function(df) {
  lm(price ~ poly(carat, 2, raw = TRUE), data = df)
}

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy)
    #resid = map_dbl(model, "residuals") #this was my best try, it doesn't work
  ) %>%
  unnest(tidied)
</code>```

答:
With the devel version of dplyr, we can do this in condense after grouping by 'cut'

```<code>library(dplyr)
library(ggplot2)
library(broom)
diamonds %>%
   group_by(cut) %>%
   condense(model = fit_mod(cur_data()),
            tidied = tidy(model),
            resid = model[["residuals"]])
# A tibble: 5 x 4
# Rowwise:  cut
#  cut       model  tidied           resid
#  <ord>     <list> <list>           <list>
#1 Fair      <lm>   <tibble [3 × 5]> <dbl [1,610]>
#2 Good      <lm>   <tibble [3 × 5]> <dbl [4,906]>
#3 Very Good <lm>   <tibble [3 × 5]> <dbl [12,082]>
#4 Premium   <lm>   <tibble [3 × 5]> <dbl [13,791]>
#5 Ideal     <lm>   <tibble [3 × 5]> <dbl [21,551]>
</code>```

Body:
I grouped my data and fit a model to each group and I would like to have the residuals for each group. I can see the residuals for each model with RStudio's viewer, but I cannot figure out how to extract them. Extracting one set of residuals can be done like diamond_mods[[3]][[1]][["residuals"]], but how do I use purrr to extract the set from every group (along with broom to end up with a nice tibble)?

Below is how far I've gotten:

library(tidyverse)
library(purrr)
library(broom)

fit_mod <- function(df) {
  lm(price ~ poly(carat, 2, raw = TRUE), data = df)
}

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy)
    #resid = map_dbl(model, "residuals") #this was my best try, it doesn't work
  ) %>%
  unnest(tidied)

Body:
With the devel version of dplyr, we can do this in condense after grouping by 'cut'

library(dplyr)
library(ggplot2)
library(broom)
diamonds %>%
   group_by(cut) %>%
   condense(model = fit_mod(cur_data()),
            tidied = tidy(model),
            resid = model[["residuals"]])
# A tibble: 5 x 4
# Rowwise:  cut
#  cut       model  tidied           resid
#  <ord>     <list> <list>           <list>
#1 Fair      <lm>   <tibble [3 × 5]> <dbl [1,610]>
#2 Good      <lm>   <tibble [3 × 5]> <dbl [4,906]>
#3 Very Good <lm>   <tibble [3 × 5]> <dbl [12,082]>
#4 Premium   <lm>   <tibble [3 × 5]> <dbl [13,791]>
#5 Ideal     <lm>   <tibble [3 × 5]> <dbl [21,551]>


问:
PL SQL error in my VB.Net code but can't reproduce in SQL Developer

ORA-06502: PL/SQL: numeric or value error

      ORA-06512: at "JOHN.GET_USERS_EMAIL", line 7

      ORA-06512: at line 1

When I run my procedure in SQL Developer and use the values in my app, it works without any problem. When I run my VB.Net code, I get the exception (shown above)

I don't know what I am doing incorrectly. (The Oracle Procedure was not written by me. It was by another person who is no longer working here).

Procedure in Oracle

create or replace PROCEDURE "GET_USERS_EMAIL" (
User_Email_P OUT VARCHAR,
Employee_P IN VARCHAR
)
As
Begin
SELECT USER_EMAIL INTO User_Email_P FROM
EMPLOYEE
WHERE
USER_ID = Employee_P;
end;
```

<p>Code in VB.Net</p>

<pre class="lang-vb prettyprint-override"><code>Public Function Get_A_Users_Email(ByVal strEmpId As String) As String
    Try
        Dim rValue As String = ""
        Dim strSQL As String = "JOHN.GET_USERS_EMAIL"
        Dim cmd As OracleCommand = dba.CreateStoredProcCommand(strSQL)
        cmd.BindByName = True
        Dim oracleParameter(1) As OracleParameter
        oracleParameter(0) = New OracleParameter()
        oracleParameter(1) = New OracleParameter()
        strEmpId = UCase(strEmpId.Trim())

        With cmd
            oracleParameter(0) = cmd.Parameters.Add(name:="User_Email_P", dbType:=OracleDbType.Varchar2, direction:=ParameterDirection.Output)
            oracleParameter(1) = cmd.Parameters.Add(name:="Employee_P", dbType:=OracleDbType.Varchar2, val:=strEmpId, ParameterDirection.Input)

        End With

        dba.ExecuteScaler(cmd)

        If String.IsNullOrEmpty(cmd.Parameters("User_Email_P").Value.ToString) = True Then
            rValue = 0
        Else
            rValue = cmd.Parameters("User_Email_P").Value.ToString
        End If

        Return rValue
    Catch ex As Exception
        Dim Err As New App_Errors("App_Users", "Get_A_Users_Email", ex)
        Return Nothing
    End Try
End Function

Public Function ExecuteScaler(ByVal cmd As OracleCommand) As String
    ' the value tobe return ...
    Dim value As String = ""
    Dim oValue As Object
    Dim bValue As Boolean = False
    ' execute command ...
    Try
        ' open connection ...
        cmd.Connection.Open()
    Catch ex As Exception
        MsgBox("Unable to establish a connection to CFR database." & ex.ToString, MsgBoxStyle.Critical)
        Return value = ""
        Exit Function
    End Try
    Try

        ' execute command ... convert type in the case of return value null ...
        oValue = cmd.ExecuteScalar
        bValue = Convert.IsDBNull(oValue)
        If Not (bValue) Then
            value = CType(oValue, String)
        Else
            value = ""
        End If
    Catch ex As Exception
        ' rethrow error ...
        ' Dim Err As New App_Errors("Data_Access_Class", "ExecuteScalar", ex)
        Throw New Exception(ex.InnerException.ToString, ex)
    Finally
        cmd.Connection.Close()
    End Try
    Return value
End Function

Public Function CreateStoredProcCommand(ByVal cmdtext As String) As OracleCommand
    Dim Cmd As New OracleCommand        ' command object ...
    ' create command ...
    With Cmd
        .Connection = Conn
        .CommandText = cmdtext
        .CommandType = CommandType.StoredProcedure
    End With
    Return Cmd
End Function
</code>```

Here is the DDL of the table.

```<code>CREATE TABLE "JOHN"."EMPLOYEE"
   (    "EMPLOYEE_NUMBER" NUMBER(9,0),
    "LOCATION_CODE" VARCHAR2(4 BYTE),
    "SECURITY_LEVEL" NUMBER(2,0),
    "DATE_LAST_UPDATE" DATE,
    "DATE_SECURITY_ASSIGNED" DATE,
    "LAST_PASSWORD_DATE" DATE,
    "CURRENT_PASSWORD" VARCHAR2(8 BYTE),
    "FIRST_NAME" VARCHAR2(20 BYTE),
    "MIDDLE_INITIAL" VARCHAR2(1 BYTE),
    "LAST_NAME" VARCHAR2(30 BYTE),
    "USER_ID" VARCHAR2(8 BYTE),
    "USER_TYPE" CHAR(1 BYTE),
    "INACTIVE_DATE" DATE,
    "SECURITY_ASSIGNED_BY" VARCHAR2(8 BYTE),
    "PASSWORD_EXPIRATION_DATE" DATE,
    "STATUS_CODE" NUMBER(2,0),
    "ACCOUNT_LOCKED" VARCHAR2(1 BYTE),
    "UPDATE_PASS_ON_SIGNON" VARCHAR2(1 BYTE),
    "USER_EMAIL" VARCHAR2(30 BYTE))
</code>```

Please note that the DDL, Stored Procedures and VB.Net code was left from a previous developer. I am replacing the Microsoft's implementation of Oracle's driver to ODP.Net. There is literally no change in code other than this.

答:
Keep your database objects local to the method where they are used. That way you can control when they are closed and disposed. Connections and commands may contain unmanaged code which needs to be released by their respective .Dispose methods. In this example a Using...End Using block handles this for you even if there is an error.

I am not sure why you are creating the stored procedure again when you state that is is already in Oracle.

Your do quite a dance with the parameters creating an array of parameters then assigning values to the array elements. The Parameter.Add method automatically adds the parameter to the Parameters Collection. You are using named parameters but you are not using the proper names. To avoid this problem just use positional parameters.

Now we get to the actual .Execute. .ExecuteScalar returns the first column of the first row of the result set. I don't think you can refer to your Out parameter in this scenario. Without a cursor in the stored procedure I am not sure any result set is returned.

Try an .ExecuteNonQuery and then retrieve the parameter value. Notice that my database objects are closed and disposed by the End Using before I start checking the returned value.

I cannot test this because I don't have an installation of Oracle hanging around.

```<code>Public Function Get_A_Users_Email(ByVal strEmpId As String) As String
    Dim retVal As Object
    Using cn As New OracleConnection("Your connection string"),
            cmd As New OracleCommand("JOHN.GET_USERS_EMAIL", cn)
        cmd.BindByName = True
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("User_Email_P", OracleDbType.Varchar2, ParameterDirection.Output)
        cmd.Parameters.Add("Employee_P", OracleDbType.Varchar2, UCase(strEmpId.Trim()), ParameterDirection.Input)
        cn.Open()
        cmd.ExecuteNonQuery()
        retVal = cmd.Parameters("User_Email_P").Value
    End Using
    Dim returnString As String
    If retVal Is Nothing Then
        returnString = ""
    Else
        returnString = retVal.ToString
    End If
    Return returnString
End Function
</code>```

Body:
ORA-06502: PL/SQL: numeric or value error

      ORA-06512: at "JOHN.GET_USERS_EMAIL", line 7

      ORA-06512: at line 1

When I run my procedure in SQL Developer and use the values in my app, it works without any problem. When I run my VB.Net code, I get the exception (shown above)

I don't know what I am doing incorrectly. (The Oracle Procedure was not written by me. It was by another person who is no longer working here).

Procedure in Oracle

create or replace PROCEDURE "GET_USERS_EMAIL" (
User_Email_P OUT VARCHAR,
Employee_P IN VARCHAR
)
As
Begin
SELECT USER_EMAIL INTO User_Email_P FROM
EMPLOYEE
WHERE
USER_ID = Employee_P;
end;

Code in VB.Net

Public Function Get_A_Users_Email(ByVal strEmpId As String) As String
    Try
        Dim rValue As String = ""
        Dim strSQL As String = "JOHN.GET_USERS_EMAIL"
        Dim cmd As OracleCommand = dba.CreateStoredProcCommand(strSQL)
        cmd.BindByName = True
        Dim oracleParameter(1) As OracleParameter
        oracleParameter(0) = New OracleParameter()
        oracleParameter(1) = New OracleParameter()
        strEmpId = UCase(strEmpId.Trim())

        With cmd
            oracleParameter(0) = cmd.Parameters.Add(name:="User_Email_P", dbType:=OracleDbType.Varchar2, direction:=ParameterDirection.Output)
            oracleParameter(1) = cmd.Parameters.Add(name:="Employee_P", dbType:=OracleDbType.Varchar2, val:=strEmpId, ParameterDirection.Input)

        End With

        dba.ExecuteScaler(cmd)

        If String.IsNullOrEmpty(cmd.Parameters("User_Email_P").Value.ToString) = True Then
            rValue = 0
        Else
            rValue = cmd.Parameters("User_Email_P").Value.ToString
        End If

        Return rValue
    Catch ex As Exception
        Dim Err As New App_Errors("App_Users", "Get_A_Users_Email", ex)
        Return Nothing
    End Try
End Function

Public Function ExecuteScaler(ByVal cmd As OracleCommand) As String
    ' the value tobe return ...
    Dim value As String = ""
    Dim oValue As Object
    Dim bValue As Boolean = False
    ' execute command ...
    Try
        ' open connection ...
        cmd.Connection.Open()
    Catch ex As Exception
        MsgBox("Unable to establish a connection to CFR database." & ex.ToString, MsgBoxStyle.Critical)
        Return value = ""
        Exit Function
    End Try
    Try

        ' execute command ... convert type in the case of return value null ...
        oValue = cmd.ExecuteScalar
        bValue = Convert.IsDBNull(oValue)
        If Not (bValue) Then
            value = CType(oValue, String)
        Else
            value = ""
        End If
    Catch ex As Exception
        ' rethrow error ...
        ' Dim Err As New App_Errors("Data_Access_Class", "ExecuteScalar", ex)
        Throw New Exception(ex.InnerException.ToString, ex)
    Finally
        cmd.Connection.Close()
    End Try
    Return value
End Function

Public Function CreateStoredProcCommand(ByVal cmdtext As String) As OracleCommand
    Dim Cmd As New OracleCommand        ' command object ...
    ' create command ...
    With Cmd
        .Connection = Conn
        .CommandText = cmdtext
        .CommandType = CommandType.StoredProcedure
    End With
    Return Cmd
End Function

Here is the DDL of the table.

CREATE TABLE "JOHN"."EMPLOYEE"
   (    "EMPLOYEE_NUMBER" NUMBER(9,0),
    "LOCATION_CODE" VARCHAR2(4 BYTE),
    "SECURITY_LEVEL" NUMBER(2,0),
    "DATE_LAST_UPDATE" DATE,
    "DATE_SECURITY_ASSIGNED" DATE,
    "LAST_PASSWORD_DATE" DATE,
    "CURRENT_PASSWORD" VARCHAR2(8 BYTE),
    "FIRST_NAME" VARCHAR2(20 BYTE),
    "MIDDLE_INITIAL" VARCHAR2(1 BYTE),
    "LAST_NAME" VARCHAR2(30 BYTE),
    "USER_ID" VARCHAR2(8 BYTE),
    "USER_TYPE" CHAR(1 BYTE),
    "INACTIVE_DATE" DATE,
    "SECURITY_ASSIGNED_BY" VARCHAR2(8 BYTE),
    "PASSWORD_EXPIRATION_DATE" DATE,
    "STATUS_CODE" NUMBER(2,0),
    "ACCOUNT_LOCKED" VARCHAR2(1 BYTE),
    "UPDATE_PASS_ON_SIGNON" VARCHAR2(1 BYTE),
    "USER_EMAIL" VARCHAR2(30 BYTE))

Please note that the DDL, Stored Procedures and VB.Net code was left from a previous developer. I am replacing the Microsoft's implementation of Oracle's driver to ODP.Net. There is literally no change in code other than this.

Body:
Keep your database objects local to the method where they are used. That way you can control when they are closed and disposed. Connections and commands may contain unmanaged code which needs to be released by their respective .Dispose methods. In this example a Using...End Using block handles this for you even if there is an error.

I am not sure why you are creating the stored procedure again when you state that is is already in Oracle.

Your do quite a dance with the parameters creating an array of parameters then assigning values to the array elements. The Parameter.Add method automatically adds the parameter to the Parameters Collection. You are using named parameters but you are not using the proper names. To avoid this problem just use positional parameters.

Now we get to the actual .Execute. .ExecuteScalar returns the first column of the first row of the result set. I don't think you can refer to your Out parameter in this scenario. Without a cursor in the stored procedure I am not sure any result set is returned.

Try an .ExecuteNonQuery and then retrieve the parameter value. Notice that my database objects are closed and disposed by the End Using before I start checking the returned value.

I cannot test this because I don't have an installation of Oracle hanging around.

Public Function Get_A_Users_Email(ByVal strEmpId As String) As String
    Dim retVal As Object
    Using cn As New OracleConnection("Your connection string"),
            cmd As New OracleCommand("JOHN.GET_USERS_EMAIL", cn)
        cmd.BindByName = True
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("User_Email_P", OracleDbType.Varchar2, ParameterDirection.Output)
        cmd.Parameters.Add("Employee_P", OracleDbType.Varchar2, UCase(strEmpId.Trim()), ParameterDirection.Input)
        cn.Open()
        cmd.ExecuteNonQuery()
        retVal = cmd.Parameters("User_Email_P").Value
    End Using
    Dim returnString As String
    If retVal Is Nothing Then
        returnString = ""
    Else
        returnString = retVal.ToString
    End If
    Return returnString
End Function


问:
How to validate the date received in the response in Karate BDD
I have two fields in the response having two parameters in response.
{
date1: "18-12-2018",
date2: "23-11-2018"
}

i want to test id date1 is less than today's date
and date2 is less than some otherdate in request param.
I dont know how this i can perform in karate schema validation

答:
As an addendum to Peter Thomas's answer.  Here is how I externalized it into a callable .feature file:

```<code>@ignore
Feature: Reusable function to capture info about the date

  # Example:
  # * def dateResponse = call read('classpath:features/test_getdate.feature')
  # * def todaysDate = dateResponse.today
  # * def lastYearDate = dateResponse.oneYearAgo

  Background: Setup
    * def pattern = 'MM/dd/yyyy'
    * def getDate =
      """
      function() {
        var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
        var sdf = new SimpleDateFormat(pattern);
        var date = new java.util.Date();
        return sdf.format(date);
      }
      """

  Scenario: Capture todays date
    * def today = getDate()
    * karate.log("Today's date is: " + today )

  Scenario: Capture a year old date
    * def today = getDate()
    * def getSubtractedYear =
      """
      function(s) {
        var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
        var LocalDate = Java.type("java.time.LocalDate");
        var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
        var dtf = DateTimeFormatter.ofPattern(pattern);
        try {
          var adj = LocalDate.parse(today, dtf).minusMonths(12);
          return dtf.format(adj);
        } catch(e) {
          karate.log('*** date parse error: ', s);
        }
      }
      """
    * def oneYearAgo = getSubtractedYear()
    * karate.log("One year ago is: " + oneYearAgo)
</code>```

Then I test it like so:

```<code>@mysuite
Feature: Get information about the date

  Background: Setup
    * def dateResponse = call read('classpath:features/test_getdate.feature')

  Scenario: Extract todays date
    * def todaysDate = dateResponse.today
    * karate.log("Captured todays date: " + todaysDate)

  Scenario: Extract last years date
    * def lastYearDate = dateResponse.oneYearAgo
    * karate.log("Captured last years date: " + lastYearDate)
</code>```

Body:
As an addendum to Peter Thomas's answer.  Here is how I externalized it into a callable .feature file:

@ignore
Feature: Reusable function to capture info about the date

  # Example:
  # * def dateResponse = call read('classpath:features/test_getdate.feature')
  # * def todaysDate = dateResponse.today
  # * def lastYearDate = dateResponse.oneYearAgo

  Background: Setup
    * def pattern = 'MM/dd/yyyy'
    * def getDate =
      """
      function() {
        var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
        var sdf = new SimpleDateFormat(pattern);
        var date = new java.util.Date();
        return sdf.format(date);
      }
      """

  Scenario: Capture todays date
    * def today = getDate()
    * karate.log("Today's date is: " + today )

  Scenario: Capture a year old date
    * def today = getDate()
    * def getSubtractedYear =
      """
      function(s) {
        var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
        var LocalDate = Java.type("java.time.LocalDate");
        var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
        var dtf = DateTimeFormatter.ofPattern(pattern);
        try {
          var adj = LocalDate.parse(today, dtf).minusMonths(12);
          return dtf.format(adj);
        } catch(e) {
          karate.log('*** date parse error: ', s);
        }
      }
      """
    * def oneYearAgo = getSubtractedYear()
    * karate.log("One year ago is: " + oneYearAgo)

Then I test it like so:

@mysuite
Feature: Get information about the date

  Background: Setup
    * def dateResponse = call read('classpath:features/test_getdate.feature')

  Scenario: Extract todays date
    * def todaysDate = dateResponse.today
    * karate.log("Captured todays date: " + todaysDate)

  Scenario: Extract last years date
    * def lastYearDate = dateResponse.oneYearAgo
    * karate.log("Captured last years date: " + lastYearDate)


问:
Evaluate the TensorFlow object detection model
How can I evaluate my object detection model in a simple and understandable way, I used the TensorFlow's Object Detection API, but I didn’t understand the Tensorboard graphs. Can I evaluate it manually?
Any help? :( </p>

答:
Welcome to StackOverflow!
In short, yes you can. Yet it could be quite time-consuming to achieve your goal.
Here are the steps you might want to follow(assuming you have some basic understanding of Tensorflow graphs and sessions, otherwise please update your question):

Export your model to a frozen graph(*.pb file) via HERE. This step will give you an out-of-the-box model that you could load without any dependencies of Object Detection API.

Write a script to load your model(frozen graph) and perform the evaluation. Some instructions can be found from HERE. Make sure you use tools such as Netron to check the input and output node names of your frozen graph.

Once you could perform the evaluation, you could write metrics on your own dataset, such as mAP, and loop through all images to get the desired evaluation performed.


问:
Pattern matching a non-exceptional value using try-catch expression
I have a question regarding the try catch block .Here is an example :

```<code>val num = try {
  110 / 12
} catch {
  case ex: NumberFormatException => 0
}

val num1 = try {
  110 / 13
} catch {
  case a: num1 > 10 => 10
  case b: num1 < 10 => 12
}
</code>```

I know num works so why is num1 not valid? All the examples and articles I've seen only do the NumberFormatException or ArithmenticException. And also are greater than and less than not valid operators in the case statement? Is it possible to treat the try catch block like an if else block using pattern matching?

答:
Supplementing the other answer, if you itch to have a tidy list of cases:</p>

```<code>scala> import util._
import util._

scala> Try(1/0) match {
     | case Success(i) if i > 42            => 42
     | case ok @ Success(_)                 => ok
     | case Failure(_: ArithmeticException) => 27
     | }
res0: Int = 27

</code>```

Body:
I have a question regarding the try catch block .Here is an example :

val num = try {
  110 / 12
} catch {
  case ex: NumberFormatException => 0
}

val num1 = try {
  110 / 13
} catch {
  case a: num1 > 10 => 10
  case b: num1 < 10 => 12
}

I know num works so why is num1 not valid? All the examples and articles I've seen only do the NumberFormatException or ArithmenticException. And also are greater than and less than not valid operators in the case statement? Is it possible to treat the try catch block like an if else block using pattern matching?

Body:
Supplementing the other answer, if you itch to have a tidy list of cases:

scala> import util._
import util._

scala> Try(1/0) match {
     | case Success(i) if i > 42            => 42
     | case ok @ Success(_)                 => ok
     | case Failure(_: ArithmeticException) => 27
     | }
res0: Int = 27


问:
How to find JS Memory Leaks?
I have struggled around with the heap profiler in chrome but it is very confusing. Especially if there are minimized libraries inside. But even the DOMElements views, elements which may not be removed are very unclear presented.

Are there any tips how to use the heap dump in chrome to find JS code that leads to memory leaks, code that cannot be cleaned by GC... and how to find elements messing around even if removed from dom?

In other words, how to read heap dump in chrome correctly? Dominators View? Comparison?

答:
I don't see mentioned window.performance.memory, which gives you the run-time ability to monitor and take action based on memory usage.

```<code>window.performance.memory:

MemoryInfo {
  totalJSHeapSize: 7084834,
  usedJSHeapSize: 6486770,
  jsHeapSizeLimit: 4294705152
}
</code>```

For a handy percentage, use this:

```<code>window.performance.memory.usedJSHeapSize / window.performance.memory.jsHeapSizeLimit
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory

ContentLicense: CC BY-SA 3.0

Title: How to find JS Memory Leaks?

Body:
I don't see mentioned window.performance.memory, which gives you the run-time ability to monitor and take action based on memory usage.

window.performance.memory:

MemoryInfo {
  totalJSHeapSize: 7084834,
  usedJSHeapSize: 6486770,
  jsHeapSizeLimit: 4294705152
}

For a handy percentage, use this:

window.performance.memory.usedJSHeapSize / window.performance.memory.jsHeapSizeLimit

https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory


问:
How to access listview items generated by arrayadapter
I have tied my application to Firebase database and after being able to display them I also want to be able to select them and access their textview values. However .getValue() does not work for views. I know that my code is very messy and my selector is only working one way, but can you help me to find out what is going on. I will add a screenshot to make things more clear. At the moment when clicking on one of the items int num = Integer.parseInt(text) gives an error and the app will crash because the value I get from view is "Android.widget...", not what I want to get.
Screenshot pic:

Orders.java

```<code>public class Orders extends ActionBarActivity {
    public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";

// Declare the UI components
    private ListView foodList;

    // Declare an ArrayAdapter that we use to join the data set and the ListView
    // is the way of type safe, means you only can pass Strings to this array
    //Anyway ArrayAdapter supports only TextView
    private ArrayAdapter arrayAdapter;

    private Firebase ref;
    private Orders activ;
    private ArrayList<String> dishes;
    public int total;

@Override
protected void onCreate(Bundle savedInstanceState) {
    activ = this;
    dishes = new ArrayList<String>(20);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_orders);

 // Initialize the UI components
    foodList = (ListView)findViewById(R.id.listView1);

    // Create a reference to a Firebase location
    ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");

    // Read data and react to changes
    ref.addChildEventListener(new ChildEventListener() {
          @Override
          public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
            Map s = snapshot.getValue(Map.class);
            dishes.add(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }

          @Override public void onChildRemoved(DataSnapshot snapshot) {
            Map s = snapshot.getValue(Map.class);
            dishes.remove(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }

          @Override
          public void onCancelled(FirebaseError arg0) { }
    });

    foodList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            view.setBackgroundColor(Color.GREEN);
            String text = view.toString();
            text.replaceAll("[^\\d.]", "");
            int num = Integer.parseInt(text);
            total += num;
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.orders, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void toPayment(View view) {
    Intent pay = new Intent(this, PaymentMethod.class);
    pay.putExtra(TOTAL_SUM, total);
    startActivity(pay);
}

}
</code>```

答:
I know this might become a little too late but, hope this
helps someone who was looking for similar solution to Custom ArrayAdapter with multiple values.</p>

```<code>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            ListItems item = (ListItems) parent.getItemAtPosition(position);
            System.out.println("Item: "+item.getName());
        }
    });
</code>```

Body:
I have tied my application to Firebase database and after being able to display them I also want to be able to select them and access their textview values. However .getValue() does not work for views. I know that my code is very messy and my selector is only working one way, but can you help me to find out what is going on. I will add a screenshot to make things more clear. At the moment when clicking on one of the items int num = Integer.parseInt(text) gives an error and the app will crash because the value I get from view is "Android.widget...", not what I want to get.
Screenshot pic:

Orders.java

public class Orders extends ActionBarActivity {
    public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";

// Declare the UI components
    private ListView foodList;

    // Declare an ArrayAdapter that we use to join the data set and the ListView
    // is the way of type safe, means you only can pass Strings to this array
    //Anyway ArrayAdapter supports only TextView
    private ArrayAdapter arrayAdapter;

    private Firebase ref;
    private Orders activ;
    private ArrayList<String> dishes;
    public int total;

@Override
protected void onCreate(Bundle savedInstanceState) {
    activ = this;
    dishes = new ArrayList<String>(20);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_orders);

 // Initialize the UI components
    foodList = (ListView)findViewById(R.id.listView1);

    // Create a reference to a Firebase location
    ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");

    // Read data and react to changes
    ref.addChildEventListener(new ChildEventListener() {
          @Override
          public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
            Map s = snapshot.getValue(Map.class);
            dishes.add(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }

          @Override public void onChildRemoved(DataSnapshot snapshot) {
            Map s = snapshot.getValue(Map.class);
            dishes.remove(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }

          @Override
          public void onCancelled(FirebaseError arg0) { }
    });

    foodList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            view.setBackgroundColor(Color.GREEN);
            String text = view.toString();
            text.replaceAll("[^\\d.]", "");
            int num = Integer.parseInt(text);
            total += num;
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.orders, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void toPayment(View view) {
    Intent pay = new Intent(this, PaymentMethod.class);
    pay.putExtra(TOTAL_SUM, total);
    startActivity(pay);
}

}

Body:
I know this might become a little too late but, hope this
helps someone who was looking for similar solution to Custom ArrayAdapter with multiple values.

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            ListItems item = (ListItems) parent.getItemAtPosition(position);
            System.out.println("Item: "+item.getName());
        }
    });


问:
Can anyone tell me how to hide the contents of a text box
I have a drop down button named bank.
I have 3 text boxes named t1, t2 and t3
if i am not selecting any of the banks all the three text boxes should be enabled..

am getting it..
but my problem is..

first i have selected any one from the drop down button, and after some time i have changed it to choose bank(i.e; the 0th index).. but even then the data in text boxes are still there itself.. how to hide it..

答:
You can't "hide" the text in a text box. You either disable the textbox, clear the textbox's text, or hide the darn thing. In your case I would add 3 blank textboxes that are invisible. when you select bank hide the real textboxes and show the three 'fake' textboxes that are blank and disabled/locked.

My Javascript syntax is horrible, so here is a jQuery Example.


问:
I can't start server PostgreSQL 11: "pg_ctl: could not start server"
I am in CentOS Linux release 7.5.1804 (Core)

When I login as postgres and run:

```<code>bash-4.2$ /usr/pgsql-11/bin/initdb -D /var/lib/pgsql/11/data
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /var/lib/pgsql/11/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/pgsql-11/bin/pg_ctl -D /var/lib/pgsql/11/data -l logfile start

bash-4.2$
</code>```

then I run

```<code>bash-4.2$ /usr/pgsql-11/bin/pg_ctl start -l logfile -D /var/lib/pgsql/11/data
waiting for server to start..../bin/sh: logfile: Permission denied
 stopped waiting
pg_ctl: could not start server
Examine the log output.
bash-4.2$ date
Wed Oct 24 01:50:44 -05 2018
bash-4.2$
</code>```

I search in GOOGLE for "waiting for server to start..../bin/sh: logfile: Permission denied" but this error only happened in MAC and no solutions is displayed...

Also I run

```<code>bash-4.2$ postgres --version;postmaster --version;
postgres (PostgreSQL) 11.0
postgres (PostgreSQL) 11.0
bash-4.2$
</code>```

then I believe PostgreSQL 11 is fine installed, but I can't start server.

I install with this line:

```<code>yum install postgresql-jdbc.noarch postgresql-jdbc-javadoc.noarch postgresql-unit11.x86_64 postgresql-unit11-debuginfo.x86_64 postgresql11.x86_64 postgresql11-contrib.x86_64 postgresql11-debuginfo.x86_64 postgresql11-devel.x86_64 postgresql11-docs.x86_64 postgresql11-libs.x86_64 postgresql11-odbc.x86_64 postgresql11-plperl.x86_64 postgresql11-plpython.x86_64 postgresql11-pltcl.x86_64 postgresql11-server.x86_64 postgresql11-tcl.x86_64 postgresql11-test.x86_64
</code>```

I didn't add [postgresql11-llvmjit.x86_64] because this requires many dependences.

CentOS Linux release 7.5.1804 + PostgreSQL 11 ?

Do I need install aditional software?

答:
So, I faced the same issue.
 First I checked for if and what all servers were active on my machine using :

```<code>brew services list
</code>```

Then I had some servers active so I stopped them as you need to stop them for posgresql server to work.

```<code>brew services stop < name of the server/s active >
</code>```

Then I created a new database

```<code>initdb /usr/local/var/postgres2
</code>```

and started the server using

```<code> pg_ctl -D /usr/local/var/postgres2 -l logfile start
</code>```

Worked fine for me !!
enter image description here

Body:
I am in CentOS Linux release 7.5.1804 (Core)

When I login as postgres and run:

bash-4.2$ /usr/pgsql-11/bin/initdb -D /var/lib/pgsql/11/data
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /var/lib/pgsql/11/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/pgsql-11/bin/pg_ctl -D /var/lib/pgsql/11/data -l logfile start

bash-4.2$

then I run

bash-4.2$ /usr/pgsql-11/bin/pg_ctl start -l logfile -D /var/lib/pgsql/11/data
waiting for server to start..../bin/sh: logfile: Permission denied
 stopped waiting
pg_ctl: could not start server
Examine the log output.
bash-4.2$ date
Wed Oct 24 01:50:44 -05 2018
bash-4.2$

I search in GOOGLE for "waiting for server to start..../bin/sh: logfile: Permission denied" but this error only happened in MAC and no solutions is displayed...

Also I run

bash-4.2$ postgres --version;postmaster --version;
postgres (PostgreSQL) 11.0
postgres (PostgreSQL) 11.0
bash-4.2$

then I believe PostgreSQL 11 is fine installed, but I can't start server.

I install with this line:

yum install postgresql-jdbc.noarch postgresql-jdbc-javadoc.noarch postgresql-unit11.x86_64 postgresql-unit11-debuginfo.x86_64 postgresql11.x86_64 postgresql11-contrib.x86_64 postgresql11-debuginfo.x86_64 postgresql11-devel.x86_64 postgresql11-docs.x86_64 postgresql11-libs.x86_64 postgresql11-odbc.x86_64 postgresql11-plperl.x86_64 postgresql11-plpython.x86_64 postgresql11-pltcl.x86_64 postgresql11-server.x86_64 postgresql11-tcl.x86_64 postgresql11-test.x86_64

I didn't add [postgresql11-llvmjit.x86_64] because this requires many dependences.

CentOS Linux release 7.5.1804 + PostgreSQL 11 ?

Do I need install aditional software?

Body:
So, I faced the same issue.
 First I checked for if and what all servers were active on my machine using :

brew services list

Then I had some servers active so I stopped them as you need to stop them for posgresql server to work.

brew services stop < name of the server/s active >

Then I created a new database

initdb /usr/local/var/postgres2

and started the server using

 pg_ctl -D /usr/local/var/postgres2 -l logfile start

Worked fine for me !!
enter image description here


问:
Unable to setup DKIM TXT-Value as DNS-Record
I have a domain name which DNS is edited via Google Cloud DNS. And I have a Google Apps for Work Account with that domain name.

I wanted to set up DKIM-authentication but when I try to save the corresponding TXT-Record I get the error that the Tag is invalid.

I did the same before and it worked perfectly. I checked the old setup and I saw that the old DKIM-record was about half the length. The new one seems to be too long for a TXT-record in the Google Cloud Platform.

Does anyone have a solution?

答:
How to easily add DKIM as TXT in GCP Cloud DNS:

copy/paste the entire DKIM string into the TXT field

ignore the ...this domain has whitespace but is not a quoted string... related GCP warning you may see

before you save it, insert a single space in the middle of the DKIM p= value string.

That's it.

This approach was tested with Mailgun and a domain name configured in Google Cloud DNS.

Additional notes:

GCP will automatically add double quotes around each space separated string after you save

you need to separate the p= string in such a way so that no resulting double quoted string created after you save is longer than 255 characters

example (before):

```<code>k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82yBC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB
</code>```

example (after):

```<code>k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB
</code>```

Scroll to the right and you'll see the newly added space - this produces three space separated strings, each less than 255 characters:

k=rsa;

p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y

BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB

example (after, viewed via DIG):

```<code>;; ANSWER SECTION:
dkim.example.com.   300 IN  TXT "k=rsa;" "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y" "BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB"
</code>```

Ref:
DKIM TXT record value invalid, cloud-dns-discuss group message

Body:
How to easily add DKIM as TXT in GCP Cloud DNS:

copy/paste the entire DKIM string into the TXT field

ignore the ...this domain has whitespace but is not a quoted string... related GCP warning you may see

before you save it, insert a single space in the middle of the DKIM p= value string.

That's it.

This approach was tested with Mailgun and a domain name configured in Google Cloud DNS.

Additional notes:

GCP will automatically add double quotes around each space separated string after you save

you need to separate the p= string in such a way so that no resulting double quoted string created after you save is longer than 255 characters

example (before):

k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82yBC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB

example (after):

k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB

Scroll to the right and you'll see the newly added space - this produces three space separated strings, each less than 255 characters:

k=rsa;

p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y

BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB

example (after, viewed via DIG):

;; ANSWER SECTION:
dkim.example.com.   300 IN  TXT "k=rsa;" "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlTtO1qRFaK955gz16Y8c1EMCqtaT4exCrwfor2yT438ZVjrUcqo2tPUNR4eqkD+xcKRQnWSw931uVUY6YJWtOrgrXTIrHnTkf5Xtg+jaXr0OhjdeVDIG/Le7oOVWncMf+9J4ZSRybOpb+XZPp/JLjis6pmCLrt5j82y" "BC9DCbsEPSOVVOC1mr5lq8irQs+qAv6M/DnjNcUrdiRBJyNrs2lfuvfs8BFceZAk1AwcVBcYCmZl5OkxZBn8liTC34FPJLLHm6jMp9+c0OaEtxo8zr3QX0ZYEWC3XqZ/p9fo4Pcg+fpyjee79wBVqUzhVAWdzE5+qAIn4e1Dmslyb6IX4mwIDAQAB"

Ref:
DKIM TXT record value invalid, cloud-dns-discuss group message


问:
Django DetailView filter by two parameters not using the primary key
I need to filter a model by two values that none of them is the PK of the model.

I want to filter the payments for an specific car and week, this means that I can have more than one payment for a car and in a week.

I'm using Django-Tables2 to display the results.

views.py

```<code>class PagosDetailView(SingleTableMixin, DetailView):

    template_name = "AC/paymentsbycarandweek.html"
    context_table_name = 'table'
    model = Pagos
    table_class = PagosTable
    slug_url_kwarg = 'carro_id'

    def get_queryset(self):
        qs = super(PagosDetailView, self).get_queryset()
        return qs.filter(carro=self.kwargs['carro'], semana=self.kwargs['semana'])
</code>```

models.py

```<code>class Pagos(models.Model):

    carro = models.ForeignKey(
        Carros, on_delete=models.CASCADE, blank=False, null=False)
    pago = models.DecimalField(max_digits=6, decimal_places=2)
    fecha = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    semana = models.CharField(max_length=20)
    startweek = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    endweek = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    renta = models.ForeignKey(
        Renta, on_delete=models.PROTECT, blank=False, null=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Pagos"

    def get_absolute_url(self):
        return reverse('pagos')

    def __str__(self):
        return self.semana
</code>```

urls.py

```<code>path('paymentsbycarandweek/<int:carro>/<slug:semana>',
         views.PagosDetailView.as_view(), name='pagos_bycar')
</code>```

This last time that I have tried several options, I'm getting the following error message:

Generic detail view PagosDetailView must be called with either an object pk or a slug in the URLconf.

How exactly can I pass these two parameters?

答:
After searching a lot, this is how I finally resolved it:</p>

```<code>class PagosDetailView(SingleTableMixin, ListView):

    model = Pagos
    table_class = PagosDetailTable
    template_name = 'AC/paymentsbycarandweek.html'
    paginate_by = 10

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        self.object_list = self.object_list.filter(
            carro=kwargs['carro'], semana=kwargs['semana'])

        context = self.get_context_data()
    return self.render_to_response(context)
</code>```

Body:
I need to filter a model by two values that none of them is the PK of the model.

I want to filter the payments for an specific car and week, this means that I can have more than one payment for a car and in a week.

I'm using Django-Tables2 to display the results.

views.py

class PagosDetailView(SingleTableMixin, DetailView):

    template_name = "AC/paymentsbycarandweek.html"
    context_table_name = 'table'
    model = Pagos
    table_class = PagosTable
    slug_url_kwarg = 'carro_id'

    def get_queryset(self):
        qs = super(PagosDetailView, self).get_queryset()
        return qs.filter(carro=self.kwargs['carro'], semana=self.kwargs['semana'])

models.py

class Pagos(models.Model):

    carro = models.ForeignKey(
        Carros, on_delete=models.CASCADE, blank=False, null=False)
    pago = models.DecimalField(max_digits=6, decimal_places=2)
    fecha = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    semana = models.CharField(max_length=20)
    startweek = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    endweek = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    renta = models.ForeignKey(
        Renta, on_delete=models.PROTECT, blank=False, null=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Pagos"

    def get_absolute_url(self):
        return reverse('pagos')

    def __str__(self):
        return self.semana

urls.py

path('paymentsbycarandweek/<int:carro>/<slug:semana>',
         views.PagosDetailView.as_view(), name='pagos_bycar')

This last time that I have tried several options, I'm getting the following error message:

Generic detail view PagosDetailView must be called with either an object pk or a slug in the URLconf.

How exactly can I pass these two parameters?

Body:
After searching a lot, this is how I finally resolved it:

class PagosDetailView(SingleTableMixin, ListView):

    model = Pagos
    table_class = PagosDetailTable
    template_name = 'AC/paymentsbycarandweek.html'
    paginate_by = 10

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        self.object_list = self.object_list.filter(
            carro=kwargs['carro'], semana=kwargs['semana'])

        context = self.get_context_data()
    return self.render_to_response(context)


问:
Java: runtime method resolution
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

```<code>package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}
</code>```

答: You may want to read this blog post and check out ClassMate. It should do most of the grungy work for you.</p>

Title: Java: runtime method resolution

Body:
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}


问:
error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class
First time using firestore and I'm getting this error. It seems to be a problem with Ivy, from my research. I don't have a lot of experience modifying tsconfig.app.json, which is the direction I've been pointed to, following other answers.

The only thing I was able to modify from the original project was to use Angular Fire 6 instead of 5, which I had done initially to follow a tutorial.

Here's package.json:

{
  "name": "language",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "^9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/fire": "^6.0.0-rc.1",
    "@angular/flex-layout": "^9.0.0-beta.29",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "firebase": "^7.8.2",
    "rxjs": "~6.5.4",
    "rxjs-compat": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5",
    "@angular-devkit/architect": "^0.900.0-0 || ^0.900.0",
    "firebase-tools": "^7.12.1",
    "fuzzy": "^0.1.3",
    "inquirer": "^6.2.2",
    "inquirer-autocomplete-prompt": "^1.0.1"
  }
}
```
<p>angular.json</p>
<pre class="lang-json prettyprint-override"><code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "language": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/language",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "language:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "language:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "language:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "language:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "language:serve:production"
            }
          }
        },
        "deploy": {
          "builder": "@angular/fire:deploy",
          "options": {}
        }
      }
    }
  },
  "defaultProject": "language"
}
</code>```

tsconfig.app.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],

  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
```

Thanks!

答:
Fixed it by opting out of Ivy as per documentation.

https://angular.io/guide/ivy

Change tsconfig.app.json to opt out of Ivy.

```<code>"enableIvy": false
</code>```

Body:
First time using firestore and I'm getting this error. It seems to be a problem with Ivy, from my research. I don't have a lot of experience modifying tsconfig.app.json, which is the direction I've been pointed to, following other answers.

The only thing I was able to modify from the original project was to use Angular Fire 6 instead of 5, which I had done initially to follow a tutorial.

Here's package.json:

{
  "name": "language",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "^9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/fire": "^6.0.0-rc.1",
    "@angular/flex-layout": "^9.0.0-beta.29",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "firebase": "^7.8.2",
    "rxjs": "~6.5.4",
    "rxjs-compat": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5",
    "@angular-devkit/architect": "^0.900.0-0 || ^0.900.0",
    "firebase-tools": "^7.12.1",
    "fuzzy": "^0.1.3",
    "inquirer": "^6.2.2",
    "inquirer-autocomplete-prompt": "^1.0.1"
  }
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "language": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/language",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "language:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "language:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "language:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "language:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "language:serve:production"
            }
          }
        },
        "deploy": {
          "builder": "@angular/fire:deploy",
          "options": {}
        }
      }
    }
  },
  "defaultProject": "language"
}

tsconfig.app.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],

  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}

Thanks!

Body:
Fixed it by opting out of Ivy as per documentation.

https://angular.io/guide/ivy

Change tsconfig.app.json to opt out of Ivy.

"enableIvy": false


问:
Use absolute values not relative values in scale_fill_gradientn
I would like a smooth gradient starting from red at 0 to white at 0.5 to green at 1.

My data doesn't cover this full range, and it seems scale_fill_gradientn takes the values argument to be relative to the data, rather than their actual values.

The plot produced below shows white above 0.5 rather than at 0.5. How can I correct this and set the gradient limits to the specific values I write, rather than relative to the data?

```<code>library(tidyverse)
set.seed(1)
expand_grid(x=1:10, y=1:10) %>%
  mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = val)) +
  geom_text(aes(label = round(val, 3))) +
  scale_fill_gradientn(colours = c("red","white","green"),
                       values = scales::rescale(c(0.0, 0.5, 1.0)))
</code>```

答:
You just need to set the limits parameter of scale_fill_gradientn:

library(tidyverse)
set.seed(1)
expand_grid(x=1:10, y=1:10) %>%
  mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = val)) +
  geom_text(aes(label = round(val, 3))) +
  scale_fill_gradientn(colours = c("red","white","green"),
                      limits = c(0.0, 1.0))
```

Created on 2020-02-18 by the reprex package (v0.3.0)

Body:
I would like a smooth gradient starting from red at 0 to white at 0.5 to green at 1.

My data doesn't cover this full range, and it seems scale_fill_gradientn takes the values argument to be relative to the data, rather than their actual values.

The plot produced below shows white above 0.5 rather than at 0.5. How can I correct this and set the gradient limits to the specific values I write, rather than relative to the data?

library(tidyverse)
set.seed(1)
expand_grid(x=1:10, y=1:10) %>%
  mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = val)) +
  geom_text(aes(label = round(val, 3))) +
  scale_fill_gradientn(colours = c("red","white","green"),
                       values = scales::rescale(c(0.0, 0.5, 1.0)))

Body:
You just need to set the limits parameter of scale_fill_gradientn:

library(tidyverse)
set.seed(1)
expand_grid(x=1:10, y=1:10) %>%
  mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = val)) +
  geom_text(aes(label = round(val, 3))) +
  scale_fill_gradientn(colours = c("red","white","green"),
                      limits = c(0.0, 1.0))

Created on 2020-02-18 by the reprex package (v0.3.0)


问:
Is it possible to use package semPlot with R 3.6.2?
I upgraded R to version 3.6.2 and have discovered that package semPlot will not work. It installs without any problems, but when I try to load it I get the message,

Error: package or namespace load failed for ‘semPlot’ in
  loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck =
  vI[[j]]):  there is no package called ‘ggm’

I then tried to install ggm but get the following warning and error:

Warning in install.packages : dependency ‘graph’ is not available

There is a binary version available but the source version is
  later:
      binary source needs_compilation ggm    2.3    2.5             FALSE installing the source package ‘ggm’ trying URL
  'https://cran.rstudio.com/src/contrib/ggm_2.5.tar.gz' Content type
  'application/x-gzip' length 109414 bytes (106 KB) downloaded 106 KB

ERROR: dependency ‘graph’ is not available for package ‘ggm’  removing
  ‘/Library/Frameworks/R.framework/Versions/3.6/Resources/library/ggm’
  Warning in install.packages : installation of package ‘ggm’ had
  non-zero exit status"

I then tried to install graph, but it says:

package ‘graph’ is not available (for R version 3.6.2).

I wondered if anyone else had experienced this problem, and had any solutions so I can load semPlot with R 3.6.2?

Many thanks.

答:
I also have R 3.6.2 and get all errors you get. But when I try to install the semPlot package from GitHub, it works fine, as follows:

```<code>install.packages('devtools')
library(devtools)

install_github('SachaEpskamp/semPlot',  dependencies = T)
library(semPlot)
</code>```

Please not that I tried the cran/semPlot repository but didn't work for me, whereas SachaEpskamp/semPlot does.

Hope you get it working.

Body:
I also have R 3.6.2 and get all errors you get. But when I try to install the semPlot package from GitHub, it works fine, as follows:

install.packages('devtools')
library(devtools)

install_github('SachaEpskamp/semPlot',  dependencies = T)
library(semPlot)

Please not that I tried the cran/semPlot repository but didn't work for me, whereas SachaEpskamp/semPlot does.

Hope you get it working.


问:
If cell is 5 long add 0 prefix , else leave as is, loop
We have Serial Numbers that have to be reviewed and some of them are 5 digits long but in the database have a 0 prefix, which of course they don't have in the format we receive. So using bits and pieces of other VBA I've got the below, which loops and changes nothing.

What am I missing/doing wrong?

```<code>Sub SNoReview()

    Dim METER                   As String
    Dim SQL_STRING              As String
    Dim ANSWER                  As String
    Dim CELLADDRESS             As Variant

    Application.ScreenUpdating = True
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Sheets("Sheet1").Activate
    Range("N6").Select

    Do Until IsEmpty(ActiveCell)

        CELLADDRESS = ActiveCell.Address
        METER = ActiveCell.Value

        If Len(METER) = 5 Then
            METER = "0" & (METER)
        Else: METER = (METER)
        End If

        ActiveCell.Offset(1, 0).Select

    Loop

End Sub
</code>```

答:
Seems like you could just apply a single Number Format to the entire range all at once. No need to loop here.

```<code>Sub sNoReview()

    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Range("N6:N" & ws.Range("N" & ws.Rows.Count).End(xlUp).Row).NumberFormat = "000000"

End Sub
</code>```

This will not change the format of any number that has LEN > 6

```<code>000001 From 1
000011 From 11
000111 From 111
001111 From 1111
011111 From 11111
111111 From 111111
</code>```

Your Code

The reason your macro is not working is because you never changed the format. The default of excel is to drop leading 0's so your code was adding them only for them to be removed by excel right after. Gotcha moment for sure.

Body:
We have Serial Numbers that have to be reviewed and some of them are 5 digits long but in the database have a 0 prefix, which of course they don't have in the format we receive. So using bits and pieces of other VBA I've got the below, which loops and changes nothing.

What am I missing/doing wrong?

Sub SNoReview()

    Dim METER                   As String
    Dim SQL_STRING              As String
    Dim ANSWER                  As String
    Dim CELLADDRESS             As Variant

    Application.ScreenUpdating = True
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Sheets("Sheet1").Activate
    Range("N6").Select

    Do Until IsEmpty(ActiveCell)

        CELLADDRESS = ActiveCell.Address
        METER = ActiveCell.Value

        If Len(METER) = 5 Then
            METER = "0" & (METER)
        Else: METER = (METER)
        End If

        ActiveCell.Offset(1, 0).Select

    Loop

End Sub

Body:
Seems like you could just apply a single Number Format to the entire range all at once. No need to loop here.

Sub sNoReview()

    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Range("N6:N" & ws.Range("N" & ws.Rows.Count).End(xlUp).Row).NumberFormat = "000000"

End Sub

This will not change the format of any number that has LEN > 6

000001 From 1
000011 From 11
000111 From 111
001111 From 1111
011111 From 11111
111111 From 111111

Your Code

The reason your macro is not working is because you never changed the format. The default of excel is to drop leading 0's so your code was adding them only for them to be removed by excel right after. Gotcha moment for sure.