问:
C# Soap Client Not Populating All Elements from the Response
Hi I'm working on a simple c# console application to fetch information from a Java JAX-WS Service. I've gotten my app to call the service and get information back but for some reason the response doesn't populate all of the attributes. I've verified that everything I'm expecting is coming back in the response and I don't think I've got a namespace issue like the other questions I've looked over so far.

Here is my actual Soap Response and I'm getting fileDate populated just fine but fileName is always null.

```<code><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:getExtractDateResponse xmlns:ns2="http://endpoint.data_extracts_ws.example.com/">
         <dataExtractDateModel>
            <fileDate>2015-09-17T00:00:00-05:00</fileDate>
            <fileName>export_file.zip</fileName>
         </dataExtractDateModel>
      </ns2:getExtractDateResponse>
   </S:Body>
</S:Envelope>
</code>```

Here is my console app

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExtractsServiceClient.DataExtractsService;

namespace DataExtractsServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            DataExtractsEndpointClient extractService = new DataExtractsEndpointClient();
            extractService.ClientCredentials.UserName.UserName = "my_username";
            extractService.ClientCredentials.UserName.Password = "my_password";
            DataExtractDateModel extractDateModel = extractService.getExtractDate("EXTRACT_NAME");
            System.Console.WriteLine("File Name Is " + extractDateModel.fileName);
            System.Console.WriteLine("File Date Is " + extractDateModel.fileDate);
            System.Console.WriteLine("Finished");
            System.Console.ReadLine();
        }
    }
}
</code>```

And the App.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <system.serviceModel>
        <bindings>
            <customBinding>
                <binding name="DataExtractsEndpointPortBinding">
                    <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'http://endpoint.data_extracts_ws.example.com/':    -->
                    <!--    <wsdl:binding name='DataExtractsEndpointPortBinding'>    -->
                    <!--        <wsoma:OptimizedMimeSerialization xmlns:wsoma="http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization">..</wsoma:OptimizedMimeSerialization>    -->
                    <mtomMessageEncoding messageVersion="Soap11" />
                    <httpsTransport authenticationScheme="Basic"/>
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="https://example.com/data_extracts_ws/DataExtractsEndpointService"
                binding="customBinding" bindingConfiguration="DataExtractsEndpointPortBinding"
                contract="DataExtractsService.DataExtractsEndpoint" name="DataExtractsEndpointPort" />
        </client>
    </system.serviceModel>
</configuration>
</code>```

Adding the XSD and WSDL

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://endpoint.data_extracts_ws.example.com/" targetNamespace="http://endpoint.data_extracts_ws.example.com/" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="ExtractException" type="tns:ExtractException" />
  <xs:element name="ExtractNotFoundException" type="tns:ExtractNotFoundException" />
  <xs:element name="getExtract" type="tns:getExtract" />
  <xs:element name="getExtractDate" type="tns:getExtractDate" />
  <xs:element name="getExtractDateResponse" type="tns:getExtractDateResponse" />
  <xs:element name="getExtractResponse" type="tns:getExtractResponse" />
  <xs:complexType name="ExtractException">
    <xs:sequence>
      <xs:element minOccurs="0" name="message" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ExtractNotFoundException">
    <xs:sequence>
      <xs:element minOccurs="0" name="message" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtract">
    <xs:sequence>
      <xs:element name="extractName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractResponse">
    <xs:sequence>
      <xs:element xmlns:ns1="http://www.w3.org/2005/05/xmlmime" minOccurs="0" name="dataExtractModel" type="tns:DataExtractModel" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="DataExtractModel">
    <xs:sequence>
      <xs:element minOccurs="0" name="fileName" type="xs:string" />
      <xs:element minOccurs="0" name="fileData" type="xs:base64Binary" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractDate">
    <xs:sequence>
      <xs:element name="extractName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractDateResponse">
    <xs:sequence>
      <xs:element minOccurs="0" name="dataExtractDateModel" type="tns:DataExtractDateModel" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="DataExtractDateModel">
    <xs:sequence>
      <xs:element minOccurs="0" name="fileName" type="xs:string" />
      <xs:element minOccurs="0" name="fileDate" type="xs:dateTime" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

<?xml version="1.0" encoding="utf-8"?>
<WL5G3N2:definitions xmlns:WL5G3N3="http://endpoint.data_extracts_ws.example.com/" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:WL5G3N1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:WL5G3N4="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:WL5G3N0="http://schemas.xmlsoap.org/ws/2004/09/policy" name="DataExtractsEndpointService" targetNamespace="http://endpoint.data_extracts_ws.example.com/" xmlns:WL5G3N2="http://schemas.xmlsoap.org/wsdl/">
  <WL5G3N0:Policy WL5G3N1:Id="Mtom.xml">
    <wsoma:OptimizedMimeSerialization xmlns:wsoma="http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization" />
  </WL5G3N0:Policy>
  <wsp:UsingPolicy WL5G3N2:Required="true" />
  <wsp:UsingPolicy WL5G3N2:Required="true" />
  <WL5G3N2:types>
    <xsd:schema xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://endpoint.data_extracts_ws.example.com/" xmlns:wssutil="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:import schemaLocation="https://www.example.com:443/data_extracts_ws/DataExtractsEndpointService?SCHEMA%2FData+Extracts+Service%2Fxsd%2FData+Extracts+Service+XSD" namespace="http://endpoint.data_extracts_ws.example.com/" />
    </xsd:schema>
  </WL5G3N2:types>
  <WL5G3N2:message name="getExtract">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtract" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractResponse">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractResponse" />
  </WL5G3N2:message>
  <WL5G3N2:message name="ExtractException">
    <WL5G3N2:part name="fault" element="WL5G3N3:ExtractException" />
  </WL5G3N2:message>
  <WL5G3N2:message name="ExtractNotFoundException">
    <WL5G3N2:part name="fault" element="WL5G3N3:ExtractNotFoundException" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractDate">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractDate" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractDateResponse">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractDateResponse" />
  </WL5G3N2:message>
  <WL5G3N2:portType name="DataExtractsEndpoint">
    <WL5G3N2:operation name="getExtract">
      <WL5G3N2:input message="WL5G3N3:getExtract" />
      <WL5G3N2:output message="WL5G3N3:getExtractResponse" />
      <WL5G3N2:fault name="ExtractException" message="WL5G3N3:ExtractException" />
      <WL5G3N2:fault name="ExtractNotFoundException" message="WL5G3N3:ExtractNotFoundException" />
    </WL5G3N2:operation>
    <WL5G3N2:operation name="getExtractDate">
      <WL5G3N2:input message="WL5G3N3:getExtractDate" />
      <WL5G3N2:output message="WL5G3N3:getExtractDateResponse" />
      <WL5G3N2:fault name="ExtractException" message="WL5G3N3:ExtractException" />
      <WL5G3N2:fault name="ExtractNotFoundException" message="WL5G3N3:ExtractNotFoundException" />
    </WL5G3N2:operation>
  </WL5G3N2:portType>
  <WL5G3N2:binding name="DataExtractsEndpointPortBinding" type="WL5G3N3:DataExtractsEndpoint">
    <wsp:Policy>
      <wsp:PolicyReference URI="#Mtom.xml" />
      <wsp:PolicyReference URI="#Mtom.xml" />
    </wsp:Policy>
    <WL5G3N4:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <WL5G3N2:operation name="getExtract">
      <WL5G3N4:operation soapAction="" />
      <WL5G3N2:input>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:input>
      <WL5G3N2:output>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:output>
      <WL5G3N2:fault name="ExtractException">
        <WL5G3N4:fault use="literal" name="ExtractException" namespace="" />
      </WL5G3N2:fault>
      <WL5G3N2:fault name="ExtractNotFoundException">
        <WL5G3N4:fault use="literal" name="ExtractNotFoundException" namespace="" />
      </WL5G3N2:fault>
    </WL5G3N2:operation>
    <WL5G3N2:operation name="getExtractDate">
      <WL5G3N4:operation soapAction="" />
      <WL5G3N2:input>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:input>
      <WL5G3N2:output>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:output>
      <WL5G3N2:fault name="ExtractException">
        <WL5G3N4:fault use="literal" name="ExtractException" namespace="" />
      </WL5G3N2:fault>
      <WL5G3N2:fault name="ExtractNotFoundException">
        <WL5G3N4:fault use="literal" name="ExtractNotFoundException" namespace="" />
      </WL5G3N2:fault>
    </WL5G3N2:operation>
  </WL5G3N2:binding>
  <WL5G3N2:service name="DataExtractsEndpointService">
    <WL5G3N2:port name="DataExtractsEndpointPort" binding="WL5G3N3:DataExtractsEndpointPortBinding">
      <WL5G3N4:address location="https://www.example.com:443/data_extracts_ws/DataExtractsEndpointService" />
    </WL5G3N2:port>
  </WL5G3N2:service>
