问:
HTTPS Volley Invalid header issue
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

```<code>mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));
</code>```

there is my SslHurlStuck

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}
</code>```

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

 import javax.net.ssl.HostnameVerifier;
javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}
</code>```

And last one TrustStoreFactory

```<code>public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}
</code>```

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask

答:
Try this</p>

```<code>headers.put("Content-Type", "application/json");
</code>```

Title: HTTPS Volley Invalid header issue

Body:
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));

there is my SslHurlStuck

package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

 import javax.net.ssl.HostnameVerifier;
javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}

And last one TrustStoreFactory

public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask

Body:
Try this

headers.put("Content-Type", "application/json");


来源: stackexchange

问:
Replace loop with apply function *pply in R
I am working on an insurance database and I need to restate the dates. I created a loop but it takes 4 hours to return a result, which is too long.

Now I'm trying to replace the loop with *pply function. Any help at all would be much appreciated.

```<code>df <- read.table(header=TRUE, text=
          "V1 V2 V3
            AA 1 4
            AB 3 2
            AB 2 7
            CD 5 1
            CC 1 2
            CC 9 6")
#Loop
for(i in 2:nrow(df)) {
  for(j in 2:ncol(df)) {
    if (df[i,1] == df[i-1,1]){
      df[i,j] <- df[i,j] + df[i-1,j]
    }
  }
}
</code>```

答:
With base Ryou can do:

```<code>df[-1] <- lapply(df[-1], function(x) ave(x, df$V1, FUN=cumsum))
</code>```

Here is a solution with data.table:

```<code>library("data.table")
setDT(df)
dnew <- df[, lapply(.SD, cumsum), V1]
dnew
#    V1 V2 V3
# 1: AA  1  4
# 2: AB  3  2
# 3: AB  5  9
# 4: CD  5  1
# 5: CC  1  2
# 6: CC 10  8
</code>```

Data used:

```<code>df <- read.table(header=TRUE,text=
"V1 V2 V3
 AA 1 4
 AB 3 2
 AB 2 7
 CD 5 1
 CC 1 2
 CC 9 6")
</code>```

using data.table you are faster with:

```<code>library("data.table")
df <- fread(
"V1 V2 V3
 AA 1 4
 AB 3 2
 AB 2 7
 CD 5 1
 CC 1 2
 CC 9 6")
</code>```

... this will give a data.table object - so setDT(...) is not needed

ContentLicense: CC BY-SA 3.0

Body:
I am working on an insurance database and I need to restate the dates. I created a loop but it takes 4 hours to return a result, which is too long.

Now I'm trying to replace the loop with *pply function. Any help at all would be much appreciated.

df <- read.table(header=TRUE, text=
          "V1 V2 V3
            AA 1 4
            AB 3 2
            AB 2 7
            CD 5 1
            CC 1 2
            CC 9 6")
#Loop
for(i in 2:nrow(df)) {
  for(j in 2:ncol(df)) {
    if (df[i,1] == df[i-1,1]){
      df[i,j] <- df[i,j] + df[i-1,j]
    }
  }
}

Body:
With base Ryou can do:

df[-1] <- lapply(df[-1], function(x) ave(x, df$V1, FUN=cumsum))

Here is a solution with data.table:

library("data.table")
setDT(df)
dnew <- df[, lapply(.SD, cumsum), V1]
dnew
#    V1 V2 V3
# 1: AA  1  4
# 2: AB  3  2
# 3: AB  5  9
# 4: CD  5  1
# 5: CC  1  2
# 6: CC 10  8

Data used:

df <- read.table(header=TRUE,text=
"V1 V2 V3
 AA 1 4
 AB 3 2
 AB 2 7
 CD 5 1
 CC 1 2
 CC 9 6")

using data.table you are faster with:

library("data.table")
df <- fread(
"V1 V2 V3
 AA 1 4
 AB 3 2
 AB 2 7
 CD 5 1
 CC 1 2
 CC 9 6")

... this will give a data.table object - so setDT(...) is not needed


问:
BarcodeScanner.GetDefaultAsync() is always returning null
I'm trying to create a simple application in UWP for a Zebra device (Model TC700J) running Windows 8, in which I make use of the built in barcode scanner.

From what I've found, there's plenty of Zebra tutorials for accessing the scanner when programming on Android, but none for Windows due to the fact that Microsoft provide their own generic barcode scanner API found in the Windows.Devices.PointOfService namespace.

The code I currently have looks something like this:

```<code>BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}
</code>```

The problem is that the if statement never evaluates to true as the GetDefaultAsync method always returns null.

Over here there was an answer that seemed to work, stating that it depends where the GetDefaultAsync method is placed. I've tried to put it in all of the suggested places though and to no avail.

There is another method, BarcodeScanner.FromIdAsync() which returns a barcode based on the string representation of that barcode scanner's id sent as a parameter, but I'm not sure that'd be valid here as the barcode scanner is built into the device.

答:
Seems the usage of Async method wasn't quite right.

Try below code:

```<code>BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}
</code>```

More details:

https://learn.microsoft.com/en-us/dotnet/csharp/async

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396

Body:
I'm trying to create a simple application in UWP for a Zebra device (Model TC700J) running Windows 8, in which I make use of the built in barcode scanner.

From what I've found, there's plenty of Zebra tutorials for accessing the scanner when programming on Android, but none for Windows due to the fact that Microsoft provide their own generic barcode scanner API found in the Windows.Devices.PointOfService namespace.

The code I currently have looks something like this:

BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}

The problem is that the if statement never evaluates to true as the GetDefaultAsync method always returns null.

Over here there was an answer that seemed to work, stating that it depends where the GetDefaultAsync method is placed. I've tried to put it in all of the suggested places though and to no avail.

There is another method, BarcodeScanner.FromIdAsync() which returns a barcode based on the string representation of that barcode scanner's id sent as a parameter, but I'm not sure that'd be valid here as the barcode scanner is built into the device.

Body:
Seems the usage of Async method wasn't quite right.

Try below code:

BarcodeScanner scanner;
ClaimedBarcodeScanner claimedScanner;

scanner = await BarcodeScanner.GetDefaultAsync();

if (scanner != null)
{
    claimedScanner = await scanner.ClaimScannerAsync();
}

More details:

https://learn.microsoft.com/en-us/dotnet/csharp/async

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396


问:
React_native Android Application is getting crashed randomly when not connected to React Packager
When I am running my app by connecting to the react packager server my app is not crashing for any exception . But when i am creating the apk by using generate signed apk my app is crashing by generating the exception like below and displaying the red screen in app.

E/unknown:React: Exception in native call java.lang.NullPointerException at
  com.facebook.react.uimanager.UIImplementation.updateNodeSize(UIImplementation.java:149)at
  com.facebook.react.uimanager.UIManagerModule.updateNodeSize(UIManagerModule.java:235)at
  com.facebook.react.views.modal.ReactModalHostView$DialogRootViewGroup$1.run(ReactModalHostView.java:311)at
  android.os.Handler.handleCallback(Handler.java:730)at
  android.os.Handler.dispatchMessage(Handler.java:92)at
  com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)at
  android.os.Looper.loop(Looper.java:176 )at
  com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)at
  java.lang.Thread.run(Thread.java:841)

答: I had the similar problem, so I just signed app for release and distributed it like that. Everything works fine now.</p>


问:
Wrapping -- don't break up paragraphs
I have a pretty standard page layout where there's an image floated to the left, and then some information to the right of it, that consists of 1 line headers (bold) and 1 line of data underneath each header.

