问:
Assigning a ArrayList after initializing it in Java
I am new to Java and I have a silly question. Here's my pseudocode:

```<code>private static Map<String, ArrayList<byte[]> > myMap = new HashMap<String,ArrayList<byte[]> >();
public void setValue(String key, byte[] value) {
  ArrayList<byte[]> valueList = new ArrayList<byte[]>();
  if(this.myMap.containsKey(key))
  {
       valueList = this.myMap.get(key);
  }
  valueList.add(value);
  this.myMap.put(key, valueList);
}
</code>```

What I am trying to do is to check if the given key already has some value in the map. If yes, it will retrieve the list of values and add the new value to this list.
If not, it will add a new key and list of value (with just one value) in the map.

My question is about initializing the ArrayList with 'new' and then assigning it the value returned by this.myMap.get(key). Is it a good way to do it? In C++ it will be an issue. I am not sure about Java. What do you think?

答:
Your attempt is a reasonable way to achieve what you ask. The classic way of doing this, though, is to attempt to retrieve and then to populate it if no value was retrieved:

```<code>Map<String, ArrayList<byte[]>> myMap = new HashMap<>();

public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.get(key);
    if (valueList == null) {
        valueList = new ArrayList<>();
        this.myMap.put(key, valueList);
    }
    valueList.add(value);
}
</code>```

This saves one key lookup and one value insertion and consolidates the initialization logic to 4 consecutive lines.

If you are using Java 8, then you can do even better by using the Map#computeIfAbsent method. This is more efficient, more concise, and has the added advantage of maintaining concurrency constraints for map implementations that support concurrent operations:

```<code>public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.computeIfAbsent(key, k -> new ArrayList<>());
    valueList.add(value);
}
</code>```

Or even more concisely:

```<code>public void setValue(String key, byte[] value) {
    this.myMap.computeIfAbsent(key, k -> new ArrayList<>())
            .add(value);
}
</code>```

Body:
I am new to Java and I have a silly question. Here's my pseudocode:

private static Map<String, ArrayList<byte[]> > myMap = new HashMap<String,ArrayList<byte[]> >();
public void setValue(String key, byte[] value) {
  ArrayList<byte[]> valueList = new ArrayList<byte[]>();
  if(this.myMap.containsKey(key))
  {
       valueList = this.myMap.get(key);
  }
  valueList.add(value);
  this.myMap.put(key, valueList);
}

What I am trying to do is to check if the given key already has some value in the map. If yes, it will retrieve the list of values and add the new value to this list.
If not, it will add a new key and list of value (with just one value) in the map.

My question is about initializing the ArrayList with 'new' and then assigning it the value returned by this.myMap.get(key). Is it a good way to do it? In C++ it will be an issue. I am not sure about Java. What do you think?

Body:
Your attempt is a reasonable way to achieve what you ask. The classic way of doing this, though, is to attempt to retrieve and then to populate it if no value was retrieved:

Map<String, ArrayList<byte[]>> myMap = new HashMap<>();

public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.get(key);
    if (valueList == null) {
        valueList = new ArrayList<>();
        this.myMap.put(key, valueList);
    }
    valueList.add(value);
}

This saves one key lookup and one value insertion and consolidates the initialization logic to 4 consecutive lines.

If you are using Java 8, then you can do even better by using the Map#computeIfAbsent method. This is more efficient, more concise, and has the added advantage of maintaining concurrency constraints for map implementations that support concurrent operations:

public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.computeIfAbsent(key, k -> new ArrayList<>());
    valueList.add(value);
}

Or even more concisely:

public void setValue(String key, byte[] value) {
    this.myMap.computeIfAbsent(key, k -> new ArrayList<>())
            .add(value);
}


来源: stackexchange

问:
QBWC1012: Authentication failed due to following error message. Index was outside the bounds of the array
I am integrating QuickBooks Desktop Enterprise 2013 with a web app using the Web Connector version 2.1.0.30 as an intermediary.
The SOAP service I developed with WCF in Visual Studio Core, and the Web Connector accesses without problems to my services, here I show the execution log of the web connector

Blockquote
  20170811.21:39:26 UTC   : QBWebConnector.WebServiceManager.DoUpdateSelected() : updateWS() for application = 'WCService' has STARTED
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.getUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock = FALSE
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock has been set to True
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : ********************* Update session locked *********************
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : Initiated connection to the following application.
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppName: WCService
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppUniqueName (if available): WCService
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppURL: http://localhost:14319/WCService.svc
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_serverVersion() :  Calling serverVersion().
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_serverVersion() : Received from serverVersion() following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() :  Calling clientVersion() with following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() : Received from clientVersion() following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() : This application agrees with the current version of QBWebConnector. Allowing update operation.
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : Authenticating to application 'WCService', username = 'Dalo'
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : * Calling authenticate() with following parameters:
  **20170811.21:39:28 UTC : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
  Índice fuera de los límites de la matriz.
  More info:
  StackTrace =    en QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
  Source = QBWebConnector
  20170811.21:39:28 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock has been set to False
  20170811.21:39:28 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : ********************* Update session unlocked *********************
  20170811.21:39:28 UTC   : QBWebConnector.WebServiceManager.DoUpdateSelected() : Update completed with errors. See log (QWClog.txt) for details.
  Blockquote

Now I show you my QWC file

<?xml version="1.0"?>
<QBWCXML>
  <AppDescription>QB Web Service</AppDescription>
  <AppID></AppID>
  <AppName>WCService</AppName>
  <AppSupport>http://localhost:14319/WCService.svc?wsdl</AppSupport>
  <AppURL>http://localhost:14319/WCService.svc</AppURL>
  <FileID>{CA1C3EB8-1B61-4747-A743-8D5B438B83AC}</FileID>
  <OwnerID>{8C809D2B-69A9-4B43-A9D0-D41C0938368B}</OwnerID>
  <QBType>QBFS</QBType>

  <UserName>Dalo</UserName>
</QBWCXML>
```

<p>Then the service code:</p>

```public string[] authenticate(string strUserName, string strPassword)
    {
        string evLogTxt = "WebMethod: authenticate() has been called by QBWebconnector" + "\r\n\r\n";
        evLogTxt = evLogTxt + "Parameters received:\r\n";
        evLogTxt = evLogTxt + "string strUserName = " + strUserName + "\r\n";
        evLogTxt = evLogTxt + "string strPassword = " + strPassword + "\r\n";
        evLogTxt = evLogTxt + "\r\n";

        string[] authReturn = new string[3];
        // Code below uses a random GUID to use as session ticket
        // An example of a GUID is {85B41BEE-5CD9-427a-A61B-83964F1EB426}
        authReturn[0] = System.Guid.NewGuid().ToString();

        // For simplicity of sample, a hardcoded username/password is used.
        // In real world, you should handle authentication in using a standard way.
        // For example, you could validate the username/password against an LDAP
        // or a directory server
        string pwd = "password";
        evLogTxt = evLogTxt + "Password locally stored = " + pwd + "\r\n";
        if (strUserName.Trim().Equals("Dalo") && strPassword.Trim().Equals(pwd))
        {
            // An empty string for authReturn[1] means asking QBWebConnector
            // to connect to the company file that is currently openned in QB
            authReturn[1] = "C:\\Users\\Dalo\\Documents\\company.QBW";
            authReturn[2] = "10";
        }
        else
        {
            authReturn[1] = "nvu";
            authReturn[2] = "";
        }
        // You could also return "none" to indicate there is no work to do
        // or a company filename in the format C:\full\path\to\company.qbw
        // based on your program logic and requirements.

        evLogTxt = evLogTxt + "\r\n";
        evLogTxt = evLogTxt + "Return values: " + "\r\n";
        evLogTxt = evLogTxt + "string[] authReturn[0] = " + authReturn[0].ToString() + "\r\n";
        evLogTxt = evLogTxt + "string[] authReturn[1] = " + authReturn[1].ToString();
        logEvent(evLogTxt);
        return authReturn;
    }
```

<p>Other data:</p>

<ol>
<li><p>The authenticate service was tested with the Visual Studio WCF Test Client tool.</p></li>
<li><p>In code debugging, when the authentication fails, the web connector calls neither the connectionError service nor the closeConnection to terminate the connection.</p></li>
<li><p>In debugging the code, you can see that the whole code of the authenticate service is run without throwing any exceptions.</p></li>
</ol>

<p>This's response </p>

<pre class="lang-xml prettyprint-override"><code>    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Body>
            <authenticateResponse xmlns="http://developer.intuit.com/">
                <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                    <a:string>bd68a1e2-7780-46ed-bb8a-09b2b25e156f</a:string>
                    <a:string>C:\Users\Dalo\Documents\company.QBW</a:string>
                </authenticateResult>
            </authenticateResponse>
        </s:Body>
    </s:Envelope>
</code>```

答:
I was having this same problem while trying to build the web service in Go, and Intuits QBWC documentation seems to be pretty outdated and incomplete.  I found that this soap 1.2 version seems to work.