</WL5G3N2:definitions>
</code>```

答: Just wanted to come back and answer this in case anyone else has this issue. The problem was the XSD that Weblogic generated had the elements in a different order than the SOAP response. Java didn't seem to have an issue but C# does. In this case the XSD had file name first and file date second for DataExtractDateModel. When i switched the order it went to working.</p>

Body:
Hi I'm working on a simple c# console application to fetch information from a Java JAX-WS Service. I've gotten my app to call the service and get information back but for some reason the response doesn't populate all of the attributes. I've verified that everything I'm expecting is coming back in the response and I don't think I've got a namespace issue like the other questions I've looked over so far.

Here is my actual Soap Response and I'm getting fileDate populated just fine but fileName is always null.

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:getExtractDateResponse xmlns:ns2="http://endpoint.data_extracts_ws.example.com/">
         <dataExtractDateModel>
            <fileDate>2015-09-17T00:00:00-05:00</fileDate>
            <fileName>export_file.zip</fileName>
         </dataExtractDateModel>
      </ns2:getExtractDateResponse>
   </S:Body>
</S:Envelope>

Here is my console app

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExtractsServiceClient.DataExtractsService;

namespace DataExtractsServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            DataExtractsEndpointClient extractService = new DataExtractsEndpointClient();
            extractService.ClientCredentials.UserName.UserName = "my_username";
            extractService.ClientCredentials.UserName.Password = "my_password";
            DataExtractDateModel extractDateModel = extractService.getExtractDate("EXTRACT_NAME");
            System.Console.WriteLine("File Name Is " + extractDateModel.fileName);
            System.Console.WriteLine("File Date Is " + extractDateModel.fileDate);
            System.Console.WriteLine("Finished");
            System.Console.ReadLine();
        }
    }
}

And the App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <system.serviceModel>
        <bindings>
            <customBinding>
                <binding name="DataExtractsEndpointPortBinding">

                    <mtomMessageEncoding messageVersion="Soap11" />
                    <httpsTransport authenticationScheme="Basic"/>
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="https://example.com/data_extracts_ws/DataExtractsEndpointService"
                binding="customBinding" bindingConfiguration="DataExtractsEndpointPortBinding"
                contract="DataExtractsService.DataExtractsEndpoint" name="DataExtractsEndpointPort" />
        </client>
    </system.serviceModel>
</configuration>

Adding the XSD and WSDL

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://endpoint.data_extracts_ws.example.com/" targetNamespace="http://endpoint.data_extracts_ws.example.com/" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="ExtractException" type="tns:ExtractException" />
  <xs:element name="ExtractNotFoundException" type="tns:ExtractNotFoundException" />
  <xs:element name="getExtract" type="tns:getExtract" />
  <xs:element name="getExtractDate" type="tns:getExtractDate" />
  <xs:element name="getExtractDateResponse" type="tns:getExtractDateResponse" />
  <xs:element name="getExtractResponse" type="tns:getExtractResponse" />
  <xs:complexType name="ExtractException">
    <xs:sequence>
      <xs:element minOccurs="0" name="message" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ExtractNotFoundException">
    <xs:sequence>
      <xs:element minOccurs="0" name="message" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtract">
    <xs:sequence>
      <xs:element name="extractName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractResponse">
    <xs:sequence>
      <xs:element xmlns:ns1="http://www.w3.org/2005/05/xmlmime" minOccurs="0" name="dataExtractModel" type="tns:DataExtractModel" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="DataExtractModel">
    <xs:sequence>
      <xs:element minOccurs="0" name="fileName" type="xs:string" />
      <xs:element minOccurs="0" name="fileData" type="xs:base64Binary" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractDate">
    <xs:sequence>
      <xs:element name="extractName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getExtractDateResponse">
    <xs:sequence>
      <xs:element minOccurs="0" name="dataExtractDateModel" type="tns:DataExtractDateModel" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="DataExtractDateModel">
    <xs:sequence>
      <xs:element minOccurs="0" name="fileName" type="xs:string" />
      <xs:element minOccurs="0" name="fileDate" type="xs:dateTime" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

<?xml version="1.0" encoding="utf-8"?>
<WL5G3N2:definitions xmlns:WL5G3N3="http://endpoint.data_extracts_ws.example.com/" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:WL5G3N1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:WL5G3N4="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:WL5G3N0="http://schemas.xmlsoap.org/ws/2004/09/policy" name="DataExtractsEndpointService" targetNamespace="http://endpoint.data_extracts_ws.example.com/" xmlns:WL5G3N2="http://schemas.xmlsoap.org/wsdl/">
  <WL5G3N0:Policy WL5G3N1:Id="Mtom.xml">
    <wsoma:OptimizedMimeSerialization xmlns:wsoma="http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization" />
  </WL5G3N0:Policy>
  <wsp:UsingPolicy WL5G3N2:Required="true" />
  <wsp:UsingPolicy WL5G3N2:Required="true" />
  <WL5G3N2:types>
    <xsd:schema xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://endpoint.data_extracts_ws.example.com/" xmlns:wssutil="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:import schemaLocation="https://www.example.com:443/data_extracts_ws/DataExtractsEndpointService?SCHEMA%2FData+Extracts+Service%2Fxsd%2FData+Extracts+Service+XSD" namespace="http://endpoint.data_extracts_ws.example.com/" />
    </xsd:schema>
  </WL5G3N2:types>
  <WL5G3N2:message name="getExtract">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtract" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractResponse">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractResponse" />
  </WL5G3N2:message>
  <WL5G3N2:message name="ExtractException">
    <WL5G3N2:part name="fault" element="WL5G3N3:ExtractException" />
  </WL5G3N2:message>
  <WL5G3N2:message name="ExtractNotFoundException">
    <WL5G3N2:part name="fault" element="WL5G3N3:ExtractNotFoundException" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractDate">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractDate" />
  </WL5G3N2:message>
  <WL5G3N2:message name="getExtractDateResponse">
    <WL5G3N2:part name="parameters" element="WL5G3N3:getExtractDateResponse" />
  </WL5G3N2:message>
  <WL5G3N2:portType name="DataExtractsEndpoint">
    <WL5G3N2:operation name="getExtract">
      <WL5G3N2:input message="WL5G3N3:getExtract" />
      <WL5G3N2:output message="WL5G3N3:getExtractResponse" />
      <WL5G3N2:fault name="ExtractException" message="WL5G3N3:ExtractException" />
      <WL5G3N2:fault name="ExtractNotFoundException" message="WL5G3N3:ExtractNotFoundException" />
    </WL5G3N2:operation>
    <WL5G3N2:operation name="getExtractDate">
      <WL5G3N2:input message="WL5G3N3:getExtractDate" />
      <WL5G3N2:output message="WL5G3N3:getExtractDateResponse" />
      <WL5G3N2:fault name="ExtractException" message="WL5G3N3:ExtractException" />
      <WL5G3N2:fault name="ExtractNotFoundException" message="WL5G3N3:ExtractNotFoundException" />
    </WL5G3N2:operation>
  </WL5G3N2:portType>
  <WL5G3N2:binding name="DataExtractsEndpointPortBinding" type="WL5G3N3:DataExtractsEndpoint">
    <wsp:Policy>
      <wsp:PolicyReference URI="#Mtom.xml" />
      <wsp:PolicyReference URI="#Mtom.xml" />
    </wsp:Policy>
    <WL5G3N4:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <WL5G3N2:operation name="getExtract">
      <WL5G3N4:operation soapAction="" />
      <WL5G3N2:input>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:input>
      <WL5G3N2:output>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:output>
      <WL5G3N2:fault name="ExtractException">
        <WL5G3N4:fault use="literal" name="ExtractException" namespace="" />
      </WL5G3N2:fault>
      <WL5G3N2:fault name="ExtractNotFoundException">
        <WL5G3N4:fault use="literal" name="ExtractNotFoundException" namespace="" />
      </WL5G3N2:fault>
    </WL5G3N2:operation>
    <WL5G3N2:operation name="getExtractDate">
      <WL5G3N4:operation soapAction="" />
      <WL5G3N2:input>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:input>
      <WL5G3N2:output>
        <WL5G3N4:body use="literal" />
      </WL5G3N2:output>
      <WL5G3N2:fault name="ExtractException">
        <WL5G3N4:fault use="literal" name="ExtractException" namespace="" />
      </WL5G3N2:fault>
      <WL5G3N2:fault name="ExtractNotFoundException">
        <WL5G3N4:fault use="literal" name="ExtractNotFoundException" namespace="" />
      </WL5G3N2:fault>
    </WL5G3N2:operation>
  </WL5G3N2:binding>
  <WL5G3N2:service name="DataExtractsEndpointService">
    <WL5G3N2:port name="DataExtractsEndpointPort" binding="WL5G3N3:DataExtractsEndpointPortBinding">
      <WL5G3N4:address location="https://www.example.com:443/data_extracts_ws/DataExtractsEndpointService" />
    </WL5G3N2:port>
  </WL5G3N2:service>
</WL5G3N2:definitions>


来源: stackexchange

问:
how to get the exact year from the given date in oracle if it has a minimal format to base from?
how to get the exact "year" from oracle data if the given data is in this format?

```<code>02-FEB-84
</code>```

I want to get the year, but when I do something like this

```<code>  case
   when dob is not null then to_date(dob,'YYYY')
   when dob is null then '""'
  end