I want the data to flow around the image, but is there any way I can stop the data from breaking from the header that goes with it when it wraps? I.E. only wrap between a line of data and the next header.

Seems simple, but I haven't been able to come up with a way to do it!

Edit: here is a jsfiddle to illustrate my situation (cool site!): http://www.jsfiddle.net/qYcX5/
See the last paragraph is broken apart from its header.

BTW, on the actual page I'm building, the length of paragraphs on the right and the # of items will vary, so I can't arbitrarily decide to clear the data at a certain point and always have it look right.

答:
Maybe try to integrate javascript to measure the height of your accumulated
 tags and then if they're cumulatively larger than the height of the image, clear: left the last one... Not sure though.

@Jessica: If you wanted all of the text on the right side, simply add the following to your CSS:

h3, p { padding-left: 360px; /* the width of the image + 10px for extra padding */ }

Also, check out the updated jsFiddle: http://www.jsfiddle.net/qYcX5/ for example of how this works.

Good luck!

ContentLicense: CC BY-SA 2.5

Title: Wrapping -- don't break up paragraphs

Body:
Maybe try to integrate javascript to measure the height of your accumulated <h3> tags and then if they're cumulatively larger than the height of the image, clear: left the last one... Not sure though.

@Jessica: If you wanted all of the text on the right side, simply add the following to your CSS:

h3, p { padding-left: 360px; /* the width of the image + 10px for extra padding */ }

Also, check out the updated jsFiddle: http://www.jsfiddle.net/qYcX5/ for example of how this works.

Good luck!


问:
Counting the number of a specific word inside a php string
I have a php string like as follows :

```<code> $string = 'www absjdjjd www123 dkkd www wwww ghy ww';
</code>```

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

```<code>$val = 'www';
$count = substr_count($string, $val);
</code>```

答:
This code will help you

Details: used explode function to convert string into array and finally used loop with condition

```<code><?php
    $string = 'www absjdjjd www123 dkkd www wwww ghy ww';
    $a=explode(" ",$string);
    print_r($a);
    $count=0;
    foreach($a as $value)
    {
        if($value=="www")
        {
            $count++;
        }
    }
    print_r($count);
    ?>
</code>```

sandbox output

Body:
I have a php string like as follows :

 $string = 'www absjdjjd www123 dkkd www wwww ghy ww';

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

$val = 'www';
$count = substr_count($string, $val);

Body:
This code will help you

Details: used explode function to convert string into array and finally used loop with condition

<?php
    $string = 'www absjdjjd www123 dkkd www wwww ghy ww';
    $a=explode(" ",$string);
    print_r($a);
    $count=0;
    foreach($a as $value)
    {
        if($value=="www")
        {
            $count++;
        }
    }
    print_r($count);
    ?>

sandbox output


问:
Query MS Access using Excel VBA, SQL BETWEEN dates query
all--

I'm attempting to use an SQL query to pull records from an Access db into an Excel VBA userform listbox using the following code:

```<code>Sub FillLBBillIDs()
'build bill ID list box with bill IDs available in database, based on client and/or date range
'<---------------------------------------------------Dimension all variables
Dim con As Object, cmd As Object, rst As Object
Dim Path As String, CName As String
Dim FromDate As Date, ToDate As Date
Dim X As Long, Y As Long
'<---------------------------------------------------Define Default Variables
X = 0
CName = AuditParametersFRM.CBOCxName.Value
FromDate = AuditParametersFRM.DTPFrom.Value
ToDate = AuditParametersFRM.DTPTo.Value
'<---------------------------------------------------Define Access connection
Set con = CreateObject("ADODB.Connection"): Set cmd = CreateObject("ADODB.Command"): Set rst = CreateObject("ADODB.RecordSet"):
Path = Sheets("AuditTool").Range("B2").Value
'<---------------------------------------------------Open Access connection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"
con.ConnectionTimeout = 0: con.CommandTimeout = 0: con.Open: cmd.CommandTimeout = 0: Set cmd.ActiveConnection = con
'<---------------------------------------------------Find all bill IDs in the database which match the selected client and
'<---------------------------------------------------are within the consolidated date range
rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#", con, 1, 3
On Error Resume Next
rst.MoveLast
rst.MoveFirst
Y = 0
Y = rst.RecordCount
AuditToolFRM.LBBillIDs.Clear
If Not Y = 0 Then
    Do Until rst.EOF
'<---------------------------------------------------Build the listbox with the acquired information
        With AuditToolFRM.LBBillIDs
            .AddItem
            .List(X, 0) = rst![BillID]
            X = X + 1
        End With
        rst.MoveNext
    Loop
End If
rst.Close
On Error GoTo 0
con.Close
End Sub
</code>```

This code works just fine if I use a greater than argument, thusly:

```<code>rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.ConsolidationDate > #" & FromDate & "#", con 1, 3
</code>```

I've gone through all the pertinent questions on this site and can't find anything that works. Any ideas?

Thanks in advance!

12/08/2017 12:54

I've done more testing and it appears that the greater than query isn't working either; it's pulling all records that meet the first criteria whilst ignoring the second, even when using parentheses to enclose the second. This tells me that the issue is definitely in the date portion of the query somehow. Any help is appreciated greatly!

答:
In ADO you must use the ISO sequence in string expressions for date values:</p>

```<code>... "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & Format(FromDate, "yyyy\/mm\/dd") & "# AND #" & Format(ToDate, "yyyy\/mm\/dd") & "#" ...
</code>```

Body:
all--

I'm attempting to use an SQL query to pull records from an Access db into an Excel VBA userform listbox using the following code:

Sub FillLBBillIDs()
'build bill ID list box with bill IDs available in database, based on client and/or date range
'<---------------------------------------------------Dimension all variables
Dim con As Object, cmd As Object, rst As Object
Dim Path As String, CName As String
Dim FromDate As Date, ToDate As Date
Dim X As Long, Y As Long
'<---------------------------------------------------Define Default Variables
X = 0
CName = AuditParametersFRM.CBOCxName.Value
FromDate = AuditParametersFRM.DTPFrom.Value
ToDate = AuditParametersFRM.DTPTo.Value
'<---------------------------------------------------Define Access connection
Set con = CreateObject("ADODB.Connection"): Set cmd = CreateObject("ADODB.Command"): Set rst = CreateObject("ADODB.RecordSet"):
Path = Sheets("AuditTool").Range("B2").Value
'<---------------------------------------------------Open Access connection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"
con.ConnectionTimeout = 0: con.CommandTimeout = 0: con.Open: cmd.CommandTimeout = 0: Set cmd.ActiveConnection = con
'<---------------------------------------------------Find all bill IDs in the database which match the selected client and
'<---------------------------------------------------are within the consolidated date range
rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#", con, 1, 3
On Error Resume Next
rst.MoveLast
rst.MoveFirst
Y = 0
Y = rst.RecordCount
AuditToolFRM.LBBillIDs.Clear
If Not Y = 0 Then
    Do Until rst.EOF
'<---------------------------------------------------Build the listbox with the acquired information
        With AuditToolFRM.LBBillIDs
            .AddItem
            .List(X, 0) = rst![BillID]
            X = X + 1
        End With
        rst.MoveNext
    Loop
End If
rst.Close
On Error GoTo 0
con.Close
End Sub