```<code><?xml version="1.0" encoding="utf-8"?>
        <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
          <soap12:Body>
            <authenticateResponse xmlns="http://developer.intuit.com/">
              <authenticateResult>
                <string>123a</string>
                <string></string>
              </authenticateResult>
            </authenticateResponse>
          </soap12:Body>
        </soap12:Envelope>
</code>```

This was found here:
https://test.developer.intuit.com/QBWC/TroubleshootWebServiceFS/Service.asmx

ContentLicense: CC BY-SA 3.0

Body:
I am integrating QuickBooks Desktop Enterprise 2013 with a web app using the Web Connector version 2.1.0.30 as an intermediary.
The SOAP service I developed with WCF in Visual Studio Core, and the Web Connector accesses without problems to my services, here I show the execution log of the web connector

Blockquote
  20170811.21:39:26 UTC   : QBWebConnector.WebServiceManager.DoUpdateSelected() : updateWS() for application = 'WCService' has STARTED
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.getUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock = FALSE
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock has been set to True
  20170811.21:39:26 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : ********************* Update session locked *********************
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : Initiated connection to the following application.
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppName: WCService
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppUniqueName (if available): WCService
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.instantiateWebService() : AppURL: http://localhost:14319/WCService.svc
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_serverVersion() :  Calling serverVersion().
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_serverVersion() : Received from serverVersion() following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() :  Calling clientVersion() with following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() : Received from clientVersion() following parameter:
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_clientVersion() : This application agrees with the current version of QBWebConnector. Allowing update operation.
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : Authenticating to application 'WCService', username = 'Dalo'
  20170811.21:39:26 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : * Calling authenticate() with following parameters:
  **20170811.21:39:28 UTC : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
  Índice fuera de los límites de la matriz.
  More info:
  StackTrace =    en QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
  Source = QBWebConnector
  20170811.21:39:28 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : HKEY_CURRENT_USER\Software\Intuit\QBWebConnector\UpdateLock has been set to False
  20170811.21:39:28 UTC   : QBWebConnector.RegistryManager.setUpdateLock() : ********************* Update session unlocked *********************
  20170811.21:39:28 UTC   : QBWebConnector.WebServiceManager.DoUpdateSelected() : Update completed with errors. See log (QWClog.txt) for details.
  Blockquote

Now I show you my QWC file

<?xml version="1.0"?>
<QBWCXML>
  <AppDescription>QB Web Service</AppDescription>
  <AppID></AppID>
  <AppName>WCService</AppName>
  <AppSupport>http://localhost:14319/WCService.svc?wsdl</AppSupport>
  <AppURL>http://localhost:14319/WCService.svc</AppURL>
  <FileID>{CA1C3EB8-1B61-4747-A743-8D5B438B83AC}</FileID>
  <OwnerID>{8C809D2B-69A9-4B43-A9D0-D41C0938368B}</OwnerID>
  <QBType>QBFS</QBType>

  <UserName>Dalo</UserName>
</QBWCXML>

Then the service code:

public string[] authenticate(string strUserName, string strPassword)
    {
        string evLogTxt = "WebMethod: authenticate() has been called by QBWebconnector" + "\r\n\r\n";
        evLogTxt = evLogTxt + "Parameters received:\r\n";
        evLogTxt = evLogTxt + "string strUserName = " + strUserName + "\r\n";
        evLogTxt = evLogTxt + "string strPassword = " + strPassword + "\r\n";
        evLogTxt = evLogTxt + "\r\n";

        string[] authReturn = new string[3];
        // Code below uses a random GUID to use as session ticket
        // An example of a GUID is {85B41BEE-5CD9-427a-A61B-83964F1EB426}
        authReturn[0] = System.Guid.NewGuid().ToString();

        // For simplicity of sample, a hardcoded username/password is used.
        // In real world, you should handle authentication in using a standard way.
        // For example, you could validate the username/password against an LDAP
        // or a directory server
        string pwd = "password";
        evLogTxt = evLogTxt + "Password locally stored = " + pwd + "\r\n";
        if (strUserName.Trim().Equals("Dalo") && strPassword.Trim().Equals(pwd))
        {
            // An empty string for authReturn[1] means asking QBWebConnector
            // to connect to the company file that is currently openned in QB
            authReturn[1] = "C:\\Users\\Dalo\\Documents\\company.QBW";
            authReturn[2] = "10";
        }
        else
        {
            authReturn[1] = "nvu";
            authReturn[2] = "";
        }
        // You could also return "none" to indicate there is no work to do
        // or a company filename in the format C:\full\path\to\company.qbw
        // based on your program logic and requirements.

        evLogTxt = evLogTxt + "\r\n";
        evLogTxt = evLogTxt + "Return values: " + "\r\n";
        evLogTxt = evLogTxt + "string[] authReturn[0] = " + authReturn[0].ToString() + "\r\n";
        evLogTxt = evLogTxt + "string[] authReturn[1] = " + authReturn[1].ToString();
        logEvent(evLogTxt);
        return authReturn;
    }

Other data:

The authenticate service was tested with the Visual Studio WCF Test Client tool.

In code debugging, when the authentication fails, the web connector calls neither the connectionError service nor the closeConnection to terminate the connection.

In debugging the code, you can see that the whole code of the authenticate service is run without throwing any exceptions.

This's response

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Body>
            <authenticateResponse xmlns="http://developer.intuit.com/">
                <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                    bd68a1e2-7780-46ed-bb8a-09b2b25e156f
                    C:\Users\Dalo\Documents\company.QBW
                </authenticateResult>
            </authenticateResponse>
        </s:Body>
    </s:Envelope>

Body:
I was having this same problem while trying to build the web service in Go, and Intuits QBWC documentation seems to be pretty outdated and incomplete.  I found that this soap 1.2 version seems to work.

<?xml version="1.0" encoding="utf-8"?>
        <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
          <soap12:Body>
            <authenticateResponse xmlns="http://developer.intuit.com/">
              <authenticateResult>
                <string>123a</string>
                <string></string>
              </authenticateResult>
            </authenticateResponse>
          </soap12:Body>
        </soap12:Envelope>

This was found here:
https://test.developer.intuit.com/QBWC/TroubleshootWebServiceFS/Service.asmx


问:
Querying customer change log for earliest record to determine the user that created the record
I am trying to report on which users created a given record in our customer table. Unfortunately it only shows the last user to modify the record. There is a change log though so I need to pull the earliest record for a given customer and pull the id of the change user.

So I have this:

```<code>SELECT min(ca.archive_date),
ca.cust_no,
ca.change_user
FROM mi_masdb.dbo.customer_archive ca
GROUP BY ca.cust_no
</code>```

but it won't pull the change user because there are multiple change users for each cust_no. I just need it to pull the change user associated with the earliest archive date for each cust_no.

Thoughts?

答:
The canonical way of doing this uses row_number():

```<code>SELECT ca.*
FROM (SELECT ca.*, ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY archive_date) as seqnum
      FROM mi_masdb.dbo.customer_archive ca
     ) ca
WHERE seqnum = 1;
</code>```

The following might be faster:

```<code>select ca.*
from mi_masdb.dbo.customer_archive ca join
     (select ca2.cust_no, min(ca2.archive_date) as min_archive_date
      from mi_masdb.dbo.customer_archive ca2
     ) ca2
     on ca2.cust_no = ca.cust_no and ca2.min_archive_date = ca.archive_date;
</code>```

Body:
I am trying to report on which users created a given record in our customer table. Unfortunately it only shows the last user to modify the record. There is a change log though so I need to pull the earliest record for a given customer and pull the id of the change user.

So I have this:

SELECT min(ca.archive_date),
ca.cust_no,
ca.change_user
FROM mi_masdb.dbo.customer_archive ca
GROUP BY ca.cust_no

but it won't pull the change user because there are multiple change users for each cust_no. I just need it to pull the change user associated with the earliest archive date for each cust_no.

Thoughts?

Body:
The canonical way of doing this uses row_number():

SELECT ca.*
FROM (SELECT ca.*, ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY archive_date) as seqnum
      FROM mi_masdb.dbo.customer_archive ca
     ) ca
WHERE seqnum = 1;

The following might be faster:

select ca.*
from mi_masdb.dbo.customer_archive ca join
     (select ca2.cust_no, min(ca2.archive_date) as min_archive_date
      from mi_masdb.dbo.customer_archive ca2
     ) ca2
     on ca2.cust_no = ca.cust_no and ca2.min_archive_date = ca.archive_date;


问:
How to get list of all tables that has identity columns
I would like to learn how to fetch list of all tables that has identity columns from a MS SQL database.</p>

答:
The script below will do:</p>

```<code>SELECT a.name as TableName,
  CASE WHEN b.name IS NULL
    THEN 'No Identity Column'
    ELSE b.name
  END as IdentityColumnName
FROM sys.tables a
  LEFT JOIN sys.identity_columns b on a.object_id = b.object_id
</code>```