as yearofbirth
</code>```

I am getting the value of

```<code>2084
</code>```

when I was expecting

```<code>1984
</code>```

how to solve this?, because my query is not smart enough to determine if the year is from the 19th century or 20th century

ContentLicense: CC BY-SA 3.0

Body:
how to get the exact "year" from oracle data if the given data is in this format?

02-FEB-84

I want to get the year, but when I do something like this

  case
   when dob is not null then to_date(dob,'YYYY')
   when dob is null then '""'
  end
as yearofbirth

I am getting the value of

2084

when I was expecting

1984

how to solve this?, because my query is not smart enough to determine if the year is from the 19th century or 20th century


问:
Javascript - Looping through spreadsheet merged cells
I am looping through a range of data in a Google spreadsheet in JavaScript.

The problem I'm having is I have some merged cells that have the same value, for example C:6 to E:6 all have the same value as those 3 cells are merged.

So in my loop it will show C:6 = 'Focus and targeting' D:6 = '' and E:6 = '' What I'm trying to do is in my loop assign the 2nd and 3rd values to the first cell value.

Here is what I have:

```<code>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = sheet.getMaxColumns();
  var values = range.getValues();

  var count = 0;
  for (var i = 2; i <= numCols - 2; i++) {

    var questionCategory = values[5][i];

    if(questionCategory == undefined) {
      continue;
    }

    if(questionCategory == "") {
       // need to assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list
    }

    count++;

  }
</code>```

Here is what the data looks like:

Any ideas how I can achieve this?

答:
Here is custom function to get merged cell value:

```<code>function getMergedCellValue(cellRange)
{
  if (!cellRange.isPartOfMerge())
  {
    return cellRange.getDisplayValue();
  }

  return cellRange.getMergedRanges()[0].getDisplayValue();
}
</code>```

And updated code using this function:

```<code>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var values = range.getValues();

  var count = 0;
  var questionRowNum = 6;
  for (var i = 0; i < numCols; i++)
  {
    // assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list
    var questionCategory = values[questionRowNum-1][i] || getMergedCellValue(sheet.getRange(questionRowNum, i+1));

    count++;
  }
</code>```

Body:
I am looping through a range of data in a Google spreadsheet in JavaScript.

The problem I'm having is I have some merged cells that have the same value, for example C:6 to E:6 all have the same value as those 3 cells are merged.

So in my loop it will show C:6 = 'Focus and targeting' D:6 = '' and E:6 = '' What I'm trying to do is in my loop assign the 2nd and 3rd values to the first cell value.

Here is what I have:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = sheet.getMaxColumns();
  var values = range.getValues();

  var count = 0;
  for (var i = 2; i <= numCols - 2; i++) {

    var questionCategory = values[5][i];

    if(questionCategory == undefined) {
      continue;
    }

    if(questionCategory == "") {
       // need to assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list
    }

    count++;

  }

Here is what the data looks like:

Any ideas how I can achieve this?

Body:
Here is custom function to get merged cell value:

function getMergedCellValue(cellRange)
{
  if (!cellRange.isPartOfMerge())
  {
    return cellRange.getDisplayValue();
  }

  return cellRange.getMergedRanges()[0].getDisplayValue();
}

And updated code using this function:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var values = range.getValues();

  var count = 0;
  var questionRowNum = 6;
  for (var i = 0; i < numCols; i++)
  {
    // assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list
    var questionCategory = values[questionRowNum-1][i] || getMergedCellValue(sheet.getRange(questionRowNum, i+1));

    count++;
  }


问:
Asynchronous communication with multiple web servers C#

I have one 'main' server, and several other servers (Extensions) which need to be controlled by the main server.

The Extensions each have a Web Reference to their respective server. Controlling these extensions is done by Init(), Start() and Stop() web calls. Up until now I did this synchronously, the main server for example calls:

```<code>public void InitExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Init();
    }
}
</code>```

And than:

```<code>public void StartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Start();
    }
}
</code>```

Where the extension.Init() and extension.Start() will do the webcalls.

Now I want to do this asynchronously, but the tricky part is that the StartExtensions() method should wait for the extension.Init() to be finished. A different Extension can of course be started before another one is initialized.

What is the best way to do this? I think I will need for example lists

```<code>List<Thread> _InitThreads;
List<Thread> _StartThreads;
List<Thread> _StopThreads;
</code>```

And check if each list contains a thread for the respective Extension, and Join() it to wait execution. This gets however very difficult very fast...

答:
This should do it, assuming your Init() method is synchronous (i.e. you don't need to wait for an event to tell it has finished)</p>

```<code>public void InitAndStartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        Task.Run(() =>
        {
            extension.Init();
            extension.Start();
        });
    }
}
</code>```

Body:
I have one 'main' server, and several other servers (Extensions) which need to be controlled by the main server.

The Extensions each have a Web Reference to their respective server. Controlling these extensions is done by Init(), Start() and Stop() web calls. Up until now I did this synchronously, the main server for example calls:

public void InitExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Init();
    }
}

And than:

public void StartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Start();
    }
}

Where the extension.Init() and extension.Start() will do the webcalls.

Now I want to do this asynchronously, but the tricky part is that the StartExtensions() method should wait for the extension.Init() to be finished. A different Extension can of course be started before another one is initialized.

What is the best way to do this? I think I will need for example lists

List<Thread> _InitThreads;
List<Thread> _StartThreads;
List<Thread> _StopThreads;

And check if each list contains a thread for the respective Extension, and Join() it to wait execution. This gets however very difficult very fast...

Body:
This should do it, assuming your Init() method is synchronous (i.e. you don't need to wait for an event to tell it has finished)

public void InitAndStartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        Task.Run(() =>
        {
            extension.Init();
            extension.Start();
        });
    }
}


问:
IE 8 flash not displaying
I'm using flash in a few of my websites for displaying a slideshow. This is the code I use in splendor-bg.com :

```<code><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="740" height="450" id="tech" align="middle">
        <param name="allowScriptAccess" value="sameDomain" />
        <param name="movie" value="splendor-bg.swf?xml_path=slides.xml" />
        <param name="quality" value="high" />
        <embed src="splendor-bg.swf?xml_path=slides.xml" quality="high" width="720" height="430" name="tech" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>