This code works just fine if I use a greater than argument, thusly:

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.ConsolidationDate > #" & FromDate & "#", con 1, 3

I've gone through all the pertinent questions on this site and can't find anything that works. Any ideas?

Thanks in advance!

12/08/2017 12:54

I've done more testing and it appears that the greater than query isn't working either; it's pulling all records that meet the first criteria whilst ignoring the second, even when using parentheses to enclose the second. This tells me that the issue is definitely in the date portion of the query somehow. Any help is appreciated greatly!

Body:
In ADO you must use the ISO sequence in string expressions for date values:

... "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & Format(FromDate, "yyyy\/mm\/dd") & "# AND #" & Format(ToDate, "yyyy\/mm\/dd") & "#" ...


问:
Django: apps.get_models() yields models from unittests
If I call this django method, in a test, it yields a lot of models which are not installed.

These models are from other apps test code.

For example, when iI use apps.get_models() I get MROBase1 from the django package polymorphic test code.

=> I want get all models which have a table in the database. In above question I got a model which exists just for testing, which is not on the database.

NB: I use Django 1.10

答:
See this SO post.

apps.get_models() will return all installed models. If you are looking for a list of models for a specific app, do the following:

```<code>from django.apps import apps
myapp = apps.get_app_config('myapp')
myapp.models #returns an OrderedDict
</code>```

Also, for reference, here's the source of get_models() to see how it works

Body:
See this SO post.

apps.get_models() will return all installed models. If you are looking for a list of models for a specific app, do the following:

from django.apps import apps
myapp = apps.get_app_config('myapp')
myapp.models #returns an OrderedDict

Also, for reference, here's the source of get_models() to see how it works


问:
Create Generic function for findOneAndUpdate Query
I want to create a Generic Function For findOneAndUpdate Query.
So My Function is Like

```<code>var findAndUpdate = function(req, res, activityname, CollectionName){
    CollectionName.findOneAndUpdate({activityname: req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};
</code>```

And calling a function like this

```<code>findAndUpdate(req, res, 'user_id', User);
</code>```

But here is the only problem is on activityname. If I pass directly 'user_id' under Query then it returns data otherwise nothing return. Like this

```<code>var findAndUpdate = function(req, res, activityname, CollectionName){
    CollectionName.findOneAndUpdate({'user_id': req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};
</code>```

I also tried to provide 'user_id' exactly like this after getting the value from variable. Like this but still not getting

```<code>var findAndUpdate = function(req, res, activityname, CollectionName){
var uid = ("'"+activityname+"'");
    CollectionName.findOneAndUpdate({uid : req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};
</code>```

Anyone Knows how it can be solved.??

答:
Your issue is simple javascript and not depending of MongoDB. For example, writing

```<code>var toto = {age: 12};
</code>```

or

```<code>var toto = {'age': 12};
</code>```

will have exactly the same effect. If you want to dynamically define a property name, you can do it like this :

```<code>var prop = 'age';
var toto = {};
toto[prop] = 12;
</code>```

In your case, you can achieve what you want this way:

```<code>var findAndUpdate = function(req, res, activityname, CollectionName){
  var filter = {};
  filter[activityname] = req.body.user_id;
  CollectionName.findOneAndUpdate(filter,  function(err, data){
    if(err){
        res.send('error');
    } else {
       res.send('data')
    }
  });
};
</code>```

Body:
I want to create a Generic Function For findOneAndUpdate Query.
So My Function is Like