Body:
The script below will do:

SELECT a.name as TableName,
  CASE WHEN b.name IS NULL
    THEN 'No Identity Column'
    ELSE b.name
  END as IdentityColumnName
FROM sys.tables a
  LEFT JOIN sys.identity_columns b on a.object_id = b.object_id


问:
How to read integers elegantly using C++ stream?
I have a file full of lines in this format:

```<code>1 - 2: 3
</code>```

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

答:
You can use a locale to change what things are read from the file as it is being read.  That is, you will filter out all non-numeric values:

```<code>struct numeric_only: std::ctype<char>
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask>
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

std::fstream myFile("foo.txt");
myfile.imbue(std::locale(std::locale(), new numeric_only()));
</code>```

Then when you read your file, it'll convert all non digits to spaces while leaving you only the numbers.  After that, you can simply use your normal conversions to transform what is being read into ints.

```<code>std::vector<int> intFromFile;
std::istream_iterator<int> myFileIter(myFile);
std::istream_iterator<int> eos;
std::copy(myFileIter, eos, std::back_inserter(intFromFile));
</code>```

Response to the comments below:

Here is what I did to get it to work

```<code>int main(int args, char** argv){
    std::fstream blah;
    blah.open("foo.txt", std::fstream::in);
    if(!blah.is_open()){
        std::cout << "no file";
        return 0;
    }
    blah.imbue(std::locale(std::locale(), new numeric_only()));

    std::vector<int> intFromFile;
    std::istream_iterator<int> myFileIter(blah);
    std::istream_iterator<int> eos;
    std::copy(myFileIter, eos, std::back_inserter(intFromFile));

   return 0;
}
</code>```

And this put only the ints into the vector, nothing more, nothing less.  The reason it wasn't working before was two fold:

I was filling up to '9' but not '9' itself.  I've changed the fill to ':'

Numbers larger than what an int can hold are a problem.  I'd suggest using longs.

ContentLicense: CC BY-SA 2.5

Body:
I have a file full of lines in this format:

1 - 2: 3

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

Body:
You can use a locale to change what things are read from the file as it is being read.  That is, you will filter out all non-numeric values:

struct numeric_only: std::ctype<char>
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask>
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

std::fstream myFile("foo.txt");
myfile.imbue(std::locale(std::locale(), new numeric_only()));

Then when you read your file, it'll convert all non digits to spaces while leaving you only the numbers.  After that, you can simply use your normal conversions to transform what is being read into ints.

std::vector<int> intFromFile;
std::istream_iterator<int> myFileIter(myFile);
std::istream_iterator<int> eos;
std::copy(myFileIter, eos, std::back_inserter(intFromFile));

Response to the comments below:

Here is what I did to get it to work

int main(int args, char** argv){
    std::fstream blah;
    blah.open("foo.txt", std::fstream::in);
    if(!blah.is_open()){
        std::cout << "no file";
        return 0;
    }
    blah.imbue(std::locale(std::locale(), new numeric_only()));

    std::vector<int> intFromFile;
    std::istream_iterator<int> myFileIter(blah);
    std::istream_iterator<int> eos;
    std::copy(myFileIter, eos, std::back_inserter(intFromFile));

   return 0;
}

And this put only the ints into the vector, nothing more, nothing less.  The reason it wasn't working before was two fold:

I was filling up to '9' but not '9' itself.  I've changed the fill to ':'

Numbers larger than what an int can hold are a problem.  I'd suggest using longs.


问:
Save scraped data csv file from inside docker container to local host
I run a python webscraper to collect articles off various websites, which I then save as csv files. I have been running these manually, but recently have been trying to run them in google cloud shell. I had some trouble with the dependencies, so I decided to build a docker image to run my python scraper

So far, I have managed to create a Dockerfile that I use to build a container with all necessary dependencies.

```<code>FROM python:3
# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
RUN pip install lxml
COPY Fin24 ./Fin24
COPY scraped_list.csv ./scraped_list.csv

# Run fin24.py when the container launches
CMD ["python3", "fin24.py"]
</code>```

fin24.py contains my scraper. Fin24 is a txt file that holds all the base urls that my scraper crawls for article links, before going into each article and extracting content. scraped_list.csv contains all previous websites I have scraped, which my python script checks to make sure I don't scrape the same article again.

After running the above, I can see it works. The python script stops after all websites it found are scraped. However, I am guessing it is saving the csv file (output) inside the docker container. How could I get it to save it to the directory off of which I am running docker?

Ultimately I want to simply upload the Dockerfile to my Google cloud shell, and run it as a cronjob, and save all output inside the shell. Any help would be much appreciated

答:
You will require to mount that path in your docker deployment. For that you need to do two things:
1. Add a volume in your Dockerfile

```<code>WORKDIR /path/in/container
VOLUME ["/path/in/container"]
</code>```

2. run your container with -v option

```<code>docker run -i -t -v /path/on/host:/path/in/container:rw "container name"
</code>```

Body:
I run a python webscraper to collect articles off various websites, which I then save as csv files. I have been running these manually, but recently have been trying to run them in google cloud shell. I had some trouble with the dependencies, so I decided to build a docker image to run my python scraper

So far, I have managed to create a Dockerfile that I use to build a container with all necessary dependencies.

FROM python:3
# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
RUN pip install lxml
COPY Fin24 ./Fin24
COPY scraped_list.csv ./scraped_list.csv

# Run fin24.py when the container launches
CMD ["python3", "fin24.py"]

fin24.py contains my scraper. Fin24 is a txt file that holds all the base urls that my scraper crawls for article links, before going into each article and extracting content. scraped_list.csv contains all previous websites I have scraped, which my python script checks to make sure I don't scrape the same article again.

After running the above, I can see it works. The python script stops after all websites it found are scraped. However, I am guessing it is saving the csv file (output) inside the docker container. How could I get it to save it to the directory off of which I am running docker?

Ultimately I want to simply upload the Dockerfile to my Google cloud shell, and run it as a cronjob, and save all output inside the shell. Any help would be much appreciated

Body:
You will require to mount that path in your docker deployment. For that you need to do two things:
1. Add a volume in your Dockerfile

WORKDIR /path/in/container
VOLUME ["/path/in/container"]

2. run your container with -v option

docker run -i -t -v /path/on/host:/path/in/container:rw "container name"


问:
delete duplicates values and keep order of elements
How we can remove duplicated values between list1 and list2 from list1 while saving its order?

Example of my code:

```<code>list1=[(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
list2=[(1,1),(1,2)]

list1 = list(set(list1) - set(list2))
print (list1)
</code>```

output

[(5, 4), (1, 3), (3, 4), (4, 7)]

expected output

[(1,3),(3,4),(5,4),(4,7)]

答:
Well, a set hashes the elements internally, and so will never be able to maintain the order. If your elements within list are guaranteed to be unique, i.e., they appear only once, you can use the set to filter the elements required:

```<code>In [26]: list1 = [(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2 = [(1,1),(1,2)]
    ...: unique = set(list1) - set(list2)
    ...: list1 = [x for x in list1 if x in unique]
    ...: print (list1)
    ...:
[(1, 3), (3, 4), (5, 4), (4, 7)]
</code>```

In case the same element can be present multiple times within the lists, and you need to keep track of unique number of distinct elements, you will need to maintain a count as well now. Due to which, the logic would look something like:

```<code>In [29]: list1=[(1,1),(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2=[(1,1),(1,2)]
    ...:
    ...: from collections import Counter
    ...:
    ...: count = Counter(list1)
    ...: for element in list2:
    ...:     if element in count:
    ...:         count[element] -= 1
    ...:
    ...: result = []
    ...: for element in list1:
    ...:     if count.get(element, 0) > 0:
    ...:         count[element] -= 1
    ...:         result.append(element)
    ...:
    ...: print (result)
    ...:
[(1, 1), (1, 3), (3, 4), (5, 4), (4, 7)]
</code>```

Body:
How we can remove duplicated values between list1 and list2 from list1 while saving its order?

Example of my code:

list1=[(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
list2=[(1,1),(1,2)]

list1 = list(set(list1) - set(list2))
print (list1)

output

[(5, 4), (1, 3), (3, 4), (4, 7)]

expected output

[(1,3),(3,4),(5,4),(4,7)]

Body:
Well, a set hashes the elements internally, and so will never be able to maintain the order. If your elements within list are guaranteed to be unique, i.e., they appear only once, you can use the set to filter the elements required:

In [26]: list1 = [(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2 = [(1,1),(1,2)]
    ...: unique = set(list1) - set(list2)
    ...: list1 = [x for x in list1 if x in unique]
    ...: print (list1)
    ...:
[(1, 3), (3, 4), (5, 4), (4, 7)]

In case the same element can be present multiple times within the lists, and you need to keep track of unique number of distinct elements, you will need to maintain a count as well now. Due to which, the logic would look something like:

In [29]: list1=[(1,1),(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2=[(1,1),(1,2)]
    ...:
    ...: from collections import Counter
    ...:
    ...: count = Counter(list1)
    ...: for element in list2:
    ...:     if element in count:
    ...:         count[element] -= 1
    ...:
    ...: result = []
    ...: for element in list1:
    ...:     if count.get(element, 0) > 0:
    ...:         count[element] -= 1
    ...:         result.append(element)
    ...:
    ...: print (result)
    ...:
[(1, 1), (1, 3), (3, 4), (5, 4), (4, 7)]


问:
Replace tab with space using Bash parameter substitution
How can I use ${var//Pattern/Replacement} to replace tab with space?

${var//\t/ } doesn't work for me.

答:
Adding here since typing an actual tab character through PuTTY into a bash shell is not so simple. CTRL V TAB doesn't work since CTRL V is captured in windows as paste.

Instead I use:

```<code>${var//$'\t'/ }
</code>```

Example:

```<code>$ var="te"$'\t'"st"

$ echo $var
te st

$ echo ${var//$'\t'/i}
teist
</code>```

Body:
Adding here since typing an actual tab character through PuTTY into a bash shell is not so simple. CTRL V TAB doesn't work since CTRL V is captured in windows as paste.

Instead I use:

${var//$'\t'/ }

Example:

$ var="te"$'\t'"st"

$ echo $var
te st

$ echo ${var//$'\t'/i}
teist


问:
Generate multiple sheets in one pdf file
I am trying to generate a pdf from a Tableau workbook which has two sheets using the url method:
E.g: https://TableauServer/views/workbook/sheet1?:format=pdf&parameter=value

I am doing this in a program which will issue the url request to the url. The url works fine for one sheet. But the problem is how to generate one pdf file with both sheets in it?

答: If you first put your two sheets into a single dashboard and then use the URL for the published dashboard (still using the format=pdf parameter), this should work just fine.


问:
Parse Form Data in Perl to remove all non alphanumeric / punctuation
In web form entries we are seeing  strange characters being used such as:

â€™ (windows 1252 encoded)

or

ðŸ’• (emoji)

or

Ã¢Â€Â¬ (no idea but think it's windows 1252)

For some of them I can use a regex to simply replace them with the utf-8 equivalent but I would prefer to use some sort of regex or encoding that efficiently removes them.

I've set the DB Table in MYSQL to utf-8

What is the best and most ideal solution for this in perl?  Or can I do it in the mysql table instead?

答:
â€™ is U+2019 RIGHT SINGLE QUOTATION MARK (’) encoded using UTF-8, then displayed on a cp1252 terminal.

ðŸ’• is U+1F495 TWO HEARTS () similarly mistreated.

Ã¢Â€Â¬is U+202C POP DIRECTIONAL FORMATTING encoded using UTF-8, then encoded using UTF-8 a second time, then displayed on a cp1252 terminal.

What is the best and most ideal solution for this in perl? Or can I do it in the mysql table instead?

Depends.

If there's a bug in your Perl program, you should fix it!

If the data is bad in the database, you should fix that (and whatever is putting bad data in the database)!

As it stands, you provided no evidence one way or another. (Providing the field's encoding and SELECT HEX(field) would reveal if the data is in the database or not.)


问:
Java maven project building with clean, install, run as
Many times I find that for my changes to take effect while working on a Maven/java project I need to Maven clean -> Maven install -> run as ..

How can I automate this in Eclipse?
So every time Im running the application it would clean, install then run

答:
Install the m2Eclipse plugin in your eclipse
http://www.eclipse.org/m2e/

or create bat file in your project with command mvn clean install


问:
Where statement with two criteria SQL
I have got pretty much everything in order apart from the last statement.

I am hoping for the query to narrow down my searches further and place a statement that says if one of the records within agencyprofilesetupcomplete is 0 then look to see if the date in agencyprofilecreateddate is less than 90 days of todays date, if it is I want to also include those results.

```<code>select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and agencyemployertaxoffice is not null
   and agencyemployertaxoffice <>''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate >=
           (GetDate()-90))
order by agencyprofilename
</code>```

I'm also using Microsoft SQL Server if you need to know.

答:
I think you can try by grouping your first group of condition. For example </p>

```<code>SELECT DISTINCT agencyprofilename
    ,(
        SELECT TOP 1 agencypayperiodfinalisestate
        FROM agencypayperiod AS app
        WHERE app.agencyprofileid = ap.agencyprofileid
        ORDER BY agencypayperiodpaydate
        ) AS 'Pay Period Finalise State'
    ,agencyprofilecreateddate
    ,agencyprofilesetupcomplete
    ,agencyemployertaxoffice
FROM Agencyprofile AS ap
LEFT JOIN agencypayperiod AS app ON ap.agencyprofileid = app.agencyprofileid
LEFT OUTER JOIN agencyemployer AS ae ON ap.agencyemployerid = ae.agencyemployerid
WHERE (
        agencypayperiodfinalisestate <> 0
        AND agencyemployertaxoffice IS NOT NULL
        AND agencyemployertaxoffice <> ''
        )
    OR (
        agencyprofilesetupcomplete = 0
        AND agencyprofilecreateddate < DATEADD(dd,1,(GetDate() - 90))
        )
ORDER BY agencyprofilename
</code>```

Title: Where statement with two criteria SQL

Body:
I have got pretty much everything in order apart from the last statement.

I am hoping for the query to narrow down my searches further and place a statement that says if one of the records within agencyprofilesetupcomplete is 0 then look to see if the date in agencyprofilecreateddate is less than 90 days of todays date, if it is I want to also include those results.

select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and agencyemployertaxoffice is not null
   and agencyemployertaxoffice <>''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate >=
           (GetDate()-90))
order by agencyprofilename

I'm also using Microsoft SQL Server if you need to know.

Body:
I think you can try by grouping your first group of condition. For example

SELECT DISTINCT agencyprofilename
    ,(
        SELECT TOP 1 agencypayperiodfinalisestate
        FROM agencypayperiod AS app
        WHERE app.agencyprofileid = ap.agencyprofileid
        ORDER BY agencypayperiodpaydate
        ) AS 'Pay Period Finalise State'
    ,agencyprofilecreateddate
    ,agencyprofilesetupcomplete
    ,agencyemployertaxoffice
FROM Agencyprofile AS ap
LEFT JOIN agencypayperiod AS app ON ap.agencyprofileid = app.agencyprofileid
LEFT OUTER JOIN agencyemployer AS ae ON ap.agencyemployerid = ae.agencyemployerid
WHERE (
        agencypayperiodfinalisestate <> 0
        AND agencyemployertaxoffice IS NOT NULL
        AND agencyemployertaxoffice <> ''
        )
    OR (
        agencyprofilesetupcomplete = 0
        AND agencyprofilecreateddate < DATEADD(dd,1,(GetDate() - 90))
        )
ORDER BY agencyprofilename


问:
Where in the NetBeans 6.9.1 source code is the code for scanning Java files and finding all the methods, variables, imports etc
I'm looking for a sample or possibly even code I can use which scans Java files and tells me key pieces of information about each class, which i can then use much like the NetBeans refactoring and go to source features do.</p>

答:
I don't understand very well your question.

If you want to navigate inside source java code with netbeans, push CTRL and with your mouse go over the word you want to explore ; netbeans highligth the word, and if you clic you go to the source.


问:
Getting print calls in LuaJ
I'm writing a Java program which uses Lua scripts to determine what to output to certain areas of the program. Currently, my code looks as such:

```<code>Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();
</code>```

The problem is that calling tojstring() appears to return return values from the Lua script. This is fine, but I need to get print calls, as that's what will be displayed on the screen. As of now, the print calls get sent directly to the Console (printed to console), and I cannot figure out a way to retrieve these print calls.

I've tried digging through the documentation but have had little success. Will change from LuaJ if needed.

答:
Expanding on Joseph Boyle's answer (a few years later): You can also set up a printStream to a ByteArrayOutputStream (no need to do it to a file on disk) if that's your poison. I did this in a JUnit test with LuaJ and it works: </p>

```<code>  @Test
  public void testPrintToStringFromLuaj() throws IOException {
    String PRINT_HELLO = "print (\"hello world\")";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos, true, "utf-8");
    Globals globals = JsePlatform.standardGlobals();
    globals.STDOUT = printStream;
    LuaValue load = globals.load(PRINT_HELLO);
    load.call();
    String content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    printStream.close();
    assertThat(content, is("hello world\n"));
  }
</code>```

Title: Getting print calls in LuaJ

Body:
I'm writing a Java program which uses Lua scripts to determine what to output to certain areas of the program. Currently, my code looks as such:

Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();

The problem is that calling tojstring() appears to return return values from the Lua script. This is fine, but I need to get print calls, as that's what will be displayed on the screen. As of now, the print calls get sent directly to the Console (printed to console), and I cannot figure out a way to retrieve these print calls.

I've tried digging through the documentation but have had little success. Will change from LuaJ if needed.

Body:
Expanding on Joseph Boyle's answer (a few years later): You can also set up a printStream to a ByteArrayOutputStream (no need to do it to a file on disk) if that's your poison. I did this in a JUnit test with LuaJ and it works:

  @Test
  public void testPrintToStringFromLuaj() throws IOException {
    String PRINT_HELLO = "print (\"hello world\")";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos, true, "utf-8");
    Globals globals = JsePlatform.standardGlobals();
    globals.STDOUT = printStream;
    LuaValue load = globals.load(PRINT_HELLO);
    load.call();
    String content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    printStream.close();
    assertThat(content, is("hello world\n"));
  }


问:
htaccess RewriteRule passes index.php instead of string
So I'm trying to learn about .htaccess RewriteRules and am facing the following issue:

"/home" should open "index.php?page=home"

and I have a php $_GET['page'] inside "index.php", but it passes "index.php" instead of "home" every time.

Here are the files

.htaccess

```<code>RewriteEngine On
RewriteRule ^/?(.+)/?$ index.php?page=$1 [L]
</code>```

index.php PHP part

```<code><?php

        if(isset($_GET['page'])) {
            $path = $_GET['page'] . ".php";
            if (file_exists($path)) {
                include($path);
            }
            else {
                echo "File not found: " . $path;
            }
        }
        else {
            include("home.php");
        }

?>
</code>```

The output is always:

```<code>File not found: index.php.php
</code>```

I face this issue on both: web-server and apache.

Any suggestions? I'll update my question with more info if necessary.

答:
You must skip existing files and directories from your rewrite rule to avoid looping the rule:</p>

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.+?)/?$ index.php?page=$1 [L,QSA]
</code>```

Body:
So I'm trying to learn about .htaccess RewriteRules and am facing the following issue:

"/home" should open "index.php?page=home"

and I have a php $_GET['page'] inside "index.php", but it passes "index.php" instead of "home" every time.

Here are the files

.htaccess

RewriteEngine On
RewriteRule ^/?(.+)/?$ index.php?page=$1 [L]

index.php PHP part

<?php

        if(isset($_GET['page'])) {
            $path = $_GET['page'] . ".php";
            if (file_exists($path)) {
                include($path);
            }
            else {
                echo "File not found: " . $path;
            }
        }
        else {
            include("home.php");
        }

?>

The output is always:

File not found: index.php.php

I face this issue on both: web-server and apache.

Any suggestions? I'll update my question with more info if necessary.

Body:
You must skip existing files and directories from your rewrite rule to avoid looping the rule:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.+?)/?$ index.php?page=$1 [L,QSA]


问:
click() event is calling twice in jQuery
I setup a link element and called its click event in jQuery but the click event is calling twice, please see below the code of jQuery.</p>
```<code>$("#link_button")
.button()
.click(function () {
   $("#attachmentForm").slideToggle("fast");
});
</code>```

答:
I solved this problem by change the element type.
instead of button I place input, and this problem don't occur more.

instesd of:

```<code><button onclick="doSomthing()">click me</button>
</code>```

replace with:

```<code><input onclick="doSomthing()" value="click me">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I setup a link element and called its click event in jQuery but the click event is calling twice, please see below the code of jQuery.

$("#link_button")
.button()
.click(function () {
   $("#attachmentForm").slideToggle("fast");
});

Body:
I solved this problem by change the element type.
instead of button I place input, and this problem don't occur more.

instesd of:

<button onclick="doSomthing()">click me</button>

replace with:

<input onclick="doSomthing()" value="click me">


问:
Prosilica GigE camera with OpenCV/python
I'm using a GigE (ethernet) prosilica GC camera on Mac OS X, and have been able to read it out through the proprietary sample viewing software from Allied Vision.

I would like to be able to read out the camera using OpenCV.  I have opencv installed correctly, but I am not sure how to read out the camera.  The last person to ask this question (~2 years ago) was told to use the native camera API to do this, and then analyze the images with opencv:

OpenCV with GigE Vision Cameras

However, I would like to know if it is even possible to do this with python/ opencv.  There seems to be very little information online about how to do this, so I'm curious if anyone managed to get it to work, and could post some example code/etc.  I have all my camera IP address information, model, etc, if that helps, but I don't know how to even tell opencv where to look.

Thanks in advance,

Mike

答:
Try Pymba

You can use Allied Vision's new SDK Vimba and a python interface called Pymba. Instructions are on the Pymba github page but basically you

Install Vimba

Install Pymba via pip install pymba

There's example code in the repo. I've been using it and it's pretty straight forward.


问:
How to find an object in table C++
i have function which finds a number in a table: </p>

```<code>int find(int arrf[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
        if (arrf[i] == seek)
            return i;
    return -1;
}
</code>```

<p>Is there a faster way to do this? </p>

答:
For linear search two optimizations come to mind:

Build a vectorized implementation that uses SIMD instructions to do multiple comparisons at the same time.

Parallelize search to multiple CPUs. That only makes sense if the array to search is sufficiently large to warrant multi-threading overhead.

Intel Parallel STL can do both optimizations for you.

Title: How to find an object in table C++

Body:
i have function which finds a number in a table:

int find(int arrf[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
        if (arrf[i] == seek)
            return i;
    return -1;
}

Is there a faster way to do this?


问:
Dynamic URL rewriting using codeigniter/php/htaccess when change in url
I have URL like base_url()/controller/rowtitle-rowid.

Where this URL is manipulated using function and arranged according to row in database.

As mentioned above I need to change whole URL when I am changing rowid in the URL, that means it should rewrite to particular id of row in database.

For example:

Consider following URLs

https://www.marketsandmarkets.com/Market-Reports/medical-device-testing-market-254474064.html

2.https://www.marketsandmarkets.com/Market-Reports/timing-relay-market-241993160.html

if I change bold numbers in number 2 URL to bold numbers in number 1 URL then it will rewrite the URL to URL number 1 and redirect to URL number 1

Can this possible?

Thanks in advance.

答:
Your say you are modifying the rowid which I assume are the numbers you are bolding in your 1,2 statements, and at the same time you want to redirect to a different slug and rowid which is the dashed statement before the rowid at the end of the url e.g. some-page-name.

I'm not sure what the rowid has to do with anything, perhaps it's just a random int to make sure you don't have duplicate slugs, but it isn't strictly required as long as you increment your titles if you have duplicates like some-page-name and some-page-name-1.

In PHP and codeigniter what you are trying to do is indeed possible as long as you keep a database with all the iterations of the slug. Then in your Market-Reports controller you just look for the most recent iteration of the slug and serve that as a link to the user. Or if the user is coming from a search engine, on the say Market-Reports single page controller to timing-relay-market-241993160 you query the database where rowid = 'someid' and order by created or something and then redirect the user to that slug which would be medical-device-testing-market-254474064.

Further if your database table for keeping track of slugs has the following rows rowid, rowtitle, fullslug you could literally just use intval() to get the rowid from the fullslug and do the same type of thing as I just outlined in the previous paragraph.

NOTE: You cannot do this with static HTML pages. I am assuming since you tagged PHP and codeigniter you are using php and controllers.


问:
jQuery loop one to one
I have problem with my code.

I have products on my website, each product has his own
CODE
 and I need to take this CODE and paste it before an image. I need to copy element with has class="loop1" and paste it into another element with class="lop1" and then take another element with class="loop2" and paste into element with class="lop2" and so on..

I made class with same numbers for easier copying, but it doesnt work. Can sombody help me?

This is my code:

```<code>$('#loop').addClass(function(i) {
   return 'lop'+(i+1);
    });
$('.p-name').addClass(function(i) {
   return 'loop'+(i+1);
    });

    function doForm() {
        var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];

        for (var i=0;i<numb.length;i++) {
            number = numb[i];

            selector = '.loop' + number;

                if ($(selector).length != 0) {
                val = $(selector).html();
                $('lop' + number).html(val);
            }
        }
    }

    doForm();
</code>```

Related html:

```<code><div class="columns">
    <div id="loop" class="lop1"></div>
       <div class="p-image">
         <a href="/"><img src="https://" width="290" height="218"></a>
       </div>

     <div class="p-info">
        <a href="/" title="PRODUCT" class="p-name loop1" itemprop="url" style="height: 80px;"><span itemprop="name">PRODUCT</span></a>
      </div>
<div>
</code>```

So I need to take from "p-info > a" and paste it into div "lop1". Depends on number in class copy and paste HTML into div with same number.

答:
Change $('lop' + radek).html(val); to $('.lop' + number).html(val);
Notice the . at the beginning of lop, it will create a selector to fetch element based on the class.

$('#loop').addClass(function(i) {
   return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
   return 'loop'+(i+1);
});

function doForm() {
    var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
    for (var i=0;i<numb.length;i++) {
        var number = numb[i];
        var selector = '.loop' + number;
        if ($(selector).length != 0) {
            var val = $(selector).html();
            $('.lop' + number).html(val);
        }
    }
}

doForm();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
    <div id="loop" class="lop1"></div>
       <div class="p-image">
         <img src="https://" width="290" height="218">
       </div>

     <div class="p-info">
        <span itemprop="name">PRODUCT</span>
      </div>
<div></code>```

Title: jQuery loop one to one

Body:
I have problem with my code.

I have products on my website, each product has his own
CODE
 and I need to take this CODE and paste it before an image. I need to copy element with has class="loop1" and paste it into another element with class="lop1" and then take another element with class="loop2" and paste into element with class="lop2" and so on..

I made class with same numbers for easier copying, but it doesnt work. Can sombody help me?

This is my code:

$('#loop').addClass(function(i) {
   return 'lop'+(i+1);
    });
$('.p-name').addClass(function(i) {
   return 'loop'+(i+1);
    });

    function doForm() {
        var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];

        for (var i=0;i<numb.length;i++) {
            number = numb[i];

            selector = '.loop' + number;

                if ($(selector).length != 0) {
                val = $(selector).html();
                $('lop' + number).html(val);
            }
        }
    }

    doForm();

Related html:

        PRODUCT

So I need to take from "p-info > a" and paste it into div "lop1". Depends on number in class copy and paste HTML into div with same number.

Body:
Change $('lop' + radek).html(val); to $('.lop' + number).html(val);
Notice the . at the beginning of lop, it will create a selector to fetch element based on the class.

$('#loop').addClass(function(i) {
   return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
   return 'loop'+(i+1);
});

function doForm() {
    var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
    for (var i=0;i<numb.length;i++) {
        var number = numb[i];
        var selector = '.loop' + number;
        if ($(selector).length != 0) {
            var val = $(selector).html();
            $('.lop' + number).html(val);
        }
    }
}

doForm();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
    <div id="loop" class="lop1"></div>
       <div class="p-image">
         <a href="/"><img src="https://" width="290" height="218"></a>
       </div>

     <div class="p-info">
        <a href="/" title="PRODUCT" class="p-name loop1" itemprop="url" style="height: 80px;"><span itemprop="name">PRODUCT</span></a>
      </div>
<div>


问:
How to limit angles in (-180,180) range just like Unity3D inspector
I want to get rotation of Camera gameobject attached to Char gameobject

EDIT: Char rotation, pos, scale is 0,0,0

I have following code: (Script is on the Char gameobject)

```<code>Transform cameraT = transform.Find("Camera").transform;
print(cameraT.localEulerAngles);
</code>```

The problem is that in inspector it shows:

but in debug console:

I want to get rotation from inspector

答:
That`s because you look at Global or Local Camera position.

Check it near the Left-Top corner, near the "Pivot" button

Body:
I want to get rotation of Camera gameobject attached to Char gameobject

EDIT: Char rotation, pos, scale is 0,0,0

I have following code: (Script is on the Char gameobject)

Transform cameraT = transform.Find("Camera").transform;
print(cameraT.localEulerAngles);

The problem is that in inspector it shows:

but in debug console:

I want to get rotation from inspector


问:
Reference type of JVM
In some Java literature, The statement

The reference type of the Java virtual
  machine is cleverly named
  reference

is widely popular. However, authors tend not to explain more why such statement is valid. Another thing that would make me understand this more is

What does the reference type of the JVM means ? Does the JVM represent itself in the heap ?

Would appreciate a lot an explanation on this statement.

Thank you,

Ashmawy

答:
Or maybe it is only notion to express different approach taken by JVM designers for memory management.

If you'll remember in C/C++ one have freedom to allocate memory for variable either in local stack or in global heap. It is possible in C++ to allocate memory for object in method's local stack and then pass entire object as a parameter to other methods.

Java designers took away this freedom from developers. You just cannot create objects in local stack, only in global heap. So every variable of type Class/Interface/Array is indeed a reference to some memory address in the heap.  And you cannot pass object by value only by reference.

If you don't have a choice - than you don't even need to think about what type of variable you have - value type or reference type.

Title: Reference type of JVM


问:
Which is better, a scheduled task or windows service?
I have created a console program that transfers data from a database to a server. This program must run every day at a certain time. At first I thought of a scheduled task but the problem is that it depends on a user being logged in. However, as it is rather tricky and the service has to run every day, I came to the Windows service through my research.

However, most of the information comes from 2009 and 2010 and may already be outdated? I also found a guide explaining how to create a scheduled service:

https://www.aspsnippets.com/Articles/Simple-Windows-Service-that-runs-periodically-and-once-a-day-at-specific-time-using-C-and-VBNet.aspx

Is that still best practice to do it that way? What would you recommend?

答:
Your first thought was right, use a scheduled task and select the 'Run whether user is logged on or not'.

If you use a Windows Service you have to code the trigger yourself which could be fraught with errors.

If you'd like something more 'enterprise' I'd suggest looking at Quartz.NET. It's an open source scheduling library, although it's probably overkill for what you're trying to achieve.


问:
android-integrate databinding with BottomSheet
while integrating the BottomSheet we need to make the parent layout as the CoordinatorLayout but in databinding we use <layout>. While implementing this it throws an exception :-

```<code>Caused by: java.lang.IllegalArgumentException: The view is not a child of CoordinatorLayout.
</code>```

How to integrate BottomSheet with databinding

```<code><layout>

<data>

    <import type="android.view.View" />

    <variable
        name="cabLayoutBinder"
        type="newage.com.hopin.rideBooking.CabSelectActivity" />

    <variable
        name="modelBinder"
        type="newage.com.hopin.rideBooking.model.DataBinders" />

    <variable
        name="fareSetters"
        type="newage.com.hopin.rideBooking.model.FareDetails" />
</data>

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".rideBooking.CabSelectActivity">

   </android.support.design.widget.CoordinatorLayout>

</layout>
</code>```

答:
You put context in your coordinator, but in databinding you don't implement this way.

Try to remove this line and try again:

```<code>tools:context=".rideBooking.CabSelectActivity"
</code>```

Let me know if it worked.

Body:
while integrating the BottomSheet we need to make the parent layout as the CoordinatorLayout but in databinding we use <layout>. While implementing this it throws an exception :-

Caused by: java.lang.IllegalArgumentException: The view is not a child of CoordinatorLayout.

How to integrate BottomSheet with databinding

<layout>

<data>

    <import type="android.view.View" />

    <variable
        name="cabLayoutBinder"
        type="newage.com.hopin.rideBooking.CabSelectActivity" />

    <variable
        name="modelBinder"
        type="newage.com.hopin.rideBooking.model.DataBinders" />

    <variable
        name="fareSetters"
        type="newage.com.hopin.rideBooking.model.FareDetails" />
</data>

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".rideBooking.CabSelectActivity">

   </android.support.design.widget.CoordinatorLayout>

</layout>

Body:
You put context in your coordinator, but in databinding you don't implement this way.

Try to remove this line and try again:

tools:context=".rideBooking.CabSelectActivity"

Let me know if it worked.


问:
SQL - Turn one date column into FromDate & ToDate columns
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

```<code>SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14
</code>```

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

```<code>SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE
</code>```

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?

答:
It looks like your FromDate is the same as the TransactionDate and the ToDate is the next TransactionDate with the same serial number.

You should be able to just create a calculated column with DAX inside Power BI to get your ToDate. Something like the following where Status is the name of your table.

```<code>ToDate =
    VAR EndDate = MINX(
                      FILTER('Status',
                          'Status'[Serial No] = EARLIER('Status'[Serial No]) &&
                          'Status'[TransactionDate] > EARLIER('Status'[TransactionDate])),
                      'Status'[TransactionDate])
    RETURN IF(ISBLANK(EndDate), TODAY(), EndDate)
</code>```

Another version using CALCULATE instead of MINX:

```<code>ToDate =
    VAR EndDate = CALCULATE(
                      MIN('Status'[TransactionDate]),
                      ALL('Status'),
                      'Status'[Serial No] = EARLIER('Status'[Serial No]),
                      'Status'[TransactionDate] > EARLIER('Status'[TransactionDate]))
    RETURN IF(ISBLANK(EndDate),TODAY(),EndDate)
</code>```

Body:
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?

Body:
It looks like your FromDate is the same as the TransactionDate and the ToDate is the next TransactionDate with the same serial number.

You should be able to just create a calculated column with DAX inside Power BI to get your ToDate. Something like the following where Status is the name of your table.

ToDate =
    VAR EndDate = MINX(
                      FILTER('Status',
                          'Status'[Serial No] = EARLIER('Status'[Serial No]) &&
                          'Status'[TransactionDate] > EARLIER('Status'[TransactionDate])),
                      'Status'[TransactionDate])
    RETURN IF(ISBLANK(EndDate), TODAY(), EndDate)

Another version using CALCULATE instead of MINX:

ToDate =
    VAR EndDate = CALCULATE(
                      MIN('Status'[TransactionDate]),
                      ALL('Status'),
                      'Status'[Serial No] = EARLIER('Status'[Serial No]),
                      'Status'[TransactionDate] > EARLIER('Status'[TransactionDate]))
    RETURN IF(ISBLANK(EndDate),TODAY(),EndDate)


问:
delete duplicates values and keep order of elements
How we can remove duplicated values between list1 and list2 from list1 while saving its order?

Example of my code:

```<code>list1=[(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
list2=[(1,1),(1,2)]

list1 = list(set(list1) - set(list2))
print (list1)
</code>```

output

[(5, 4), (1, 3), (3, 4), (4, 7)]

expected output

[(1,3),(3,4),(5,4),(4,7)]

答:
Use a list comprehension:

```<code>list1 = [item for item in list1 if item not in list2]
</code>```

If list2 could be larger than a few items, then convert it to a set to make checking it faster:

```<code>set2 = set(list2)
list1 = [item for item in list1 if item not in set2]
</code>```

Note that either of the above snippets will keep any duplicate items in list1 (i.e., if two items in list1 are the same, but are not in list2). If you want to eliminate internal duplicates in list1, which is a behavior of your original solution, this will retain only the first occurrence of each:

```<code>set1 = set(list1)
set2 = set(list2)
list1 = [set1.remove(item) or item for item in list1
         if item in set1 and item not in set2]
</code>```

Body:
How we can remove duplicated values between list1 and list2 from list1 while saving its order?

Example of my code:

list1=[(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
list2=[(1,1),(1,2)]

list1 = list(set(list1) - set(list2))
print (list1)

output

[(5, 4), (1, 3), (3, 4), (4, 7)]

expected output

[(1,3),(3,4),(5,4),(4,7)]

Body:
Use a list comprehension:

list1 = [item for item in list1 if item not in list2]

If list2 could be larger than a few items, then convert it to a set to make checking it faster:

set2 = set(list2)
list1 = [item for item in list1 if item not in set2]

Note that either of the above snippets will keep any duplicate items in list1 (i.e., if two items in list1 are the same, but are not in list2). If you want to eliminate internal duplicates in list1, which is a behavior of your original solution, this will retain only the first occurrence of each:

set1 = set(list1)
set2 = set(list2)
list1 = [set1.remove(item) or item for item in list1
         if item in set1 and item not in set2]


问:
three.js: Is it possible to exempt an object from global clipping?
I have many textured meshes so they must have different materials. It seems like there are only two ways to clip: globally, and per-material.

However, I want some visualizers to not be clipped (e.g. the plane I'm manipulating to define the clip planes), but all of the rest of the meshes are to be clipped. So I want to use global clipping, but to exempt the parts of the 3D UI (specific objects) from clipping. Is this possible?

答: I'm fairly certain that I can address this at the application level by separating the scenes so that i can issue the render of items i need clipped by using globally clipped functionality, and then clear out the clip planes and render a second scene containing UI elements prior to clearing the renderbuffers. </p>


答:
Please try the below query.

I did not get a chance to test this. Let me know if you face any issues.

```<code>select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and IsNull(agencyemployertaxoffice,'') != ''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate < DATEADD(dd,1,(GetDate() - 90))
order by agencyprofilename
</code>```

Title: Where statement with two criteria SQL

Body:
I have got pretty much everything in order apart from the last statement.

I am hoping for the query to narrow down my searches further and place a statement that says if one of the records within agencyprofilesetupcomplete is 0 then look to see if the date in agencyprofilecreateddate is less than 90 days of todays date, if it is I want to also include those results.

select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and agencyemployertaxoffice is not null
   and agencyemployertaxoffice <>''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate >=
           (GetDate()-90))
order by agencyprofilename

I'm also using Microsoft SQL Server if you need to know.

Body:
Please try the below query.

I did not get a chance to test this. Let me know if you face any issues.

select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and IsNull(agencyemployertaxoffice,'') != ''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate < DATEADD(dd,1,(GetDate() - 90))
order by agencyprofilename


问:
How to create ASPX Page Dynamically
i have two controls on asp.net page , textbox and button and i want to write new page into textbox then when i hit the button i want to create new asp.net web page with textbox text. what do you want me to prefer to do this? is there any step by step tutorial or any code you have done before? thanks for asnwers.

ok more detail about what i want.

textbox control text is "contact" and i click my button control. button take textbox text "contact" and create new web form page which name is "contact.aspx and its code page contact.cs" . thats it. just create new web form page under root directory with button click.

maybe there is a single code line like

Page pg =new Page();
pg.create();

答:
You can use File.WriteAllText to write the contents of the textbox to any location that the application pool user has permissions to write to.

From your edit it appears that you are looking for a CMS/wiki kind of functionality. There is nothing like that built into the .NET framework.

I suggest you look for wiki software.

Title: How to create ASPX Page Dynamically


问:
trying to extract complex numbers from strings
I am attempting to extract two columns of numbers from a text file. first column is the real part of the number and the second in the imaginary part. I managed to extract the list of numbers from the file as strings but I don't know how to separate the strings into two parts. I have attempted to use the sscanf function but just hasnt worked. The difficult part is the numbers can be both positive and negative therefore I cant use + and - in the delimiter of the strtok function since it will remove the negatives. Iv been stuck for a few days so any suggestions would be appreciated. Thanks in advance. Here is the code I worte which errors at the sscanf line.

```<code>        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #include <complex.h>

        char array[35]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
        char *arrayp[35];
        int count,n,i,j;
        double complex z1;
        double real = 0;
        double imaginary = 0;

        int main()
        {
            arrayp[0] = strtok(array," []");
            n=1;
            while (arrayp[n-1]!=NULL)
            {
               arrayp[n] = strtok(NULL, " []");
               n++;
            }
        // up to this point it has been tested to work. the remaining code is very
        // sloppy since I have tried 8 different things and have quickly written one of
        // the options tried.

            for(j=0;j<n;j++)
            {
                if (strchr(*arrayp, '+'))
                {
                    sscanf(arrayp[j],"%f+%fi", real, imaginary);
                }
                else if(arrayp string has equal to more than 1 '-')
                {
                     sscanf(arrayp[j],"%f%fi", real, imaginary);
                }
            }
        }
</code>```

The output should be something like this:

  0     0

  -4    100

  45    -234

  -56   -78

I noticed there are mistakes such are trying to search *arrayp in strchr but its a pointer I dont know how to convert a pointer into a string so i can put it into this file. Thank you for the help and effort in advance.

答:
So far so good but in

```<code>sscanf(arrayp[j],"%f%fi", real, imaginary);
</code>```

there are two errors. Firstly the scanf function family needs %lf for a double target.

Secondly, it needs the address of the target, so

```<code>sscanf(arrayp[j], "%lf%lfi", &real, &imaginary);
</code>```

Also, I don't see why you need to build an array of string pointers first - just examine every non-NULL token pointer that strtok produces.

Edit: this is a little test program.

```<code>#include <stdio.h>
#include <string.h>

int main ()
{
    double r, i;
    char array[]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
    char *tok;
    tok = strtok(array, " []");
    while(tok) {
        sscanf(tok, "%lf%lfi", &r, &i);
        printf("%.0f %.0fi\n", r, i);
        tok = strtok(NULL, " []");
    }
    return 0;
}
</code>```

Program output:

```
1 1i
-4 100i
45 -234i
-56 -78i
```

The program should be more rigorous and check the return value from sscanf.

Body:
I am attempting to extract two columns of numbers from a text file. first column is the real part of the number and the second in the imaginary part. I managed to extract the list of numbers from the file as strings but I don't know how to separate the strings into two parts. I have attempted to use the sscanf function but just hasnt worked. The difficult part is the numbers can be both positive and negative therefore I cant use + and - in the delimiter of the strtok function since it will remove the negatives. Iv been stuck for a few days so any suggestions would be appreciated. Thanks in advance. Here is the code I worte which errors at the sscanf line.

        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #include <complex.h>

        char array[35]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
        char *arrayp[35];
        int count,n,i,j;
        double complex z1;
        double real = 0;
        double imaginary = 0;

        int main()
        {
            arrayp[0] = strtok(array," []");
            n=1;
            while (arrayp[n-1]!=NULL)
            {
               arrayp[n] = strtok(NULL, " []");
               n++;
            }
        // up to this point it has been tested to work. the remaining code is very
        // sloppy since I have tried 8 different things and have quickly written one of
        // the options tried.

            for(j=0;j<n;j++)
            {
                if (strchr(*arrayp, '+'))
                {
                    sscanf(arrayp[j],"%f+%fi", real, imaginary);
                }
                else if(arrayp string has equal to more than 1 '-')
                {
                     sscanf(arrayp[j],"%f%fi", real, imaginary);
                }
            }
        }

The output should be something like this:

  0     0

  -4    100

  45    -234

  -56   -78

I noticed there are mistakes such are trying to search *arrayp in strchr but its a pointer I dont know how to convert a pointer into a string so i can put it into this file. Thank you for the help and effort in advance.

Body:
So far so good but in

sscanf(arrayp[j],"%f%fi", real, imaginary);

there are two errors. Firstly the scanf function family needs %lf for a double target.

Secondly, it needs the address of the target, so

sscanf(arrayp[j], "%lf%lfi", &real, &imaginary);

Also, I don't see why you need to build an array of string pointers first - just examine every non-NULL token pointer that strtok produces.

Edit: this is a little test program.

#include <stdio.h>
#include <string.h>

int main ()
{
    double r, i;
    char array[]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
    char *tok;
    tok = strtok(array, " []");
    while(tok) {
        sscanf(tok, "%lf%lfi", &r, &i);
        printf("%.0f %.0fi\n", r, i);
        tok = strtok(NULL, " []");
    }
    return 0;
}

Program output:

1 1i
-4 100i
45 -234i
-56 -78i

The program should be more rigorous and check the return value from sscanf.


问:
Redirect in React with Typescript
I am working on React with Typescript. "Redirect" doesn't seem to work for me.
I don't know what the problem is.

```<code>import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {

refs: {
    name: (HTMLInputElement);
    description: (HTMLInputElement);
}

addTodo() {
    store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
    alert("Task added successfully");

 <Redirect to="/home" push/>
}

render() {

    return (
        <div id="addtodo">
            <TextField
                label='Add Todo' ref="name"
            />
            <br />
            <TextField
                label='Add Description' ref="description"
            />
            <br />
            <PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />
        </div>
    )
}
</code>```

}

答:
This is not a typescript related issue. This is improper usage of <Redirect/>. You are trying to use a JSX component in a callback; this won't work. What you need to do is have some state change when a todo is added and conditionally render the <Redirect/> component when that state is true.

Try the below refactoring.

```<code>export class AddTodo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            shouldRedirect: false
        };

        this.addTodo = this.addTodo.bind(this);
    }

    refs: {
        name: (HTMLInputElement);
        description: (HTMLInputElement);
    }

    addTodo() {
        store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
        alert("Task added successfully");

        this.setState({ shouldRedirect: true });
    }

    render() {
        return (
            <div id="addtodo">
                {
                    this.state.shouldRedirect ?
                        <Redirect to="/home" push/> :
                        <div>
                            <TextField
                                label='Add Todo' ref="name"
                            />
                            <br />
                            <TextField
                                label='Add Description' ref="description"
                            />
                            <br />
                            <PrimaryButton text="Add" onClick={this.addTodo} />
                        </div>
                }
            </div>
        );
    }
}
</code>```

Title: Redirect in React with Typescript

Body:
I am working on React with Typescript. "Redirect" doesn't seem to work for me.
I don't know what the problem is.

import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {

refs: {
    name: (HTMLInputElement);
    description: (HTMLInputElement);
}

addTodo() {
    store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
    alert("Task added successfully");

 <Redirect to="/home" push/>
}

render() {

    return (

            <TextField
                label='Add Todo' ref="name"
            />

            <TextField
                label='Add Description' ref="description"
            />

            <PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />

    )
}

}

Body:
This is not a typescript related issue. This is improper usage of <Redirect/>. You are trying to use a JSX component in a callback; this won't work. What you need to do is have some state change when a todo is added and conditionally render the <Redirect/> component when that state is true.

Try the below refactoring.

export class AddTodo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            shouldRedirect: false
        };

        this.addTodo = this.addTodo.bind(this);
    }

    refs: {
        name: (HTMLInputElement);
        description: (HTMLInputElement);
    }

    addTodo() {
        store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
        alert("Task added successfully");

        this.setState({ shouldRedirect: true });
    }

    render() {
        return (
            <div id="addtodo">
                {
                    this.state.shouldRedirect ?
                        <Redirect to="/home" push/> :
                        <div>
                            <TextField
                                label='Add Todo' ref="name"
                            />
                            <br />
                            <TextField
                                label='Add Description' ref="description"
                            />
                            <br />
                            <PrimaryButton text="Add" onClick={this.addTodo} />
                        </div>
                }
            </div>
        );
    }
}


问:
including font face for bold not working
I've added the 'circular' font family to my site shown in the first code snippet below, but it doesn't add any bold,  so I tried to include the bold .ttf and .woff for the bold 'circular' font but neither of my two approaches worked, the first approach made all the text bold and the second approach didn't do anything at all!

Here is how I added 'circular' to my asp.net mvc site's site.css file and it makes all the text circular, but not the bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}```
</div>
</div>
</p>

<p>Here I tried adding the bold but it makes everything bold</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}</code>```

The last thing I tried was adding a new 'font-face' and including it in the body like this but it doesn't change any of my 'font-weight: bold' css to bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

@font-face {
    font-family: 'Circular-bold';
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular, Circular-bold,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}```

答:
below code'll work</p>

```<code>@font-face {
   font-family: 'Circular';
   src: url('../fonts/circular-bold.ttf') format('truetype');
   src: url('../fonts/circular-bold.woff') format('woff');
}

body {
  font-family: Circular;
  font-weight: bold;
}
</code>```

Body:
I've added the 'circular' font family to my site shown in the first code snippet below, but it doesn't add any bold,  so I tried to include the bold .ttf and .woff for the bold 'circular' font but neither of my two approaches worked, the first approach made all the text bold and the second approach didn't do anything at all!

Here is how I added 'circular' to my asp.net mvc site's site.css file and it makes all the text circular, but not the bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

Here I tried adding the bold but it makes everything bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

The last thing I tried was adding a new 'font-face' and including it in the body like this but it doesn't change any of my 'font-weight: bold' css to bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

@font-face {
    font-family: 'Circular-bold';
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular, Circular-bold,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

Body:
below code'll work

@font-face {
   font-family: 'Circular';
   src: url('../fonts/circular-bold.ttf') format('truetype');
   src: url('../fonts/circular-bold.woff') format('woff');
}

body {
  font-family: Circular;
  font-weight: bold;
}


问:
The render method in Jest
Does the render method made available in Jest tests simply call ReactDOM.render?

Is the result some kind of intermediate representation of the eventual HTML?

答:
So far Jest doesn't offer such a method. There is nothing related to that on API.

Enzyme has a feature like that, you can use html() method of the wrapper.

```<code>const wrapper = shallow(<Bar />);
const output = wrapper.html();
</code>```

Title: The render method in Jest

Body:
So far Jest doesn't offer such a method. There is nothing related to that on API.

Enzyme has a feature like that, you can use html() method of the wrapper.

const wrapper = shallow(<Bar />);
const output = wrapper.html();


问:
PHP - compatibility of <?= shortcut

Possible Duplicates:

  Are PHP short tags acceptable to use?

  Reference - What does this symbol mean in PHP?

Hi Guys,

I can't seem to find any information about the <?= shortcut of php.
Does anyone of you know more about that?

Thanks in advance!

答:
You are looking for the PHP ini directive short_open_tag
It enables the support for <? instead of <?php

From the docs:

```<code>Note:

This directive also affects the shorthand <?=, which is identical to
</code>```

short_open_tag to be on.

There has been no announcement whatsoever that support should be discontinued. You can regard <?= as supported as <?=.

There are however some weird preconfigured systems that don't have it enabled by default.

For example some debian version in early php5 versions.

So to be on the save side you should do <?php

php.net also says:

Note:

Using short tags should be avoided
  when developing applications or
  libraries that are meant for
  redistribution, or deployment on PHP
  servers which are not under your
  control, because short tags may not be
  supported on the target server. For
  portable, redistributable code, be
  sure not to use short tags.

which i would interpret at, you are totally fine as long as you can control your settings.

Documentation is here: http://php.net/manual/en/ini.core.php
and here: http://www.php.net/manual/en/language.basic-syntax.phpmode.php

Title: PHP - compatibility of <?= shortcut

Body:
You are looking for the PHP ini directive short_open_tag
It enables the support for <? instead of <?php

From the docs:

Note:

This directive also affects the shorthand <?=, which is identical to

short_open_tag to be on.

There has been no announcement whatsoever that support should be discontinued. You can regard <?= as supported as <?=.

There are however some weird preconfigured systems that don't have it enabled by default.

For example some debian version in early php5 versions.

So to be on the save side you should do <?php

php.net also says:

Note:

Using short tags should be avoided
  when developing applications or
  libraries that are meant for
  redistribution, or deployment on PHP
  servers which are not under your
  control, because short tags may not be
  supported on the target server. For
  portable, redistributable code, be
  sure not to use short tags.

which i would interpret at, you are totally fine as long as you can control your settings.

Documentation is here: http://php.net/manual/en/ini.core.php
and here: http://www.php.net/manual/en/language.basic-syntax.phpmode.php