</code>```

I can see it on my computer in internet explorer just fine (I must have installed something that is needed, or set up IE in some way, I guess).. but its not working on quite a few other computers I've tested it on - this is what they see:

Does anyone have an idea on how to fix this? Either a message of something that needs to be installed should be shown to the user, or something in the code itself.. Any help will be greatly appreciated!

答:
I'm not sure what the problem may be in this particular code.

However, I would like to suggest that you try swfobject. You can download it at http://code.google.com/p/swfobject/

swfobject is a great way to embed flash to a website and seems to work in all browsers for me.

It's also very simple to use, let's assume you have a div container with the id flashcontent:

```<code><div id="flashcontent">
</div>
</code>```

And then with javascript you would simply do:

```<code><script type="text/javascript">
    var flashvars = {};
    var params = {allowScriptAccess: "sameDomain"};
    var attributes = {};
    swfobject.embedSWF("splendor-bg.swf?xml_path=slides.xml", "flashcontent", "720", "430", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
</script>
</code>```

Voila and the Flash object should be embedded over the flashcontent div container.

Give it a try and see if it works better. You can read the swfobject documentation at http://code.google.com/p/swfobject/wiki/documentation

ContentLicense: CC BY-SA 2.5

Title: IE 8 flash not displaying

Body:
I'm using flash in a few of my websites for displaying a slideshow. This is the code I use in splendor-bg.com :

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="740" height="450" id="tech" align="middle">
        <param name="allowScriptAccess" value="sameDomain" />
        <param name="movie" value="splendor-bg.swf?xml_path=slides.xml" />
        <param name="quality" value="high" />
        <embed src="splendor-bg.swf?xml_path=slides.xml" quality="high" width="720" height="430" name="tech" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>

I can see it on my computer in internet explorer just fine (I must have installed something that is needed, or set up IE in some way, I guess).. but its not working on quite a few other computers I've tested it on - this is what they see:

Does anyone have an idea on how to fix this? Either a message of something that needs to be installed should be shown to the user, or something in the code itself.. Any help will be greatly appreciated!

Body:
I'm not sure what the problem may be in this particular code.

However, I would like to suggest that you try swfobject. You can download it at http://code.google.com/p/swfobject/

swfobject is a great way to embed flash to a website and seems to work in all browsers for me.

It's also very simple to use, let's assume you have a div container with the id flashcontent:

<div id="flashcontent">
</div>

And then with javascript you would simply do:

<script type="text/javascript">
    var flashvars = {};
    var params = {allowScriptAccess: "sameDomain"};
    var attributes = {};
    swfobject.embedSWF("splendor-bg.swf?xml_path=slides.xml", "flashcontent", "720", "430", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
</script>

Voila and the Flash object should be embedded over the flashcontent div container.

Give it a try and see if it works better. You can read the swfobject documentation at http://code.google.com/p/swfobject/wiki/documentation


问:
Letsencrypt ImportError: No module named interface on amazon linux while renewing
Today when i tried to renew my certificates using this command I'm facing error

```<code>/opt/letsencrypt/letsencrypt-auto renew --config /etc/letsencrypt/config.ini --agree-tos && apachectl graceful
</code>```

also tried this command

```<code>/opt/letsencrypt/letsencrypt-auto renew
</code>```

Error :

```<code>Traceback (most recent call last):
  File "/root/.local/share/letsencrypt/bin/letsencrypt", line 7, in <module>
    from certbot.main import main
  File "/root/.local/share/letsencrypt/local/lib/python2.7/dist-packages/certbot/main.py", line 12, in <module>
    import zope.component
  File "/root/.local/share/letsencrypt/local/lib/python2.7/dist-packages/zope/component/__init__.py", line 16, in <module>
    from zope.interface import Interface
ImportError: No module named interface
</code>```

I did lot of research no solution found.

答:
I faced the same issue and upgrading pip and virtualenv as instructed in this post worked for me.</p>

```<code>sudo pip install --upgrade pip
sudo pip install --upgrade virtualenv
rm -rf ~/.local/share/letsencrypt
/opt/letsencrypt/letsencrypt-auto --debug
</code>```

Body:
Today when i tried to renew my certificates using this command I'm facing error

/opt/letsencrypt/letsencrypt-auto renew --config /etc/letsencrypt/config.ini --agree-tos && apachectl graceful

also tried this command

/opt/letsencrypt/letsencrypt-auto renew

Error :

Traceback (most recent call last):
  File "/root/.local/share/letsencrypt/bin/letsencrypt", line 7, in <module>
    from certbot.main import main
  File "/root/.local/share/letsencrypt/local/lib/python2.7/dist-packages/certbot/main.py", line 12, in <module>
    import zope.component
  File "/root/.local/share/letsencrypt/local/lib/python2.7/dist-packages/zope/component/__init__.py", line 16, in <module>
    from zope.interface import Interface
ImportError: No module named interface

I did lot of research no solution found.

Body:
I faced the same issue and upgrading pip and virtualenv as instructed in this post worked for me.

sudo pip install --upgrade pip
sudo pip install --upgrade virtualenv
rm -rf ~/.local/share/letsencrypt
/opt/letsencrypt/letsencrypt-auto --debug


问:
Let user select multiple values in VBA toolbar
Is there a way in VBA to add a ListBox to a toolbar (Add In ribbon)? I want to be able to let the user select multiple values/criteria in a listbox instead of just one value in a dropdown/combobox menu.

The below code adds a dropdown menu only

```<code>Sub addSelectControls()
    Dim newBar As Office.CommandBar
    Set newBar = CommandBars.Add(Name:="testing CommandBar", temporary:=True)
    Dim newCombo As Office.CommandBarComboBox
    Set newCombo = newBar.Controls.Add(Type:=msoControlDropdown, temporary:=True)
    With newCombo

        .AddItem "Blocks"
        .AddItem "Hardware"
        .AddItem "Aircraft Hardware"
        .AddItem "Vehical Hardware"
        .AddItem "Machinery"
        .AddItem "Wood Products"
        .AddItem "Miscellaneous Products"
        .AddItem "Miscellaneous Metal"
        .AddItem "Precast Metal"
        .AddItem "Forged Metal"
        .AddItem "Structural Steel"
        .AddItem "Fabricated Steel"
        .AddItem "Prebent Steel"
        .AddItem "Stock Steel"
        .ListIndex = 13
        .Width = 200
        .Caption = "Category"
        .Style = msoComboLabel
        .BeginGroup = True
        .OnAction = "Category_Select"

    End With
    'ctlComboBoxHandler.SyncBox newCombo
    newBar.Visible = True
End Sub
</code>```

Please advice. In case you know a better way to do this, that would be great too!

答:
Age-old question, but there is a way to get multiselect dropdown in the Office ribbon. Not too fancy though, as after every selection, you will have to reopen the dropdown.

You need to use a DynamicMenu with Checkboxes in it.

Here is the XML I have used in the custom ribbon UI thingy:

```<code><customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui">
  <ribbon>
    <tabs>
      <tab id="mso_c1.FD142A8" label="Diaverum" insertBeforeQ="TabHome">
        <group id="mso_c2.FD142A8" label="Szurés" imageMso="FilterByResource">
          <dynamicMenu id="FilterMenu" label="Beosztás szerint" getContent="GetMenuContent_FilterMenu" />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>
</code>```

The GetMenuContent_FilterMenu callback populates the dynamic menu with checkboxes. It basically creates an XML string that contains the commands to create the checkboxes. I use a Table in Excel to get the values from, but you can change this. The code for the callback:

```<code>Sub GetMenuContent_Beosztas(control As IRibbonControl, ByRef returnedVal)

Dim CheckboxesXML As String
Dim myCell As Range
Dim i As Integer

For Each myCell In Range("tblBeosztas").Cells
  CheckboxesXML = CheckboxesXML & "<checkBox id=""chk_" & i & """ label=""" & myCell.Value & """ />" & vbNewLine
  i = i + 1
Next myCell

returnedVal = "<menu xmlns=""http://schemas.microsoft.com/office/2006/01/customui"">" & vbNewLine & _
    CheckboxesXML & _
    "</menu>"

End Sub
</code>```

The generated XML looks like this:

```<code><menu xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<checkBox id="chk_0" label="Nővér" />
<checkBox id="chk_1" label="Dializáló asszisztens" />
<checkBox id="chk_2" label="Technikus" />
<checkBox id="chk_4" label="Orvos igazgató" />
</menu>
</code>```

Body:
Is there a way in VBA to add a ListBox to a toolbar (Add In ribbon)? I want to be able to let the user select multiple values/criteria in a listbox instead of just one value in a dropdown/combobox menu.

The below code adds a dropdown menu only

Sub addSelectControls()
    Dim newBar As Office.CommandBar
    Set newBar = CommandBars.Add(Name:="testing CommandBar", temporary:=True)
    Dim newCombo As Office.CommandBarComboBox
    Set newCombo = newBar.Controls.Add(Type:=msoControlDropdown, temporary:=True)
    With newCombo

        .AddItem "Blocks"
        .AddItem "Hardware"
        .AddItem "Aircraft Hardware"
        .AddItem "Vehical Hardware"
        .AddItem "Machinery"
        .AddItem "Wood Products"
        .AddItem "Miscellaneous Products"
        .AddItem "Miscellaneous Metal"
        .AddItem "Precast Metal"
        .AddItem "Forged Metal"
        .AddItem "Structural Steel"
        .AddItem "Fabricated Steel"
        .AddItem "Prebent Steel"
        .AddItem "Stock Steel"
        .ListIndex = 13
        .Width = 200
        .Caption = "Category"
        .Style = msoComboLabel
        .BeginGroup = True
        .OnAction = "Category_Select"

    End With
    'ctlComboBoxHandler.SyncBox newCombo
    newBar.Visible = True
End Sub

Please advice. In case you know a better way to do this, that would be great too!

Body:
Age-old question, but there is a way to get multiselect dropdown in the Office ribbon. Not too fancy though, as after every selection, you will have to reopen the dropdown.

You need to use a DynamicMenu with Checkboxes in it.

Here is the XML I have used in the custom ribbon UI thingy:

<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui">
  <ribbon>
    <tabs>
      <tab id="mso_c1.FD142A8" label="Diaverum" insertBeforeQ="TabHome">
        <group id="mso_c2.FD142A8" label="Szurés" imageMso="FilterByResource">
          <dynamicMenu id="FilterMenu" label="Beosztás szerint" getContent="GetMenuContent_FilterMenu" />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

The GetMenuContent_FilterMenu callback populates the dynamic menu with checkboxes. It basically creates an XML string that contains the commands to create the checkboxes. I use a Table in Excel to get the values from, but you can change this. The code for the callback:

Sub GetMenuContent_Beosztas(control As IRibbonControl, ByRef returnedVal)

Dim CheckboxesXML As String
Dim myCell As Range
Dim i As Integer

For Each myCell In Range("tblBeosztas").Cells
  CheckboxesXML = CheckboxesXML & "<checkBox id=""chk_" & i & """ label=""" & myCell.Value & """ />" & vbNewLine
  i = i + 1
Next myCell

returnedVal = "<menu xmlns=""http://schemas.microsoft.com/office/2006/01/customui"">" & vbNewLine & _
    CheckboxesXML & _
    "</menu>"

End Sub

The generated XML looks like this:

<menu xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<checkBox id="chk_0" label="Nővér" />
<checkBox id="chk_1" label="Dializáló asszisztens" />
<checkBox id="chk_2" label="Technikus" />
<checkBox id="chk_4" label="Orvos igazgató" />
</menu>


问:
How can I disable compiler optimization in C#?
How can I disable compiler optimization in C#?</p>

答:
Set Configurations to All Configurations

Set Optimized code checkbox to unchecked

OwnerDisplayName: Yasar


问:
How many people can connect to ServerSocket?
I'm working with sockets. I'd like to know how many people can connect to my SocketServer using Sockets?

According to Cameron it is 2^16 different connection. So, as much as 2^16 people can actually use my chat at the same time(resources for handling so much users and other factors are not considered)???

https://www.quora.com/How-many-connections-can-a-JAVA-socket-server-hold

答:
The theoretical limit is 2^16 - 1.  Port zero is reserved.

The practical limit will be platform specific, and can only be determined by testing.

The limiting factors will include:

available network throughput,

the number of simultaneous connections that the OS kernel can sustain,

the number of open file descriptors that a process is permitted, and

the in-process resources required to sustain a large number of active connections.

Most of those are most likely to be hardware limitations.

The limit of 50 that people are talking above in comments is the number of connection requests that can be queued.  If your java application calls ServerSocket.accept() fast enough, requests won't be dropped.


问:
Unable to cast object of generic type to generic interface C#
I have two interfaces:

```<code>public interface IDbModel {}
public interface IDmModel {}
</code>```

And classes derived from this:

```<code>public class DbModel : IDbModel {}
public class DmModel : IDmModel {}
public class Middle { }
</code>```

Also I have two interfaces with restrictions:

```<code>public interface IRule { }
public interface IRule<in TInput, out TOutput> : IRule
    where TInput : IDmModel
    where TOutput : IDbModel
{
    TOutput Apply(TInput elem);
}
</code>```

And one abstract class derived from this interface:

```<code>public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb>
    where TDmModel : IDmModel
    where TDb : IDbModel
{
    private readonly Func<TDmModel, TMiddle> _rule;
    protected Rule(Func<TDmModel, TMiddle> rule) { _rule = rule; }
    protected abstract TDb Apply(TMiddle transformedMessage);
    public TDb Apply(TDmModel elem) { ... }
}
</code>```

After this I created two classes derived from this abstract class:

```<code>public class RuleA : Rule<DmModel, Middle, DbModel>
{
    public RuleA(Func<DmModel, Middle> rule) : base(rule) {}
    protected override DbMode Apply(Middle transformedMessage) { ... }
}

public class RuleB : RuleA
{
    public RuleB() : base((dm) => new Middle()) {}
}
</code>```

RuleB : RuleA : Rule< DmModel,Middle,DbModel > : IRule< IDmModel,IDbModel > : IRule

And when I try to cast object of RuleB to IRule<IDmModel, IDbModel> occours unhandled exception

Unable to cast object of type 'ParsreCombinators.RuleB' to type 'ParsreCombinators.IRule`2[ParsreCombinators.IDmModel,ParsreCombinators.IDbModel]'.

```<code>var ruleB = (IRule<IDmModel, IDbModel>)new RuleB(); // Exception
IDbModel dbModel = ruleB.Apply(new DmModel());
</code>```

What wrong with this

To make the example less confusing I simplify it:

EDIT:

After the answers I understood, what is the problem and to make the example less confusing I simplify it:

```<code>public interface IDbModel {}
public interface IDmModel {}

public class DbModel : IDbModel {}
public class DmModel : IDmModel {}

public interface IRule<in TInput, out TOutput>
    where TInput : IDmModel
    where TOutput : IDbModel
{
    TOutput Apply(TInput elem);
}

public class RuleA : IRule<DmModel, DbModel>
{
    public DbModel Apply(DmModel elem) { ... }
}

var ruleA = (IRule<IDmModel, IDbModel>)new RuleA(); // Exception
</code>```

答:
That's a lot of levels of indirection you got there...

Here's the issue:

```<code>public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb>
    where TDmModel : IDmModel
    where TDb : IDbModel

public class RuleA : Rule<DmModel, Middle, DbMode>
public class RuleB : RuleA
...
var ruleB = (IRule<IDmModel, IDbModel>)new RuleB();
</code>```

RuleB implements IRule<DmModel, DbMode>

This cannot be cast to IRule<IDmModel, IDbModel>.  C# does not support this type of casting.  For the same reason, you cannot do List<object> b = (List<object>)new List<string>();  (Gives "Cannot convert type 'System.Collections.Generic.List<string> to System.Collections.Generic.List<object>.")

This is an issue with covariance.

Here is some more information from Microsoft on the subject: https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance

Body:
I have two interfaces:

public interface IDbModel {}
public interface IDmModel {}

And classes derived from this:

public class DbModel : IDbModel {}
public class DmModel : IDmModel {}
public class Middle { }

Also I have two interfaces with restrictions:

public interface IRule { }
public interface IRule<in TInput, out TOutput> : IRule
    where TInput : IDmModel
    where TOutput : IDbModel
{
    TOutput Apply(TInput elem);
}

And one abstract class derived from this interface:

public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb>
    where TDmModel : IDmModel
    where TDb : IDbModel
{
    private readonly Func<TDmModel, TMiddle> _rule;
    protected Rule(Func<TDmModel, TMiddle> rule) { _rule = rule; }
    protected abstract TDb Apply(TMiddle transformedMessage);
    public TDb Apply(TDmModel elem) { ... }
}

After this I created two classes derived from this abstract class:

public class RuleA : Rule<DmModel, Middle, DbModel>
{
    public RuleA(Func<DmModel, Middle> rule) : base(rule) {}
    protected override DbMode Apply(Middle transformedMessage) { ... }
}

public class RuleB : RuleA
{
    public RuleB() : base((dm) => new Middle()) {}
}

RuleB : RuleA : Rule< DmModel,Middle,DbModel > : IRule< IDmModel,IDbModel > : IRule

And when I try to cast object of RuleB to IRule<IDmModel, IDbModel> occours unhandled exception

Unable to cast object of type 'ParsreCombinators.RuleB' to type 'ParsreCombinators.IRule`2[ParsreCombinators.IDmModel,ParsreCombinators.IDbModel]'.

var ruleB = (IRule<IDmModel, IDbModel>)new RuleB(); // Exception
IDbModel dbModel = ruleB.Apply(new DmModel());

What wrong with this

To make the example less confusing I simplify it:

EDIT:

After the answers I understood, what is the problem and to make the example less confusing I simplify it:

public interface IDbModel {}
public interface IDmModel {}

public class DbModel : IDbModel {}
public class DmModel : IDmModel {}

public interface IRule<in TInput, out TOutput>
    where TInput : IDmModel
    where TOutput : IDbModel
{
    TOutput Apply(TInput elem);
}

public class RuleA : IRule<DmModel, DbModel>
{
    public DbModel Apply(DmModel elem) { ... }
}

var ruleA = (IRule<IDmModel, IDbModel>)new RuleA(); // Exception

Body:
That's a lot of levels of indirection you got there...

Here's the issue:

public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb>
    where TDmModel : IDmModel
    where TDb : IDbModel

public class RuleA : Rule<DmModel, Middle, DbMode>
public class RuleB : RuleA
...
var ruleB = (IRule<IDmModel, IDbModel>)new RuleB();

RuleB implements IRule<DmModel, DbMode>

This cannot be cast to IRule<IDmModel, IDbModel>.  C# does not support this type of casting.  For the same reason, you cannot do List<object> b = (List<object>)new List<string>();  (Gives "Cannot convert type 'System.Collections.Generic.List<string> to System.Collections.Generic.List<object>.")

This is an issue with covariance.

Here is some more information from Microsoft on the subject: https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance


问:
jquery UI draggable with live
this is a draggable sortable example on the jqueryui website, i need to use live() with this (I think) because the elements are created through ajax, does anybody know how to apply the live event to the following?  </p>

```<code><script>
    $(function() {
        $( "#sortable" ).sortable({
            revert: true
        });
        $( "#draggable" ).draggable({
            connectToSortable: "#sortable",
            helper: "clone",
            revert: "invalid"
        });
        $( "ul, li" ).disableSelection();
    });
    </script>
</code>```

答:
You don't have to use live with this (and I don't think you can), just hook them up once you've added them, in the success handler. For instance, if using load:

```<code>$("#target").load("your url", function() {
  // Replace the selectors below to match what you load
  $( "#target *[data-name=sortable]" ).sortable({
      revert: true
  });
  $( "#target *[data-name=draggable]" ).draggable({
      connectToSortable: "#target *[data-name=sortable]",
      helper: "clone",
      revert: "invalid"
  });
  $(this).find( "ul, li" ).disableSelection();
});
</code>```

Live Example

That uses this modified HTML from the jQuery UI demo page (just replaced id values with data-name instead, so they don't have to be unique):

```<code><ul>
  <li data-name='draggable' class="ui-state-highlight">Drag me down</li>
</ul>

<ul data-name="sortable">
  <li class="ui-state-default">Item 1</li>
  <li class="ui-state-default">Item 2</li>
  <li class="ui-state-default">Item 3</li>
  <li class="ui-state-default">Item 4</li>
  <li class="ui-state-default">Item 5</li>
</ul>
</code>```

Title: jquery UI draggable with live

Body:
You don't have to use live with this (and I don't think you can), just hook them up once you've added them, in the success handler. For instance, if using load:

$("#target").load("your url", function() {
  // Replace the selectors below to match what you load
  $( "#target *[data-name=sortable]" ).sortable({
      revert: true
  });
  $( "#target *[data-name=draggable]" ).draggable({
      connectToSortable: "#target *[data-name=sortable]",
      helper: "clone",
      revert: "invalid"
  });
  $(this).find( "ul, li" ).disableSelection();
});

Live Example