var findAndUpdate = function(req, res, activityname, CollectionName){
    CollectionName.findOneAndUpdate({activityname: req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};

And calling a function like this

findAndUpdate(req, res, 'user_id', User);

But here is the only problem is on activityname. If I pass directly 'user_id' under Query then it returns data otherwise nothing return. Like this

var findAndUpdate = function(req, res, activityname, CollectionName){
    CollectionName.findOneAndUpdate({'user_id': req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};

I also tried to provide 'user_id' exactly like this after getting the value from variable. Like this but still not getting

var findAndUpdate = function(req, res, activityname, CollectionName){
var uid = ("'"+activityname+"'");
    CollectionName.findOneAndUpdate({uid : req.body.user_id},  function(err, data){
        if(err){
            res.send('error');
        } else {
           res.send('data')
        }
    });
};

Anyone Knows how it can be solved.??

Body:
Your issue is simple javascript and not depending of MongoDB. For example, writing

var toto = {age: 12};

or

var toto = {'age': 12};

will have exactly the same effect. If you want to dynamically define a property name, you can do it like this :

var prop = 'age';
var toto = {};
toto[prop] = 12;

In your case, you can achieve what you want this way:

var findAndUpdate = function(req, res, activityname, CollectionName){
  var filter = {};
  filter[activityname] = req.body.user_id;
  CollectionName.findOneAndUpdate(filter,  function(err, data){
    if(err){
        res.send('error');
    } else {
       res.send('data')
    }
  });
};


问:
Convert Column of List to Dataframe
I have a column of lists in a spark dataframe. </p>

<pre class="lang-python prettyprint-override"><code>+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+
</code>```

<p>How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size. </p>

<p>For Example, </p>

<pre class="lang-python prettyprint-override"><code>+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+
</code>```

Title: Convert Column of List to Dataframe

Body:
I have a column of lists in a spark dataframe.

+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+

How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size.

For Example,

+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+

Body:
You can use getItem:

df.withColumn("c1", df["features"].getItem(0))\
  .withColumn("c2", df["features"].getItem(1))\
  .withColumn("c3", df["features"].getItem(2))\
  .withColumn("c4", df["features"].getItem(3))\
  .withColumn("c5", df["features"].getItem(4))\
  .withColumn("c6", df["features"].getItem(5))\
  .withColumn("c7", df["features"].getItem(6))\
  .drop('features').show()

+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+


问:
Running Java jars as windows service
I have an executable jar and I was trying to create a Windows Service using sc.exe. I used the below code for creating service:

```<code>sc create "TestService" binPath= "C:\Program Files\Java\jdk1.6.0_03\jre\bin\java.exe -jar C:\abc\MainClass.jar"
</code>```

The service got created but when I was trying to start the service I got the below error:

```<code>Error 1053: The service did not respond to the start or control request in a timely fashion.
</code>```

Later I tried to use Java Service Wrapper (Community Edition), the service starts for some time but is getting stopped everytime. The wrapper log tells something like:

```<code>Advice:
The Wrapper consists of a native component as well as a set of classes
which run within the JVM that it launches.  The Java component of the
Wrapper must be initialized promptly after the JVM is launched or the
Wrapper will timeout, as just happened.  Most likely the main class
specified in the Wrapper configuration file is not correctly initializing
the Wrapper classes:
com.MainClass
While it is possible to do so manually, the Wrapper ships with helper
classes to make this initialization processes automatic.
Please review the integration section of the Wrapper's documentation
for the various methods which can be employed to launch an application
within the Wrapper
</code>```

Could anyone please tell me how can I run jar as a Windows Service without using external software as I can't use any third party app on Client's prod env.

If not what other configs I need to do in Java Service Wrapper to make the service start.

I tried to find some info related to this on stackoverflow but I did not get anything thing. If any one has anything on stackoverflow please feel free to put this in comment.

答:
I have used this approach before in a productive environment, so I can assure you it is safe to use.

The Jar-File is wrapped in an exe and then it is added to the windows service scheduler (or however you want to call this). If you have a maven project this is also really easy to accomplish.

https://dzone.com/articles/installing-a-java-application-as-a-windows-service

Edit: you said you can’t use external software. With this approach everything that is needed is packed in the exe file. Including a JRE, I hope that that is allowed by your client’s policy.

Title: Running Java jars as windows service

Body:
I have an executable jar and I was trying to create a Windows Service using sc.exe. I used the below code for creating service:

sc create "TestService" binPath= "C:\Program Files\Java\jdk1.6.0_03\jre\bin\java.exe -jar C:\abc\MainClass.jar"

The service got created but when I was trying to start the service I got the below error:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Later I tried to use Java Service Wrapper (Community Edition), the service starts for some time but is getting stopped everytime. The wrapper log tells something like:

Advice:
The Wrapper consists of a native component as well as a set of classes
which run within the JVM that it launches.  The Java component of the
Wrapper must be initialized promptly after the JVM is launched or the
Wrapper will timeout, as just happened.  Most likely the main class
specified in the Wrapper configuration file is not correctly initializing
the Wrapper classes:
com.MainClass
While it is possible to do so manually, the Wrapper ships with helper
classes to make this initialization processes automatic.
Please review the integration section of the Wrapper's documentation
for the various methods which can be employed to launch an application
within the Wrapper

Could anyone please tell me how can I run jar as a Windows Service without using external software as I can't use any third party app on Client's prod env.

If not what other configs I need to do in Java Service Wrapper to make the service start.

I tried to find some info related to this on stackoverflow but I did not get anything thing. If any one has anything on stackoverflow please feel free to put this in comment.


问:
JMeter to wait until form is fully loaded
I have a form, which is inside a div on page. When page is loaded, form start to load with a loading screen. JMeter capture it, when page is loaded, it doesn't wait for the form, so page loader is on 0 % when I view results. I tried to use Constant Timer to delay processing. JMeter says too early in this case, that request is successful, because a failure can happen during loading of input fields.

答:
JMeter waits for the whole response with one little exception, as per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So if your form is being loaded via AJAX request JMeter won't automatically execute it, you will have to add a separate HTTP Request sampler to invoke the relevant AJAX request(s) which will load your form.

In order to mimic real browser's behavior you can put the main and the "AJAX" requests under Parallel Controller (you can install it using JMeter Plugins Manager)


问:
Using Moq to mock only some methods
I have the following method:

public CustomObect MyMethod()
{
    var lUser = GetCurrentUser();
    if (lUser.HaveAccess)
    {
        //One behavior
    }
    else
    {
        //Other behavior
    }

    //return CustomObject
}
```
<p>I want to mock <code>IMyInterface.GetCurrentUser</code>, so that while calling <code>MyMethod</code> I could get to one of the code paths to check it. How to do that with Moq?</p>
<p>I'm doing the following thing:</p>
<pre class="lang-cs prettyprint-override"><code>var moq = new Mock<IMyInterface>();
moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);

//act
var lResult = moq.Object.MyMethod();
</code>```

But for some reason lResult is always null, and when I'm trying to get into MyMethod in debug, I'm always skipping to the next statement.

答:
This is called a partial mock, and the way I know to do it in Moq requires mocking the class rather than the interface and then setting the CallBase property on your mocked object to true.

This will require making all the methods and properties of the class you are testing virtual. Assuming this isn't a problem, you can then write a test like this:

var mock = new Mock<YourTestClass>();
mock.CallBase = true;
mock.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);
mockedTest.Object.MyMethod();
```

ContentLicense: CC BY-SA 4.0

Title: Using Moq to mock only some methods

Body:
I have the following method:

public CustomObect MyMethod()
{
    var lUser = GetCurrentUser();
    if (lUser.HaveAccess)
    {
        //One behavior
    }
    else
    {
        //Other behavior
    }

    //return CustomObject
}

I want to mock IMyInterface.GetCurrentUser, so that while calling MyMethod I could get to one of the code paths to check it. How to do that with Moq?

I'm doing the following thing:

var moq = new Mock<IMyInterface>();
moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);

//act
var lResult = moq.Object.MyMethod();

But for some reason lResult is always null, and when I'm trying to get into MyMethod in debug, I'm always skipping to the next statement.


问:
Is there a simple way to give an application information, without making/hosting a database?
I'm relatively new to programming and wanted to ask, if i can communicate or send information to an C# application, without having a database.

I currently know nothing about databases.

Maybe with Google Sheets?

答: Yes, an application can get data from any source that you choose and have suitable access to and can code against. It could be a web-service, it could be a flat file on disk, it could be a custom socket server, it could be a database, it could be a no-sql store; it can be anything you can imagine. But implementing that: is your job.


问:
Run more than expected number
Please do not get too hard about my grammar.

I write  follow  class for delay

```<code>public class Queue_System_Of_Begin_Game : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true)
        {

            StartCoroutine(ExecuteAfterTime(1));

        }

    }
    //--------------------------------------
    public GameObject player1_icon, player2_icon, dice1_p1, dice2_p1, dice1_p2, dice2_p2;
    void determine_the_turn()
    {
        Debug.Log("update");

    }

    IEnumerator ExecuteAfterTime(float time)
    {
        yield return new WaitForSeconds(time);

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

I receive 62 times the word update on the console.
This problem will cause my next round of games to run 62 times, which slowed down my game.

答:
The Update() method is called once per frame, thats the reason you get 62 "updates".

You can try adding a boolean so it only gets called once like this:

```<code>bool ischecked = false;
void Update(){
    if (!ischecked){
        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true) {
            ischecked = true;
            StartCoroutine (ExecuteAfterTime (1));
        }
    }
}
</code>```

Title: Run more than expected number

Body:
Please do not get too hard about my grammar.

I write  follow  class for delay

public class Queue_System_Of_Begin_Game : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true)
        {

            StartCoroutine(ExecuteAfterTime(1));

        }

    }
    //--------------------------------------
    public GameObject player1_icon, player2_icon, dice1_p1, dice2_p1, dice1_p2, dice2_p2;
    void determine_the_turn()
    {
        Debug.Log("update");

    }

    IEnumerator ExecuteAfterTime(float time)
    {
        yield return new WaitForSeconds(time);

        determine_the_turn();
    }
}

I receive 62 times the word update on the console.
This problem will cause my next round of games to run 62 times, which slowed down my game.

Body:
The Update() method is called once per frame, thats the reason you get 62 "updates".

You can try adding a boolean so it only gets called once like this:

bool ischecked = false;
void Update(){
    if (!ischecked){
        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true) {
            ischecked = true;
            StartCoroutine (ExecuteAfterTime (1));
        }
    }
}


问:
How to configure MAMP PRO nginx server for symfony on Mac
since I have an Macbook, I use MAMP PRO to run several local servers. Now I want to change from Apache to nginx. But I allways get an 404.

What does a working standard nginx configuration for Symfony 3.x look like?

Thanks, Anton

答:
The following configuration works:

Directory Index: app.php
try_files: $uri /index.php$is_args$args;
Custom:

```<code>$uri /index.php$is_args$args;
location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/Applications/MAMP/Library/logs/fastcgi/nginxFastCGI_php7.1.8.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include          /Applications/MAMP/conf/nginx/fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/index.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
</code>```

Body:
The following configuration works:

Directory Index: app.php
try_files: $uri /index.php$is_args$args;
Custom:

$uri /index.php$is_args$args;
location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/Applications/MAMP/Library/logs/fastcgi/nginxFastCGI_php7.1.8.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include          /Applications/MAMP/conf/nginx/fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/index.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.