That uses this modified HTML from the jQuery UI demo page (just replaced id values with data-name instead, so they don't have to be unique):

<ul>
  <li data-name='draggable' class="ui-state-highlight">Drag me down</li>
</ul>

<ul data-name="sortable">
  <li class="ui-state-default">Item 1</li>
  <li class="ui-state-default">Item 2</li>
  <li class="ui-state-default">Item 3</li>
  <li class="ui-state-default">Item 4</li>
  <li class="ui-state-default">Item 5</li>
</ul>


问:
setting values for ntree and mtry for random forest regression model
I'm using R package randomForest to do a regression on some biological data. My training data size is 38772 X 201.

I just wondered---what would be a good value for the number of trees ntree and the number of variable per level mtry? Is there an approximate formula to find such parameter values?

Each row in my input data is a 200 character representing the amino acid sequence, and I want to build a regression model to use such sequence in order to predict the distances between the proteins.

答: One nice trick that I use is to initially start with first taking square root of the number of predictors and plug that value for "mtry". It is usually around the same value that tunerf funtion in random forest would pick. </p>

ContentLicense: CC BY-SA 4.0


问:
How to create a new row with the total sum of a axis
I need create a new row with the total value of axis 0 sum.

I have the follow series values:

```<code>INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
</code>```

How can i add a new row at the end of series with the total sum, like this:

```<code>INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
TOTAL   0.26
</code>```

答:
You should find your answer here :

Appending column totals to a Pandas DataFrame

Precisely : df.loc['Total']= df.sum()

Body:
I need create a new row with the total value of axis 0 sum.

I have the follow series values:

INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62

How can i add a new row at the end of series with the total sum, like this:

INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
TOTAL   0.26


问:
Error when using XmlBeans generated classes
I've generated classes with XMLBeans from an xsd file and packed them in a jar file. then I've added that jar to the project classpath in eclipse and everything compiles and runs fine.
I built a stand alone jar file from my project with Maven and again the build is successful, but when i try running it i get this error:

```<code> Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.oblicore.oblisync.resolutions.TestsDocument$Factory.parse(TestsDo
cument.java:126)
    at com.oblicore.oblisync.handlers.TransferEntitiesHandler.getResolution(
TransferEntitiesHandler.java:117)
    at com.oblicore.oblisync.handlers.TransferEntitiesHandler.resolveConflic
ts(TransferEntitiesHandler.java:103)
    at com.oblicore.oblisync.main.Orchestrator.run(Orchestrator.java:107)
    at com.oblicore.oblisync.main.Orchestrator.main(Orchestrator.java:58)
Caused by: java.lang.RuntimeException: Cannot load SchemaTypeSystem. Unable to l
oad class with name schemaorg_apache_xmlbeans.system.s8B21CFFFCFED0B2438C2585C61
F113F7.TypeSystemHolder. Make sure the generated binary files are on the classpa
th.
    at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
83)
    at com.oblicore.oblisync.resolutions.TestsDocument.<clinit>(TestsDocumen
t.java:19)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: schemaorg_apache_xmlbeans.system.s8
B21CFFFCFED0B2438C2585C61F113F7.TypeSystemHolder
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
69)
    ... 6 more
</code>```

The missing class is in the jar i created with XmlBeans, how do i tell maven to add it to the jar it creates from my project?

答:
Extract jar in which you want to include  schemaorg_apache_xmlbeans folder.
Copy schemaorg_apache_xmlbeans folder in extracted folder (result from jar extraction).
open command prompt in extracted folder.

make jar again using jar cf command. e.g jar cf test.jar *,
 to include all folders.

Deploy that jar .

Body:
I've generated classes with XMLBeans from an xsd file and packed them in a jar file. then I've added that jar to the project classpath in eclipse and everything compiles and runs fine.
I built a stand alone jar file from my project with Maven and again the build is successful, but when i try running it i get this error:

 Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.oblicore.oblisync.resolutions.TestsDocument$Factory.parse(TestsDo
cument.java:126)
    at com.oblicore.oblisync.handlers.TransferEntitiesHandler.getResolution(
TransferEntitiesHandler.java:117)
    at com.oblicore.oblisync.handlers.TransferEntitiesHandler.resolveConflic
ts(TransferEntitiesHandler.java:103)
    at com.oblicore.oblisync.main.Orchestrator.run(Orchestrator.java:107)
    at com.oblicore.oblisync.main.Orchestrator.main(Orchestrator.java:58)
Caused by: java.lang.RuntimeException: Cannot load SchemaTypeSystem. Unable to l
oad class with name schemaorg_apache_xmlbeans.system.s8B21CFFFCFED0B2438C2585C61
F113F7.TypeSystemHolder. Make sure the generated binary files are on the classpa
th.
    at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
83)
    at com.oblicore.oblisync.resolutions.TestsDocument.<clinit>(TestsDocumen
t.java:19)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: schemaorg_apache_xmlbeans.system.s8
B21CFFFCFED0B2438C2585C61F113F7.TypeSystemHolder
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
69)
    ... 6 more

The missing class is in the jar i created with XmlBeans, how do i tell maven to add it to the jar it creates from my project?


问:
How to store a string in a empty list and display the results in a listbox
Hello Python community,

Im using Python 3.6 and Im stumped on how to display a stored item in an empty list to a list box. Can anyone evaluate my code and tell me what I'm missing? Thanks in advance!

```<code>from tkinter import *

root = Tk()
root.title("Name Entry")
root.geometry("240x250")

mylist = []

def get_data(l):
    l.append(box1.get())
    print(l)

label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)

ID=StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)

botonA = Button(root, text = "accept",command=lambda: get_data(mylist), width = 5)
botonA.grid(row = 0, column = 2)

list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7)
for item in mylist:
    list_names.insert("end", item)

root.mainloop()
</code>```

With the help from Matteo, I was able to creat what I wanted. Thanks again for clearing this up for me! :)

```<code>{from tkinter import *

 root = Tk()
 root.title("Name Entry")
 root.geometry("240x250")

 mylist = []

 def get_data(l):
    l.append(box1.get())
    print(l)
    display_data()

def display_data():
    list_names.delete(0, "end")

    for items in mylist:
        list_names.insert(END, items)

label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)

ID = StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)

botonA = Button(root, text = "accept",command = lambda: get_data(mylist),
width = 5)
botonA.grid(row = 0, column = 2)

list_names = Listbox(root)
list_names.grid(row = 2, column = 1, rowspan = 7)

root.mainloop()}
</code>```

答:
You have to insert the element when the button is pressed! In your code you are adding it to the listbox when mylist was empty.

Here is the working code:

```<code>from tkinter import *

root = Tk()
root.title("Name Entry")
root.geometry("240x250")

mylist = []

def get_data(l):
    l.append(box1.get())
    list_names.insert(END, l)
    print(l)

label1 = Label(root, text="ID:", height=2)
label1.grid(row=0, column=0)

ID = StringVar()
box1 = Entry(root, bd=4, textvariable=ID)
box1.grid(row=0, column=1)

botonA = Button(root, text="accept", command=lambda: get_data(mylist), width=5)
botonA.grid(row=0, column=2)

list_names = Listbox(root)
list_names.grid(row=2, column=1, rowspan=7)

root.mainloop()
</code>```

I also modified two other things:

I'm not sure if it's what you wanted but l.append(box1.get()) adds to the listbox all the element of the list, and not just the last one as I think you need.

list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7) means that the list_names variable is the result of the grid function (which is None). You have to first save the ListBox variable, and the grid it.

Body:
Hello Python community,

Im using Python 3.6 and Im stumped on how to display a stored item in an empty list to a list box. Can anyone evaluate my code and tell me what I'm missing? Thanks in advance!

from tkinter import *

root = Tk()
root.title("Name Entry")
root.geometry("240x250")

mylist = []

def get_data(l):
    l.append(box1.get())
    print(l)

label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)

ID=StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)

botonA = Button(root, text = "accept",command=lambda: get_data(mylist), width = 5)
botonA.grid(row = 0, column = 2)

list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7)
for item in mylist:
    list_names.insert("end", item)

root.mainloop()

With the help from Matteo, I was able to creat what I wanted. Thanks again for clearing this up for me! :)

{from tkinter import *

 root = Tk()
 root.title("Name Entry")
 root.geometry("240x250")

 mylist = []

 def get_data(l):
    l.append(box1.get())
    print(l)
    display_data()

def display_data():
    list_names.delete(0, "end")

    for items in mylist:
        list_names.insert(END, items)

label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)

ID = StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)

botonA = Button(root, text = "accept",command = lambda: get_data(mylist),
width = 5)
botonA.grid(row = 0, column = 2)

list_names = Listbox(root)
list_names.grid(row = 2, column = 1, rowspan = 7)

root.mainloop()}

Body:
You have to insert the element when the button is pressed! In your code you are adding it to the listbox when mylist was empty.

Here is the working code:

from tkinter import *

root = Tk()
root.title("Name Entry")
root.geometry("240x250")

mylist = []

def get_data(l):
    l.append(box1.get())
    list_names.insert(END, l)
    print(l)

label1 = Label(root, text="ID:", height=2)
label1.grid(row=0, column=0)

ID = StringVar()
box1 = Entry(root, bd=4, textvariable=ID)
box1.grid(row=0, column=1)

botonA = Button(root, text="accept", command=lambda: get_data(mylist), width=5)
botonA.grid(row=0, column=2)

list_names = Listbox(root)
list_names.grid(row=2, column=1, rowspan=7)

root.mainloop()

I also modified two other things:

I'm not sure if it's what you wanted but l.append(box1.get()) adds to the listbox all the element of the list, and not just the last one as I think you need.