问:
crypto.createECDH is not getting added with webpack
I want to use createECDH function provided by crypto module in nodejs. I downloaded all the dependencies. Webpack does not add createECDH function in my resultant javascript files. How to use createECDH function of crypto available in node.

it adds number of functions like createCipher, createDechiper, createDiffihelman, listCiphers, getCiphers etc.

答:
Possibly you're using old version of crypto lib. According to docs, ECDH class was added in v0.11.14, later than the rest of functions you mentioned.

It would be nice to see your code.


问:
Cannot get PyCharm Django project to read and display Django Templating Language Tags
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3.

I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates.

The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj

Essentially the directory structure is as follows:

```<code>Test  >
    settings.py etc
TestProj  >
    templates  >
        Test  >
            index.html
            header.html
    other python files are here!
</code>```

The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
    </head>
   <body>
       <div>
           {% block content %}
           {% endblock %}
       </div>
   </body>
</html>
</code>```

And this is header html which is located in the same templates directory:

```<code>{% extends 'Test/index.html' %}

{% block content %}
    <p>Hello World</p>
{% endblock %}
</code>```

index.html is served as normal but for some reason no matter what I do the
Django {% block content %} in index.html doesnt seem to evaluate. Thus, my index.html, when served in the browser with Pycharm, has an empty body instead of Hello World.

The Test folder within templates is marked as a template folder in PyCharm so I don't see why this is the case. I also have Django selected as the template language in PyCharm settings and I have tried reinstalling PyCharm. The settings.py templates is also correctly configured to my knowledge as below:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'TestProj/templates/Test')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

Any help would be very much appreciated!

答:
I've fixed this, turns out it was stupidity in my views.
I was linking to index.html when rendering instead of header, which is supposedly how extends works.</p>

Body:
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3.

I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates.

The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj

Essentially the directory structure is as follows:

Test  >
    settings.py etc
TestProj  >
    templates  >
        Test  >
            index.html
            header.html
    other python files are here!

The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Test</title>

           {% block content %}
           {% endblock %}

And this is header html which is located in the same templates directory:

{% extends 'Test/index.html' %}

{% block content %}

Hello World

{% endblock %}

index.html is served as normal but for some reason no matter what I do the
Django {% block content %} in index.html doesnt seem to evaluate. Thus, my index.html, when served in the browser with Pycharm, has an empty body instead of Hello World.

The Test folder within templates is marked as a template folder in PyCharm so I don't see why this is the case. I also have Django selected as the template language in PyCharm settings and I have tried reinstalling PyCharm. The settings.py templates is also correctly configured to my knowledge as below:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'TestProj/templates/Test')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Any help would be very much appreciated!


问:
Return a function pointer from a class member function
I have the class AbstractOdeSolver which is the following :

```<code>class AbstractOdeSolver
{
private:
    double (*rightHandSide)(double y,double t);

public:
    AbstractOdeSolver(int nop,double initime, double fintime, double initval, double(*pf)(double,double));
    double (*GetRightHandSide)(double y, double t)();
};
</code>```

So I have a class with a private member a function pointer namely rightHandSide and  I want to return it from a member function. So ...

I don't know if the last line of the code define what I want to define, but I write having in thought this answer Returning function pointer type.

If the last line is right then I want to know how can I write the implementation in the AbstractOdeSolver.cpp? I tried:

```<code>double (*AbstractOdeSolver::GetRightHandSide)(double y, double t)()
</code>```

but this is not accepted even from the editor(Kdevelop) and I think with a small revision it is referred to something-like pointer to a member function not to a pointer to a function.

Note that I want to return a pointer to a function which take two doubles and
returns a double, if it cannot be done it is ok.

答:
IIUC what do you want, the most simple way is use typedef:

```<code>class AbstractOdeSolver
{
public:
    typedef double (*FSolver)(double, double);
    ....
    FSolver GetRightHandSide();
};
....
AbstractOdeSolver::FSolver AbstractOdeSolver::GetRightHandSide()
{
    // just for an example:
    return +[](double, double) -> double { return 0.0; }
}
</code>```

The same without typedef:

```<code>class AbstractOdeSolver
{
public:
    double (* GetRightHandSide())(double, double);
};

double (*AbstractOdeSolver::GetRightHandSide())(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}
</code>```

And with trailing return type as suggested by @Jarod42:

```<code>class AbstractOdeSolver
{
public:
    auto GetRightHandSide() -> double (*)(double, double);
};

auto AbstractOdeSolver::GetRightHandSide() -> double (*)(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}
</code>```

Body:
I have the class AbstractOdeSolver which is the following :

class AbstractOdeSolver
{
private:
    double (*rightHandSide)(double y,double t);

public:
    AbstractOdeSolver(int nop,double initime, double fintime, double initval, double(*pf)(double,double));
    double (*GetRightHandSide)(double y, double t)();
};

So I have a class with a private member a function pointer namely rightHandSide and  I want to return it from a member function. So ...

I don't know if the last line of the code define what I want to define, but I write having in thought this answer Returning function pointer type.

If the last line is right then I want to know how can I write the implementation in the AbstractOdeSolver.cpp? I tried:

double (*AbstractOdeSolver::GetRightHandSide)(double y, double t)()

but this is not accepted even from the editor(Kdevelop) and I think with a small revision it is referred to something-like pointer to a member function not to a pointer to a function.

Note that I want to return a pointer to a function which take two doubles and
returns a double, if it cannot be done it is ok.

Body:
IIUC what do you want, the most simple way is use typedef:

class AbstractOdeSolver
{
public:
    typedef double (*FSolver)(double, double);
    ....
    FSolver GetRightHandSide();
};
....
AbstractOdeSolver::FSolver AbstractOdeSolver::GetRightHandSide()
{
    // just for an example:
    return +[](double, double) -> double { return 0.0; }
}

The same without typedef:

class AbstractOdeSolver
{
public:
    double (* GetRightHandSide())(double, double);
};

double (*AbstractOdeSolver::GetRightHandSide())(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}

And with trailing return type as suggested by @Jarod42:

class AbstractOdeSolver
{
public:
    auto GetRightHandSide() -> double (*)(double, double);
};

auto AbstractOdeSolver::GetRightHandSide() -> double (*)(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}


问:
Importing functions from in the same file as declared
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

```<code>from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a
</code>```

答:
you can try to use pass :

```<code>def func1():
    pass

func1()

def func1():
    print "yes"
</code>```

But this does not actually help you run the function.

Body:
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a

Body:
you can try to use pass :

def func1():
    pass

func1()

def func1():
    print "yes"

But this does not actually help you run the function.


问:
java program is not able to read a string
```<code>import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}
</code>```

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

答:
This problem is appearing because a call to nextDouble only consumes the number itself, and not only newlines after it.

This happens:

Your program asks the scanner for a new double

Your give the console 4 characters: 0.1\n

Scanner reads from the console, and gets 0.1\n

Since it now can calculate where the double ends, it pushes back \n to its buffer

Your program asks the scanner for a new newline

The scanner reads from its buffers: \n

Since it found a valid line ending, it returns the string in front of it without the trailing newline.

There are different solutions for this:

Prepend the string directly after the number in the input:

```<code>1 3.5I'm a short string
</code>```

Consume the unneeded line character in your code manually:

```<code>        double d1 = scan.nextDouble();
        scan.nextLine();
        String s1 = scan.nextLine();
</code>```

Call next instead of nextLine:

Notice, this will only consume 1 word at a time

```<code>        double d1 = scan.nextDouble();
        String s1 = scan.next();
</code>```

Read the double using a call to nextline:

This will limit your program to newline separated numbers, instead of allowing any seperator:

```<code>int j = Integer.parseInteger(scan.nextLine());
double d1 = Double.parseDouble(scan.nextLine());
String s1 =scan.nextLine();
</code>```

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
This problem is appearing because a call to nextDouble only consumes the number itself, and not only newlines after it.

This happens:

Your program asks the scanner for a new double

Your give the console 4 characters: 0.1\n

Scanner reads from the console, and gets 0.1\n

Since it now can calculate where the double ends, it pushes back \n to its buffer

Your program asks the scanner for a new newline

The scanner reads from its buffers: \n

Since it found a valid line ending, it returns the string in front of it without the trailing newline.

There are different solutions for this:

Prepend the string directly after the number in the input:

1 3.5I'm a short string

Consume the unneeded line character in your code manually:

        double d1 = scan.nextDouble();
        scan.nextLine();
        String s1 = scan.nextLine();

Call next instead of nextLine:

Notice, this will only consume 1 word at a time

        double d1 = scan.nextDouble();
        String s1 = scan.next();

Read the double using a call to nextline:

This will limit your program to newline separated numbers, instead of allowing any seperator:

int j = Integer.parseInteger(scan.nextLine());
double d1 = Double.parseDouble(scan.nextLine());
String s1 =scan.nextLine();


问:
Cant get Moment .isBetween() to work properly
I am trying to verify that dates from a Db is not overlapping with event dates from Full Calender. The inputs are all strings from the beginning. The moment().isBetween() always gives false no matter what. What am I doing wrong? </p>

```<code>var format = 'YYYY-MM-DD h:mm',
            start = "2017-12-08 09:00",
            end = "2017-12-08 10:00",
            checkStart = "2017-12-08 09:00";

            var startDate = moment(start).format(format),
                endDate = moment(end).format(format);

            var startDatetoCheck = moment(checkStart).format(format),
                endDateToCheck = moment(checkStart).add(1, 'hours').format(format);

            var bool1 = moment(checkStart).isBetween(moment(start).format(format), moment(end).format(format));
            var bool2 = moment(endDateToCheck).isBetween(moment(start).format(format), moment(end).format(format));
</code>```

答:
By default moment(data0).isBetween(date1, date2) use strict comparison.

Version 2.13.0 introduces inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion. If the inclusivity parameter is used, both indicators must be passed.

var format = 'YYYY-MM-DD hh:mm',
    start = "2017-12-08 09:00",
    end = "2017-12-08 10:00",
    checkStart = "2017-12-08 09:00";

var startDate = moment(start).format(format),
    endDate = moment(end).format(format);

var startDatetoCheck = moment(checkStart).format(format),
    endDateToCheck = moment(checkStart).add(1, 'hours').format(format);

var bool1 = moment(checkStart).isBetween(moment(start).format(format), moment(end).format(format),  null, '[]');
var bool2 = moment(endDateToCheck).isBetween(moment(start).format(format), moment(end).format(format),  null, '[]')

console.log(bool1)
console.log(bool2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/moment@2.19.3/moment.min.js"></script></code>```

Body:
I am trying to verify that dates from a Db is not overlapping with event dates from Full Calender. The inputs are all strings from the beginning. The moment().isBetween() always gives false no matter what. What am I doing wrong?

var format = 'YYYY-MM-DD h:mm',
            start = "2017-12-08 09:00",
            end = "2017-12-08 10:00",
            checkStart = "2017-12-08 09:00";

            var startDate = moment(start).format(format),
                endDate = moment(end).format(format);

            var startDatetoCheck = moment(checkStart).format(format),
                endDateToCheck = moment(checkStart).add(1, 'hours').format(format);

            var bool1 = moment(checkStart).isBetween(moment(start).format(format), moment(end).format(format));
            var bool2 = moment(endDateToCheck).isBetween(moment(start).format(format), moment(end).format(format));

Body:
By default moment(data0).isBetween(date1, date2) use strict comparison.

Version 2.13.0 introduces inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion. If the inclusivity parameter is used, both indicators must be passed.

var format = 'YYYY-MM-DD hh:mm',
    start = "2017-12-08 09:00",
    end = "2017-12-08 10:00",
    checkStart = "2017-12-08 09:00";

var startDate = moment(start).format(format),
    endDate = moment(end).format(format);

var startDatetoCheck = moment(checkStart).format(format),
    endDateToCheck = moment(checkStart).add(1, 'hours').format(format);

var bool1 = moment(checkStart).isBetween(moment(start).format(format), moment(end).format(format),  null, '[]');
var bool2 = moment(endDateToCheck).isBetween(moment(start).format(format), moment(end).format(format),  null, '[]')

console.log(bool1)
console.log(bool2)

<script src="https://cdn.jsdelivr.net/npm/moment@2.19.3/moment.min.js"></script>


问:
JwtSecurityToken returning wrong expiration time
I need to check if my JwtSecurityToken is expired or not.

I'm using System.IdentityModel.Tokens.Jwt library.

When I create a JwtSecurityToken like this:

```<code>var token = new JwtSecurityToken(
    issuer: token_issuer,
    audience: token_audience,
    claims: claims,
    expires: DateTime.Now.AddMinutes(15),
    signingCredentials: creds
    );
</code>```

And check its lifetime, I'm getting 2 hours after the current time.

I check the lifetime this way (only for test purposes):

```<code>var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;
</code>```

And my method for validation:

```<code>private static bool ValidateToken(string token)
{
    try
    {
        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = new SymmetricSecurityKey(token_salt),
            ValidAudience = token_audience,
            ValidIssuer = token_issuer,
            RequireExpirationTime = true
        };

        var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;

        ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);

        return true;
    }
    catch(Exception ex)
    {

    }

    return false;
}
</code>```

Can anyone explain what's happening or am I doing some wrong?

EDIT (for explanation purposes)

Test 1

Current time of my device: 10:06

Using expiration = DateTime.Now.AddSeconds(5);

Token's lifetime = 12:06:10 and Kind = UTC

Validation is ok.

Test 2

Current time of my device: 10:16

Using expiration = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc).AddSeconds(5);

Token's lifetime = 10:16:12 and Kind = UTC

Validation fails:
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: '12/11/2017 10:16:12'  Current time: '12/11/2017 12:18:40'.

Test 3

Using expiration = DateTime.UtcNow.AddSeconds(5);

Token's lifetime = 13:07:10 and Kind = UTC

Validation is ok.

But WHY the validation passes if when I run the validation was 13:12 and token's lifetime is 13:07? Is there a minimum time to bet set in expiration?

答:
From the only source of this library got from google search you can see that the time is being converted to universal time (UTC).

DateTime.Now.AddMinutes(15) seems to be the problem.

Replacing it with Datetime.UtcNow.AddMinutes(15) might fix it

is your local time zone is UTC+2:00?

Body:
I need to check if my JwtSecurityToken is expired or not.

I'm using System.IdentityModel.Tokens.Jwt library.

When I create a JwtSecurityToken like this:

var token = new JwtSecurityToken(
    issuer: token_issuer,
    audience: token_audience,
    claims: claims,
    expires: DateTime.Now.AddMinutes(15),
    signingCredentials: creds
    );

And check its lifetime, I'm getting 2 hours after the current time.