list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7) means that the list_names variable is the result of the grid function (which is None). You have to first save the ListBox variable, and the grid it.


问:
Max, Min, Avg function for an array in C++
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.</p>

```<code>#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}
</code>```

答:
Three things:

You have to define min, max, avg in your main() function before passing them on.

You can't cout << function() if it doesn't return anything.

In normalizeMinMaxAvg for loop, you access i (index) instead of data[i] (the data under index i in array data).

Body:
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}


问:
How to change default ProgressDialog circle color in android
I am using ProgressDialog for showing progressbar

```<code>            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.setMessage(message);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
</code>```

And it is coming like this

I want to change the green color of the circle to red. is there any way?

I tried

```<code>.getIndeterminateDrawable().setColorFilter(0xFFFFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY);
</code>```

But not working.

答:
If you'd like to define the colour ad-hoc, without needing inheritance or dedicated XML, you can use something like this:</p>

```<code>/** Styles a ProgressDialog to use a themed Spinner. */
public void setStyledProgressDialog(final Context pContext, final ProgressDialog pProgressDialog, final int pColorResourceId) {
    // Allocate a new ProgressBar.
    final ProgressBar lProgressBar = new android.widget.ProgressBar(pContext, null, android.R.attr.progressBarStyle);
    // Configure the IndeterminateDrawable.
    lProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(pContext, pColorResourceId), android.graphics.PorterDuff.Mode.MULTIPLY);
    // Assign the ProgressBar to the ProgressDialog.
    pProgressDialog.setIndeterminateDrawable(lProgressBar.getIndeterminateDrawable());
}
</code>```

Body:
I am using ProgressDialog for showing progressbar

            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.setMessage(message);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

And it is coming like this

I want to change the green color of the circle to red. is there any way?

I tried

.getIndeterminateDrawable().setColorFilter(0xFFFFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY);

But not working.

Body:
If you'd like to define the colour ad-hoc, without needing inheritance or dedicated XML, you can use something like this:

/** Styles a ProgressDialog to use a themed Spinner. */
public void setStyledProgressDialog(final Context pContext, final ProgressDialog pProgressDialog, final int pColorResourceId) {
    // Allocate a new ProgressBar.
    final ProgressBar lProgressBar = new android.widget.ProgressBar(pContext, null, android.R.attr.progressBarStyle);
    // Configure the IndeterminateDrawable.
    lProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(pContext, pColorResourceId), android.graphics.PorterDuff.Mode.MULTIPLY);
    // Assign the ProgressBar to the ProgressDialog.
    pProgressDialog.setIndeterminateDrawable(lProgressBar.getIndeterminateDrawable());
}


问:
"sre_constants.error: nothing to repeat" error every time trying to install using pip
I just installed Python 2.7.5 on my Windows 10 machine and I also got pip installed through setuptools. However whenever I try to install something using pip e.g. pip install numpy, I get this error message:

```<code>Traceback (most recent call last):
  File "C:\Python27\Scripts\pip-script.py", line 8, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 318, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 2221, in load_entry_point
    return ep.load()
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 1954, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\__init__.py", line 26, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\utils\__init__.py", line 27, in <module>
    from pip._vendor import pkg_resources
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\pkg_resources\__init__.py", line 73, in <module>
    __import__('pip._vendor.packaging.specifiers')
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\packaging\specifiers.py", line 275, in <module>
    class Specifier(_IndividualSpecifier):
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\packaging\specifiers.py", line 373, in Specifier
    r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
  File "C:\Python27\Lib\re.py", line 190, in compile
    return _compile(pattern, flags)
  File "C:\Python27\Lib\re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat
</code>```

Since I'm pretty new to Python, I don't really understand what this error means. Any workaround?

答:
I had a similar issue with a library that is using regular expressions (with the re.compile() function). I solved this issue installing the last version available 2.7.13 (I run a Windows 7).
Before I had the 2.7.6 version. I updated it installing the new version with the .msi installer, available in the Python web page.</p>

Body:
I just installed Python 2.7.5 on my Windows 10 machine and I also got pip installed through setuptools. However whenever I try to install something using pip e.g. pip install numpy, I get this error message:

Traceback (most recent call last):
  File "C:\Python27\Scripts\pip-script.py", line 8, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 318, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 2221, in load_entry_point
    return ep.load()
  File "C:\Python27\lib\site-packages\pkg_resources.py", line 1954, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\__init__.py", line 26, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\utils\__init__.py", line 27, in <module>
    from pip._vendor import pkg_resources
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\pkg_resources\__init__.py", line 73, in <module>
    __import__('pip._vendor.packaging.specifiers')
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\packaging\specifiers.py", line 275, in <module>
    class Specifier(_IndividualSpecifier):
  File "C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor\packaging\specifiers.py", line 373, in Specifier
    r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
  File "C:\Python27\Lib\re.py", line 190, in compile
    return _compile(pattern, flags)
  File "C:\Python27\Lib\re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

Since I'm pretty new to Python, I don't really understand what this error means. Any workaround?


问:
How do I convert an NSMutableString into a regular NSString?
How can I convert a NSMutable String into a regular NSString?</p>

答: Try [NSString stringWithString: yourMutableString]


问:
Security implications of generating salts immediately vs. when needed
Say I have a database of users (customers).  Some of these customers have logged in through a portal, some of them have not and only exist in the database to facilitate customer management by an administrator.  At a later date, customers may decide to begin using the portal, at which point they'll need to be provided a password.

Assuming the randomization method is reasonably secure, are there any security implications related to the timing of the salt generation?

ie.: is it better, worse, or irrelevant to be salting all accounts as early as possible vs. salting only at the time a password is created?

答:
The main idea behind the salts, is to offer protection against rainbow tables, which are databases containing pre-hashed passwords. Having each password salted using a different salt allows you to minimize this risk, since now (in theory) there should be no rainbow table containing your password.

As long as you're using a cryptographically secure pseudo-random number generator (CSPRNG) to generate your salts, there should not be a problem with salting your passwords as early as possible (and it'll be even better if you use the salting mechanism already included in most modern implementations). After all, you only care about always producing a different hash. And salts are not even secret values, if your database got compromised, the attacker will already have the hashed password and the salt (they're usually stored like salt$base64HashedPassword, or they just have a column for the salt), and salts are not like the IVs in cipher block chaining (CBC) where an attacker can take advantage of a predictable IV. Here you only care about always producing a different hash, so as long as you do it, everything should be ok.

Edit: Now I'm curious about something. You're talking about salting the password someday in the future... does that mean that you're storing it as plaintext or in a recoverable way before salting it? Because now that'll be a bad practice. You need to salt it as soon as you get it, since you should not know anything about user's passwords.


问:
How to find specific columns from table?
The columns in my table are:

```<code>BWT_ID
BWT_NAME
BWT_SALARY
ADDRESS
JOB-TYPE
GENDER
</code>```

How do I fetch columns whose name starts with "BWT"?

答:
Use all_tab_columns

```<code> SELECT all_tab.COLUMN_NAME
 FROM all_tab_columns all_tab
 WHERE all_tab.TABLE_NAME = 'MY_TABLE'
 AND all_tab.COLUMN_NAME like 'BWT%'
</code>```

ALL_TAB_COLUMNS describes the columns of the tables, views, and clusters accessible to the current user.

Body:
The columns in my table are:

BWT_ID
BWT_NAME
BWT_SALARY
ADDRESS
JOB-TYPE
GENDER

How do I fetch columns whose name starts with "BWT"?

Body:
Use all_tab_columns

 SELECT all_tab.COLUMN_NAME
 FROM all_tab_columns all_tab
 WHERE all_tab.TABLE_NAME = 'MY_TABLE'
 AND all_tab.COLUMN_NAME like 'BWT%'

ALL_TAB_COLUMNS describes the columns of the tables, views, and clusters accessible to the current user.


答:
Your interface IRule<in TInput, out TOutput> is both covariant and contravariant, which means you can't covariantly cast it.  The contravariance prevents this.

Basically, your assignment var dbModel = (IRule<IDmModel, IDbModel>)new RuleB(); asserts that dbModel must accept any IDmModel parameter.  Unfortunately, this is not true; instances must be assignable to DmModel due to the concrete form of RuleA, so other derivatives of IDmModel would fail.

Title: Unable to cast object of generic type to generic interface C#


问:
Angular Validator.maxlength show message on keypress
I would like to show validation messages on keypress for certain validations such as max length. Currently, they show if you tab out or click out of the field.

Form group:

```<code>this.shortForm = this.fb.group({
  fName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]]
})
</code>```

template:

```<code><md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength') && shortForm.get('fName').touched">
      Maximum of 50 characters
 </md-error>
</md-input-container>
</code>```

Also does not work:

```<code><md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
      Maximum of 50 characters
 </md-error>
</md-input-container>
</code>```

How can I display the error message if the user input hits max-length on keypress instead of waiting for them to tab or click out?

Update:

If I move

```<code><md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
 Maximum of 50 characters
</md-error>
</code>```

to the outside of md-input-container, the error message displayed in keypress. Is this possibly a bug within angular material?

Update #2:
https://github.com/angular/material2/issues/4027

答:
The default Angular validation validates every time the value changes (so basically on keypress). You are however checking touched. That is what is making it wait for the user to tab or leave the field.

Just remove the .touched expression and it should work as you require.

Body:
I would like to show validation messages on keypress for certain validations such as max length. Currently, they show if you tab out or click out of the field.

Form group:

this.shortForm = this.fb.group({
  fName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]]
})