I check the lifetime this way (only for test purposes):

var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;

And my method for validation:

private static bool ValidateToken(string token)
{
    try
    {
        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = new SymmetricSecurityKey(token_salt),
            ValidAudience = token_audience,
            ValidIssuer = token_issuer,
            RequireExpirationTime = true
        };

        var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;

        ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);

        return true;
    }
    catch(Exception ex)
    {

    }

    return false;
}

Can anyone explain what's happening or am I doing some wrong?

EDIT (for explanation purposes)

Test 1

Current time of my device: 10:06

Using expiration = DateTime.Now.AddSeconds(5);

Token's lifetime = 12:06:10 and Kind = UTC

Validation is ok.

Test 2

Current time of my device: 10:16

Using expiration = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc).AddSeconds(5);

Token's lifetime = 10:16:12 and Kind = UTC

Validation fails:
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: '12/11/2017 10:16:12'  Current time: '12/11/2017 12:18:40'.

Test 3

Using expiration = DateTime.UtcNow.AddSeconds(5);

Token's lifetime = 13:07:10 and Kind = UTC

Validation is ok.

But WHY the validation passes if when I run the validation was 13:12 and token's lifetime is 13:07? Is there a minimum time to bet set in expiration?


问:
The debugger cannot connect to the remote computer - but application running on the same computer
I am trying to debug an application but every time I do it reports it is unable to start debugging as the debugger cannot connect to the remote computer.

Only thing is the application it is debugging is a console application and there is no need to access a remote PC.

答:
In the Debug Section of the Project Properties the Use Remote Machine checkbox was clicked (why I don't rightly know) - for this reason it was trying to connect to a remote machine which just did not exist.

Clearing this flag got rid of the issue.


问:
Slick: comparing Rep[Option[Blob]] with Rep[Int]
I am using Slick to analyze a legacy MySQL database (with MyISAM engine). And I’m using implicit classes to navigate through entities, e.g. user.logs with this code:

```<code>implicit class UserNav(user: User) {
    def logs = Logs.filter(_.userId === user.id)
}
</code>```

However, in this case the key is an INT but the foreign key is a BLOB. Using a MySQL client I can run select userId * 1 from logs to get an INT from the BLOB, and I can even join despite the different datatypes. But with Slick I get a compile errors for the code above.

```<code>error: Cannot perform option-mapped operation [ERROR]
with type: (Option[java.sql.Blob], Int) => R [ERROR]
for base type:(java.sql.Blob, java.sql.Blob) => Boolean

error: ambiguous implicit values:
both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
match expected type slick.lifted.CanBeQueryCondition[Nothing]
</code>```

Any idea how to solve this?

答:
As I found out by trying, just pretending the column has a different data type works.

So besides the original val in class Log (which extends Table[LogRow])

```<code>val userId: Rep[Option[java.sql.Blob]] = column[Option[java.sql.Blob]]("userId", O.Default(None))
</code>```

I added

```<code>val userId_asInt: Rep[Option[Int]] = column[Option[Int]]("userId", O.Default(None))
</code>```

and changed the navigation def to

```<code>def logs = Logs.filter(_.userId_asInt === user.id)
</code>```

This did the trick – at least with MySQL/MyISAM (no idea if this works with other engines or even other DBMS).

Instead I could also have replaced the data type in original val userId, but then I would also have to change that data type all over the place like in Log.* and Log.? ...

Body:
I am using Slick to analyze a legacy MySQL database (with MyISAM engine). And I’m using implicit classes to navigate through entities, e.g. user.logs with this code:

implicit class UserNav(user: User) {
    def logs = Logs.filter(_.userId === user.id)
}

However, in this case the key is an INT but the foreign key is a BLOB. Using a MySQL client I can run select userId * 1 from logs to get an INT from the BLOB, and I can even join despite the different datatypes. But with Slick I get a compile errors for the code above.

error: Cannot perform option-mapped operation [ERROR]
with type: (Option[java.sql.Blob], Int) => R [ERROR]
for base type:(java.sql.Blob, java.sql.Blob) => Boolean

error: ambiguous implicit values:
both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
match expected type slick.lifted.CanBeQueryCondition[Nothing]

Any idea how to solve this?

Body:
As I found out by trying, just pretending the column has a different data type works.

So besides the original val in class Log (which extends Table[LogRow])

val userId: Rep[Option[java.sql.Blob]] = column[Option[java.sql.Blob]]("userId", O.Default(None))

I added

val userId_asInt: Rep[Option[Int]] = column[Option[Int]]("userId", O.Default(None))

and changed the navigation def to

def logs = Logs.filter(_.userId_asInt === user.id)

This did the trick – at least with MySQL/MyISAM (no idea if this works with other engines or even other DBMS).

Instead I could also have replaced the data type in original val userId, but then I would also have to change that data type all over the place like in Log.* and Log.? ...


问:
Changing this Python program to have function def()
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

```<code>import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)
</code>```

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

```<code>def flip (a, b):
    flipValue = random.randint
</code>```

but it's barely anything.

答:
```<code>import random
def Main():
    numOfFlips=getFlips()
    outcome=flipping(numOfFlips)
    print(outcome)
def getFlips():
    Flips=int(input("Enter number if flips:\n"))
    return Flips
def flipping(numOfFlips):
    longHeads=[]
    longTails=[]
    Tails=0
    Heads=0
    for flips in range(0,numOfFlips):
        flipValue=random.randint(1,2)
        print(flipValue)
        if flipValue==1:
            Tails+=1
            longHeads.append(Heads) #recording value of Heads before resetting it
            Heads=0
        else:
            Heads+=1
            longTails.append(Tails)
            Tails=0
    longestHeads=max(longHeads) #chooses the greatest length from both lists
    longestTails=max(longTails)
    return "Longest heads:\t"+str(longestHeads)+"\nLongest tails:\t"+str(longestTails)
Main()
</code>```

I did not quite understand how your code worked, so I made the code in functions that works just as well, there will probably be ways of improving my code alone but I have moved the code over to functions

Body:
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

def flip (a, b):
    flipValue = random.randint

but it's barely anything.

Body:
import random
def Main():
    numOfFlips=getFlips()
    outcome=flipping(numOfFlips)
    print(outcome)
def getFlips():
    Flips=int(input("Enter number if flips:\n"))
    return Flips
def flipping(numOfFlips):
    longHeads=[]
    longTails=[]
    Tails=0
    Heads=0
    for flips in range(0,numOfFlips):
        flipValue=random.randint(1,2)
        print(flipValue)
        if flipValue==1:
            Tails+=1
            longHeads.append(Heads) #recording value of Heads before resetting it
            Heads=0
        else:
            Heads+=1
            longTails.append(Tails)
            Tails=0
    longestHeads=max(longHeads) #chooses the greatest length from both lists
    longestTails=max(longTails)
    return "Longest heads:\t"+str(longestHeads)+"\nLongest tails:\t"+str(longestTails)
Main()

I did not quite understand how your code worked, so I made the code in functions that works just as well, there will probably be ways of improving my code alone but I have moved the code over to functions


问:
Drupal multi-site single code base other domain name pointing
I have a Drupal multi-site setup using a single code base.
I have a site running in /home/drupal/sites/wxyz.com
I want to point another domain name to the same site(same content). The domain is wxyz.net.
Do I make a copy of entry for wxyz.com in the vhosts file and copy it for wxyz.net ?
Do I need a symbolic link for this also?
I don't want an entire new site for wxyz.net, I just want the domain to point to the .com.

thanks

答:
If both sites share the same content you don't need to do anything but set up the vhost. If you have different content you will need 2 different settings.php files.

You should not need to set up a symlink in either setup.


问:
Ajax code not working only validation worked
Here is the JS Fiddle

My Ajax code not working i dont know how..
I used ajax below code many time but this time not working
please help me..

only this code run inside the ajax code

```<code>if(!validateee()) return false;
</code>```

If validation code remove then ajax run

Ajax Code

```<code>$('#body-enquiry').submit(function(e){
              e.preventDefault();
            if(!validateee()) return false;
             $(this).find(":submit").prop("disabled", true);

            var form = $(this);
            var post_url = 'enquiry-entire-mail.php';
            var post_data = form.serialize();
            $.ajax({
                type: 'POST',
                url: post_url,
                data: post_data,

                success: function(data) {
                    alert('Submited');
                }

            });

        });
</code>```

答:
you forgot to return true at the end of your function that is the issue.

```<code> return true;
</code>```

this you need to write in you validateee function .

please find update here : https://jsfiddle.net/qref356z/6/

you updated validateee function, update below code it will work i checked it at my end

```<code>      function validateee() {
            var name = document.popbody.namebody.value;
            var email = document.popbody.emailbody.value;
            var number = document.popbody.numberbody.value.length;
            var msg = document.popbody.msgbody.value.length;
            alert('msg5');
            if(name.trim() == "") {
                alert("Please Fill Name");
                document.popbody.namebody.focus();
                return false;
            }
            alert('msg4');
            if(name<3) {
                alert("invalid Name");
                document.popbody.namebody.focus();
                return false;
            }
            alert('msg3');
            if(email=="") {
                alert("Enter Your Email");
                document.popbody.emailbody.focus();
                return false;
            }
            alert('msg2');
            if(number=="") {
                alert("Enter Your Number");
                document.popbody.numberbody.focus();
                return false;
            }
            alert('msg1');
            if(number<9) {
                alert("Your Mobile number at least 10 digit");
                document.popbody.numberbody.focus();
                return false;
            }
            alert('msg');
            if(msg == "") {
                alert("Enter your Message");
                document.popbody.msgbody.focus();
                return false;
            }

    return true;///you need to add here
  }
</code>```

Body:
Here is the JS Fiddle

My Ajax code not working i dont know how..
I used ajax below code many time but this time not working
please help me..

only this code run inside the ajax code

if(!validateee()) return false;

If validation code remove then ajax run

Ajax Code

$('#body-enquiry').submit(function(e){
              e.preventDefault();
            if(!validateee()) return false;
             $(this).find(":submit").prop("disabled", true);

            var form = $(this);
            var post_url = 'enquiry-entire-mail.php';
            var post_data = form.serialize();
            $.ajax({
                type: 'POST',
                url: post_url,
                data: post_data,

                success: function(data) {
                    alert('Submited');
                }

            });

        });

Body:
you forgot to return true at the end of your function that is the issue.

 return true;

this you need to write in you validateee function .

please find update here : https://jsfiddle.net/qref356z/6/

you updated validateee function, update below code it will work i checked it at my end

      function validateee() {
            var name = document.popbody.namebody.value;
            var email = document.popbody.emailbody.value;
            var number = document.popbody.numberbody.value.length;
            var msg = document.popbody.msgbody.value.length;
            alert('msg5');
            if(name.trim() == "") {
                alert("Please Fill Name");
                document.popbody.namebody.focus();
                return false;
            }
            alert('msg4');
            if(name<3) {
                alert("invalid Name");
                document.popbody.namebody.focus();
                return false;
            }
            alert('msg3');
            if(email=="") {
                alert("Enter Your Email");
                document.popbody.emailbody.focus();
                return false;
            }
            alert('msg2');
            if(number=="") {
                alert("Enter Your Number");
                document.popbody.numberbody.focus();
                return false;
            }
            alert('msg1');
            if(number<9) {
                alert("Your Mobile number at least 10 digit");
                document.popbody.numberbody.focus();
                return false;
            }
            alert('msg');
            if(msg == "") {
                alert("Enter your Message");
                document.popbody.msgbody.focus();
                return false;
            }

    return true;///you need to add here
  }


问:
Get `env: node: No such file or directory` error when run `babel` in Intellij
I am using Intellij ultimate 2017.3 and installed nodejs plugin on it. My nodejs project requires babel to do the translation work from es5 to es6. In order to make Intellij to be able to debug my nodejs process, I added a file watcher plugin to listen on the source code changes. Once a file is changed, it will run below command to translate the code:

```<code>babel ./src --out-dir ./lib --source-maps
</code>```

this command works fine from my OS but I get below error in Intellij:

```<code>env: node: No such file or directory

Process finished with exit code 127
</code>```

I am using MacOS 10.13.1 and my node is managed by nvm which is at the v8.9.1. Babel is 6.26.0. Is there any problem in Intellij to call babel command? Or is it a babel or node environment problem on my OS?

答:
Must be a $PATH issue. Can you check if the problem persist when running IDEA from terminal (open -a /Applications/idea.app )?

on MacOSX the environment variables differ between GUI applications and within the terminal. Terminal environment is only available to applications started from terminal.
To solve this problem, IDEA tries to load terminal environment by executing the following command on startup:

```<code><your shell> -l -i -c '/Applications/idea.app/bin/printenv.py'
</code>```

Seems this command can't retrieve all needed stuff in your case - thus the issue.

Some links you may find useful: http://apple.stackexchange.com/questions/106355/setting-the-system-wide-path-environment-variable-in-mavericks, https://devnet.jetbrains.com/docs/DOC-1160#comment-2801, http://apple.stackexchange.com/questions/51677/how-to-set-path-for-finder-launched-applications.. The problem is that the way to define system-wide environment variables on Mac changes from one version to another (even minor system updates may break your environment)

Body:
I am using Intellij ultimate 2017.3 and installed nodejs plugin on it. My nodejs project requires babel to do the translation work from es5 to es6. In order to make Intellij to be able to debug my nodejs process, I added a file watcher plugin to listen on the source code changes. Once a file is changed, it will run below command to translate the code:

babel ./src --out-dir ./lib --source-maps

this command works fine from my OS but I get below error in Intellij:

env: node: No such file or directory

Process finished with exit code 127

I am using MacOS 10.13.1 and my node is managed by nvm which is at the v8.9.1. Babel is 6.26.0. Is there any problem in Intellij to call babel command? Or is it a babel or node environment problem on my OS?

Body:
Must be a $PATH issue. Can you check if the problem persist when running IDEA from terminal (open -a /Applications/idea.app )?

on MacOSX the environment variables differ between GUI applications and within the terminal. Terminal environment is only available to applications started from terminal.
To solve this problem, IDEA tries to load terminal environment by executing the following command on startup:

<your shell> -l -i -c '/Applications/idea.app/bin/printenv.py'

Seems this command can't retrieve all needed stuff in your case - thus the issue.

Some links you may find useful: http://apple.stackexchange.com/questions/106355/setting-the-system-wide-path-environment-variable-in-mavericks, https://devnet.jetbrains.com/docs/DOC-1160#comment-2801, http://apple.stackexchange.com/questions/51677/how-to-set-path-for-finder-launched-applications.. The problem is that the way to define system-wide environment variables on Mac changes from one version to another (even minor system updates may break your environment)