template:

<md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength') && shortForm.get('fName').touched">
      Maximum of 50 characters
 </md-error>
</md-input-container>

Also does not work:

<md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
      Maximum of 50 characters
 </md-error>
</md-input-container>

How can I display the error message if the user input hits max-length on keypress instead of waiting for them to tab or click out?

Update:

If I move

<md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
 Maximum of 50 characters
</md-error>

to the outside of md-input-container, the error message displayed in keypress. Is this possibly a bug within angular material?

Update #2:
https://github.com/angular/material2/issues/4027


问:
Algorithm to sum/stack values from a time series graph where data points don't match on time
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

```<code>S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)
</code>```

When added together, should result in:

```<code>ST: (1;100) (4;250) (5;200) (10;200) (18;250)
</code>```

Logic:

```<code>x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250
</code>```

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

答:
Something like this:

```<code>def join_series(s1, s2):
    S1 = iter(s1)
    S2 = iter(s2)
    value1 = 0
    value2 = 0
    time1, next1 = next(S1)
    time2, next2 = next(S2)
    end1 = False
    end2 = False

    while True:
        time = min(time1, time2)
        if time == time1:
            value1 = next1
            try:
                time1, next1 = next(S1)
            except StopIteration:
                end1 = True
                time1 = time2

        if time == time2:
            value2 = next2
            try:
                time2, next2 = next(S2)
            except StopIteration:
                end2 = True
                time2 = time1

        yield time, value1 + value2

        if end1 and end2:
            raise StopIteration

S1 = ((1, 100), (5, 100), (10, 100))
S2 = ((4, 150), (5, 100), (18, 150))

for result in join_series(S1, S2):
    print(result)
</code>```

It basically keeps the current value of S1 and S2, together with the next of S1 and S2, and steps through them based on which has the lowest "upcoming time". Should handle lists of different lengths to, and uses iterators all the way so it should be able to handle massive dataseries, etc, etc.

Body:
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)

When added together, should result in:

ST: (1;100) (4;250) (5;200) (10;200) (18;250)

Logic:

x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

Body:
Something like this:

def join_series(s1, s2):
    S1 = iter(s1)
    S2 = iter(s2)
    value1 = 0
    value2 = 0
    time1, next1 = next(S1)
    time2, next2 = next(S2)
    end1 = False
    end2 = False

    while True:
        time = min(time1, time2)
        if time == time1:
            value1 = next1
            try:
                time1, next1 = next(S1)
            except StopIteration:
                end1 = True
                time1 = time2

        if time == time2:
            value2 = next2
            try:
                time2, next2 = next(S2)
            except StopIteration:
                end2 = True
                time2 = time1

        yield time, value1 + value2

        if end1 and end2:
            raise StopIteration

S1 = ((1, 100), (5, 100), (10, 100))
S2 = ((4, 150), (5, 100), (18, 150))

for result in join_series(S1, S2):
    print(result)

It basically keeps the current value of S1 and S2, together with the next of S1 and S2, and steps through them based on which has the lowest "upcoming time". Should handle lists of different lengths to, and uses iterators all the way so it should be able to handle massive dataseries, etc, etc.


问:
Inno Setup unable to find and execute ie4uinit.exe on x64
I am trying to refresh the Windows icon cache using the well known and documented method of calling ie4uinit.exe -ClearIconCache for anything below Window 10 and ie4uinit.exe -Show on Windows 10 and above:

```<code>[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove
</code>```

Both commands work as expected when run in Explorer or at a command prompt. They also work correctly in Inno Setup when running on an x86 system. However, on an x64 system, the following error is produced:

The path to the file, using the {sys} constant, resolves correctly and the file exists and can be seen both in Explorer and in a directory listing at the command prompt:

The following variation of the above code, running through the command prompt, also fails in much the same way, although it is silent and only indicated by an exit code of 1 in the install log.

```<code>[Run]
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove
</code>```

I have already read clear icon cache in win 7 programmatically - execute ie4uinit.exe-ClearIconCache using C# or Visual Basic, which also has mention of this being a problem in Inno Setup (towards the bottom) and tried the workaround to copy the file and run it from elsewhere. However, attempting to copy the file to another location, using the FileCopy function, also failed to find it in C:\Windows\System32. I also tried running the same command in the [Code] section using the Exec function, but this also fails to find it in C:\Windows\System32.

I considered making a copy of the file and installing it to the temp directory to run it from there, but this file is a different version on each Windows version, so this is not really a viable solution, especially as, being a system file, it may also change in the future.

The accepted answer in the above question seems to be to build the executable for 'Any CPU' rather than 'x86'. However, I am not sure if this can be done in Inno Setup and also if doing so would have any unforeseen side effects on the installers behaviour?

Is there any way to resolve or work around this in Inno Setup?

答:
A far simpler and better solution (thanks for the links Martin) is to have two duplicated [Run] entries for x64 with Check: IsWin64 and Flags: 64bit and to add Check: not IsWin64 to the original lines:

```<code>[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove and not IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove and not IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden 64bit; Check: not IsWindows10AndAbove and IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden 64bit; Check: IsWindows10AndAbove and IsWin64
</code>```

Body:
I am trying to refresh the Windows icon cache using the well known and documented method of calling ie4uinit.exe -ClearIconCache for anything below Window 10 and ie4uinit.exe -Show on Windows 10 and above:

[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove

Both commands work as expected when run in Explorer or at a command prompt. They also work correctly in Inno Setup when running on an x86 system. However, on an x64 system, the following error is produced:

The path to the file, using the {sys} constant, resolves correctly and the file exists and can be seen both in Explorer and in a directory listing at the command prompt:

The following variation of the above code, running through the command prompt, also fails in much the same way, although it is silent and only indicated by an exit code of 1 in the install log.

[Run]
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove

I have already read clear icon cache in win 7 programmatically - execute ie4uinit.exe-ClearIconCache using C# or Visual Basic, which also has mention of this being a problem in Inno Setup (towards the bottom) and tried the workaround to copy the file and run it from elsewhere. However, attempting to copy the file to another location, using the FileCopy function, also failed to find it in C:\Windows\System32. I also tried running the same command in the [Code] section using the Exec function, but this also fails to find it in C:\Windows\System32.

I considered making a copy of the file and installing it to the temp directory to run it from there, but this file is a different version on each Windows version, so this is not really a viable solution, especially as, being a system file, it may also change in the future.

The accepted answer in the above question seems to be to build the executable for 'Any CPU' rather than 'x86'. However, I am not sure if this can be done in Inno Setup and also if doing so would have any unforeseen side effects on the installers behaviour?

Is there any way to resolve or work around this in Inno Setup?

Body:
A far simpler and better solution (thanks for the links Martin) is to have two duplicated [Run] entries for x64 with Check: IsWin64 and Flags: 64bit and to add Check: not IsWin64 to the original lines:

[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove and not IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove and not IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden 64bit; Check: not IsWindows10AndAbove and IsWin64
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden 64bit; Check: IsWindows10AndAbove and IsWin64


问:
How to pass array by HiddenType?
I'm having trouble, I'm trying to pass an array by a form to the twig template, the idea I had is to pass it via an HiddenType.

I can pass a string, but I can't pass an array, I get an "Array to string conversion" error.

Here is the code :

```<code>$builder->add(
                'existingManagementWorkUnitLabels',
                HiddenType::class,
                [
                    'mapped' => false,
                    'data' => $existingManagementWorkUnitLabels,
                ]
            )
</code>```

If someone has an idea.
Thank you.

答:
How about serializing the array and doing it like this:

```<code>$builder->add(
                'existingManagementWorkUnitLabels',
                HiddenType::class,
                [
                    'mapped' => false,
                    'data' => serialize($existingManagementWorkUnitLabels),
                ]
            )
</code>```

Within twig you can do:

```<code>$filter = new Twig_SimpleFilter('unserialize', 'unserialize');
$twig->addFilter($filter);
</code>```

and then:

```<code>do {% for value in (array|unserialize) %}
</code>```

Title: How to pass array by HiddenType?

Body:
I'm having trouble, I'm trying to pass an array by a form to the twig template, the idea I had is to pass it via an HiddenType.

I can pass a string, but I can't pass an array, I get an "Array to string conversion" error.

Here is the code :

$builder->add(
                'existingManagementWorkUnitLabels',
                HiddenType::class,
                [
                    'mapped' => false,
                    'data' => $existingManagementWorkUnitLabels,
                ]
            )

If someone has an idea.
Thank you.

Body:
How about serializing the array and doing it like this:

$builder->add(
                'existingManagementWorkUnitLabels',
                HiddenType::class,
                [
                    'mapped' => false,
                    'data' => serialize($existingManagementWorkUnitLabels),
                ]
            )

Within twig you can do:

$filter = new Twig_SimpleFilter('unserialize', 'unserialize');
$twig->addFilter($filter);

and then:

do {% for value in (array|unserialize) %}