问:
How to get a value of __LINE__ of another function (before calling that function)?
For the currently existing test framework I need to pass (during the first-most call) to the function a line number of a fragment inside of that function. Something like this:

```<code>#include <stdio.h>
void func(int line_num)
{
#define LINE_NUM  (__LINE__ + 1)
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(LINE_NUM); // Pass to the func the line number inside of that func.
  return 0;
}
</code>```

(this is a minimalistic version of a more complex functionality).

As is the sample code prints "FAIL".

If I pass an absolute value 5, e.g. func(5) then it prints "OK". I don't like the absolute value 5 because if I add one more line in front of the func definition then the absolute value will need a correction.

Instead of #define LINE_NUM  (__LINE__ + 1) I also tried the following:

1.

```<code>#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)
</code>```

2.

```<code>#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)
</code>```

3.

```<code>#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)
</code>```

I'm using:

```<code>gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
</code>```

In my sample code the value that func() gets is 14 (the call site line number + 1).

答:
After @rici 's great answer and comments the closest thing to what I need is the following:</p>

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

#define LINE_NUM_TESTER() \
    enum { LINE_NUM = __LINE__ }; \
    \
    void line_num_tester(int line_num) \
    { \
      if(line_num == __LINE__) \
        printf("OK\n"); \
      else \
        printf("FAIL. line_num: %d, __LINE__: %d.\n", line_num, __LINE__); \
    }

LINE_NUM_TESTER()

int main(void)
{
  line_num_tester(LINE_NUM);
  return 0;
}
</code>```

Body:
For the currently existing test framework I need to pass (during the first-most call) to the function a line number of a fragment inside of that function. Something like this:

#include <stdio.h>
void func(int line_num)
{
#define LINE_NUM  (__LINE__ + 1)
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(LINE_NUM); // Pass to the func the line number inside of that func.
  return 0;
}

(this is a minimalistic version of a more complex functionality).

As is the sample code prints "FAIL".

If I pass an absolute value 5, e.g. func(5) then it prints "OK". I don't like the absolute value 5 because if I add one more line in front of the func definition then the absolute value will need a correction.

Instead of #define LINE_NUM  (__LINE__ + 1) I also tried the following:

1.

#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)

2.

#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)

3.

#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)

I'm using:

gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

In my sample code the value that func() gets is 14 (the call site line number + 1).

Body:
After @rici 's great answer and comments the closest thing to what I need is the following:

#include <stdio.h>

#define LINE_NUM_TESTER() \
    enum { LINE_NUM = __LINE__ }; \
    \
    void line_num_tester(int line_num) \
    { \
      if(line_num == __LINE__) \
        printf("OK\n"); \
      else \
        printf("FAIL. line_num: %d, __LINE__: %d.\n", line_num, __LINE__); \
    }

LINE_NUM_TESTER()

int main(void)
{
  line_num_tester(LINE_NUM);
  return 0;
}


来源: stackexchange

问:
How do I load a nested resource using cancan when the name of the nested model differs from the controller name?
given that I have a Worker model which is nested under Farm model, how do I correctly load the Worker resource in the Workers controller (called FarmWorkersController)? I've tried this...

```<code>class FarmWorkersController < ApplicationController
  load_resource :farm, :parent => true
  load_resource :class => 'Worker', :through => :farm, :parent => false

  # Note that :parent and :class need to be specified on the Worker resource line,
  # as the name of the controller (FarmWorkersController) is different from Worker model name
end
</code>```

... but I get the error

```<code>undefined method `farm_workers' for #<Farm:0xa87670c>
</code>```

Note that if I define a farm_workers() getter in the Farm model which returns the collection of Workers, then I don't get the error - though the Workers collection is not loaded for the index action. In any case, I don't want to pollute my model to make the controller authentication work.

(It shouldn't matter but I am using mongoid)

答:
Untested, but according to the docs/code, you should be able to specify the name as the first argument to load_resource:

```<code>load_resource :worker, :class => 'Worker', :through => :farm, :parent => false</code>```

ContentLicense: CC BY-SA 2.5

Body:
given that I have a Worker model which is nested under Farm model, how do I correctly load the Worker resource in the Workers controller (called FarmWorkersController)? I've tried this...

class FarmWorkersController < ApplicationController
  load_resource :farm, :parent => true
  load_resource :class => 'Worker', :through => :farm, :parent => false

  # Note that :parent and :class need to be specified on the Worker resource line,
  # as the name of the controller (FarmWorkersController) is different from Worker model name
end

... but I get the error

undefined method `farm_workers' for #<Farm:0xa87670c>

Note that if I define a farm_workers() getter in the Farm model which returns the collection of Workers, then I don't get the error - though the Workers collection is not loaded for the index action. In any case, I don't want to pollute my model to make the controller authentication work.

(It shouldn't matter but I am using mongoid)

Body:
Untested, but according to the docs/code, you should be able to specify the name as the first argument to load_resource:

load_resource :worker, :class => 'Worker', :through => :farm, :parent => false


问:
Decorators and globals
The application has a module, A, which contains a decorator which adds functions to a list which is a module-level global in A.  The list of functions is used in other functions within the module.

A.py

```<code>import functools

things = []

def register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        things.append(func)
        return func
    return inner

@register
def foo():pass

@register
def bar():pass

foo()
bar()

print(things)
</code>```

This pattern has been copied in other parts of the application, so a number of modules contain the register function and the module level list.

I want to reduce the amount of duplication by having A.register implemented in a single location, but modules that import need to have their own local list of functions.

I tried importing A and creating a providing a list:

B.py

```<code>import A

things = []

@A.register
def baz():pass

@A.register
def quux():pass

baz()
quux()

print(things)
</code>```

But all the functions are registered in A.things:

```<code>>>> import A
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]
>>> import B
[]
>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>, <function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]
</code>```

Is there a way to have single implementation of A.register, but to have it populate a list in the modules in which it's imported?  That is

```<code>>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]

>>> print B.things
[<function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]
</code>```

答:
An alternative to my other answer that might require less modification to your existing code would be changing module B like:

```<code>...
things = []
A.things = things

@A.register
def baz():pass
...
</code>```

Essentially anything you have a reference to is mutable (A.things in this case). You could of course save a reference to the original A.things and swap between within a single module if needed.

ContentLicense: CC BY-SA 3.0

Title: Decorators and globals

Body:
The application has a module, A, which contains a decorator which adds functions to a list which is a module-level global in A.  The list of functions is used in other functions within the module.

A.py

import functools

things = []

def register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        things.append(func)
        return func
    return inner

@register
def foo():pass

@register
def bar():pass

foo()
bar()

print(things)

This pattern has been copied in other parts of the application, so a number of modules contain the register function and the module level list.

I want to reduce the amount of duplication by having A.register implemented in a single location, but modules that import need to have their own local list of functions.

I tried importing A and creating a providing a list:

B.py

import A

things = []

@A.register
def baz():pass

@A.register
def quux():pass

baz()
quux()

print(things)

But all the functions are registered in A.things:

>>> import A
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]
>>> import B
[]
>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>, <function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]

Is there a way to have single implementation of A.register, but to have it populate a list in the modules in which it's imported?  That is

>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]

>>> print B.things
[<function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]

Body:
An alternative to my other answer that might require less modification to your existing code would be changing module B like:

...
things = []
A.things = things

@A.register
def baz():pass
...

Essentially anything you have a reference to is mutable (A.things in this case). You could of course save a reference to the original A.things and swap between within a single module if needed.


问:
Need help to write a unit test using Mockito and JUnit4
Need help to write a unit test for the below code using Mockito and JUnit4,

```<code>public class MyFragmentPresenterImpl {
      public Boolean isValid(String value) {
        return !(TextUtils.isEmpty(value));
      }
}
</code>```

I tried below method:
MyFragmentPresenter mMyFragmentPresenter

```<code>@Before
public void setup(){
    mMyFragmentPresenter=new MyFragmentPresenterImpl();
}

@Test
public void testEmptyValue() throws Exception {
    String value=null;
    assertFalse(mMyFragmentPresenter.isValid(value));
}
</code>```

but it returns following exception,

java.lang.RuntimeException: Method isEmpty in android.text.TextUtils
  not mocked. See http://g.co/androidstudio/not-mocked for details. at
  android.text.TextUtils.isEmpty(TextUtils.java) at ....

答:
I replaces everywhere in my project TextUtils.isEmpty(...) with this:

```<code>/**
 * Util class to be used instead of Android classes for Junit tests.
 */
public class Utils {

    /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(@Nullable CharSequence str) {
        return str == null || str.length() == 0;
    }
}
</code>```

Body:
Need help to write a unit test for the below code using Mockito and JUnit4,

public class MyFragmentPresenterImpl {
      public Boolean isValid(String value) {
        return !(TextUtils.isEmpty(value));
      }
}

I tried below method:
MyFragmentPresenter mMyFragmentPresenter

@Before
public void setup(){
    mMyFragmentPresenter=new MyFragmentPresenterImpl();
}

@Test
public void testEmptyValue() throws Exception {
    String value=null;
    assertFalse(mMyFragmentPresenter.isValid(value));
}

but it returns following exception,

java.lang.RuntimeException: Method isEmpty in android.text.TextUtils
  not mocked. See http://g.co/androidstudio/not-mocked for details. at
  android.text.TextUtils.isEmpty(TextUtils.java) at ....

Body:
I replaces everywhere in my project TextUtils.isEmpty(...) with this:

/**
 * Util class to be used instead of Android classes for Junit tests.
 */
public class Utils {

    /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(@Nullable CharSequence str) {
        return str == null || str.length() == 0;
    }
}


问:
method does not override or implement a method from a supertype @Override
I am using bugsnag-react-native version 2.2.3, I am getting below error while building in android
"method does not override or implement a method from a supertype @override"
and in ios, it's working fine.
and when i comment @override in node_modules/bugsnag-react-native/android/src/main/java/com/bugsnag/BugsnagReactNative.java file then it' successfully build.

I replaced this

```<code>@override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
</code>```

to

```<code>//@override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
</code>```

and it's working

when i use latest version so i am getting so many errors.
So please suggest, Dont want to change in node module.

答: This issue was fixed in a later version. Could you try updating to the newest bugsnag-react-native version (2.7.0)?</p>

Body:
I am using bugsnag-react-native version 2.2.3, I am getting below error while building in android
"method does not override or implement a method from a supertype @override"
and in ios, it's working fine.
and when i comment @override in node_modules/bugsnag-react-native/android/src/main/java/com/bugsnag/BugsnagReactNative.java file then it' successfully build.

I replaced this

@override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

to

//@override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

and it's working

when i use latest version so i am getting so many errors.
So please suggest, Dont want to change in node module.


问:
How to use a client certificate to authenticate and authorize in a Web API
I am trying to use a client certificate to authenticate and authorize devices using a Web API and developed a simple proof of concept to work through issues with the potential solution.  I am running into an issue where the client certificate is not being received by the web application.  A number of people of reported this issue, including in this Q&A, but none of them have an answer.  My hope is to provide more detail to revive this issue and hopefully get an answer for my issue.  I am open to other solutions.  The main requirement is that a standalone process written in C# can call a Web API and be authenticated using a client certificate.

The Web API in this POC is very simple and just returns a single value.  It uses an attribute to validate that HTTPS is used and that a client certificate is present.

```<code>public class SecureController : ApiController
{
    [RequireHttps]
    public string Get(int id)
    {
        return "value";
    }

}
</code>```

Here is the code for the RequireHttpsAttribute:

```<code>public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            var cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            base.OnAuthorization(actionContext);
        }
    }
}
</code>```

In this POC I am just checking for the availability of the client certificate.  Once this is working I can add checks for information in the certificate to validate against a list of certificates.

Here are the setting in IIS for SSL for this web application.

Here is the code for the client that sends the request with a client certificate.  This is a console application.

```<code>    private static async Task SendRequestUsingHttpClient()
    {
        WebRequestHandler handler = new WebRequestHandler();
        X509Certificate certificate = GetCert("ClientCertificate.cer");
        handler.ClientCertificates.Add(certificate);
        handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri("https://localhost:44398/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Secure/1");
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Received response: {0}",content);
            }
            else
            {
                Console.WriteLine("Error, received status code {0}: {1}", response.StatusCode, response.ReasonPhrase);
            }
        }
    }

    public static bool ValidateServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine("Validating certificate {0}", certificate.Issuer);
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }
</code>```

When I run this test app I get back a status code of 403 Forbidden with a reason phrase of “Client Certificate Required” indicating that it is getting into my RequireHttpsAttribute and it is not finding any client certificates.  Running this through a debugger I have verified that the certificate is getting loaded and added to the WebRequestHandler.  The certificate is exported into a CER file that is being loaded.  The full certificate with the private key is located on the Local Machine’s Personal and Trusted Root stores for the web application server.  For this test the client and web application are being run on the same machine.

I can call this Web API method using Fiddler, attaching the same client certificate, and it works fine.  When using Fiddler it passes the tests in RequireHttpsAttribute and returns a successful status code of 200 and returns the expected value.

Has anybody run into the same issue where HttpClient does not send a client certificate in the request and found a solution?

Update 1:

I also tried getting the certificate from the certificate store that includes the private key.  Here is how I retrieved it:

```<code>    private static X509Certificate2 GetCert2(string hostname)
    {
        X509Store myX509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        myX509Store.Open(OpenFlags.ReadWrite);
        X509Certificate2 myCertificate = myX509Store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.GetNameInfo(X509NameType.SimpleName, false) == hostname);
        return myCertificate;
    }
</code>```

I verified that this certificate was getting retrieved correctly and it was being added to the client certificate collection.  But I got the same results where the server code does not retrieve any client certificates.

For completeness here is the code used to retrieve the certificate from a file:

```<code>    private static X509Certificate GetCert(string filename)
    {
        X509Certificate Cert = X509Certificate.CreateFromCertFile(filename);
        return Cert;

    }
</code>```

You will notice that when you get the certificate from a file it returns an object of type X509Certificate and when you retrieve it from the certificate store it is of type X509Certificate2.  The X509CertificateCollection.Add Method is expecting a type of X509Certificate.

Update 2:
I am still trying to figure this out and have tried many different options but to no avail.

I changed the web application to run on a host name instead of local host.

I set the web application to require SSL

I verified that the certificate was set for Client Authentication and that it is in the trusted root

Besides testing the client certificate in Fiddler I also validated it in Chrome.

At one point during trying these options it started working.  Then I started backing out changes to see what caused it to work. It continued to work.  Then I tried removing the certificate from the trusted root to validate that this was required and it stopped working and now I cannot get it back to working even though I put the certificate back in the trusted root.  Now Chrome will not even prompt me for a certificate like it used too and it fails in Chrome, but still works in Fiddler.  There must be some magic configuration I am missing.

I also tried enabling "Negotiate Client Certificate" in the binding but Chrome still will not prompt me for a client certificate.  Here is the settings using "netsh http show sslcert"

```<code> IP:port                 : 0.0.0.0:44398
 Certificate Hash        : 429e090db21e14344aa5d75d25074712f120f65f
 Application ID          : {4dc3e181-e14b-4a21-b022-59fc669b0914}
 Certificate Store Name  : MY
 Verify Client Certificate Revocation    : Disabled
 Verify Revocation Using Cached Client Certificate Only    : Disabled
 Usage Check    : Enabled
 Revocation Freshness Time : 0
 URL Retrieval Timeout   : 0
 Ctl Identifier          : (null)
 Ctl Store Name          : (null)
 DS Mapper Usage    : Disabled
 Negotiate Client Certificate    : Enabled
</code>```

Here is the client certificate I am using:

I am baffled as to what the issue is.  I am adding a bounty for anyone that can help me figure this out.

答:
Update:

Example from Microsoft:

https://learn.microsoft.com/en-us/azure/app-service/app-service-web-configure-tls-mutual-auth#special-considerations-for-certificate-validation

Original

This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.

First I edited <src>\.vs\config\applicationhost.config and made this change:

This allows me to edit <system.webServer> in web.config and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.

For production follow a guide like this to set up the IIS:

https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb

web.config:

```<code><security>
  <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>
</code>```

API Controller:

```<code>[RequireSpecificCert]
public class ValuesController : ApiController
{
    // GET api/values
    public IHttpActionResult Get()
    {
        return Ok("It works!");
    }
}
</code>```

Attribute:

```<code>public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            X509Certificate2 cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            else
            {
                X509Chain chain = new X509Chain();

                //Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
                chain.ChainPolicy = new X509ChainPolicy()
                {
                    RevocationMode = X509RevocationMode.NoCheck,
                };
                try
                {
                    var chainBuilt = chain.Build(cert);
                    Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));

                    var validCert = CheckCertificate(chain, cert);

                    if (chainBuilt == false || validCert == false)
                    {
                        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                        {
                            ReasonPhrase = "Client Certificate not valid"
                        };
                        foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                        {
                            Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }

            base.OnAuthorization(actionContext);
        }
    }

    private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
    {
        var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);

        var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);

        //Check that the certificate have been issued by a specific Root Certificate
        var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));

        //Check that the certificate thumbprint matches our expected thumbprint
        var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);

        return validRoot && validCert;
    }
}
</code>```

Can then call the API with client certification like this, tested from another web project.

```<code>[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{

    public IHttpActionResult Get()
    {
        var handler = new WebRequestHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ClientCertificates.Add(GetClientCert());
        handler.UseProxy = false;
        var client = new HttpClient(handler);
        var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
        var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return Ok(resultString);
    }

    private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certificateSerialNumber= "81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

            //Does not work for some reason, could be culture related
            //var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

            //if (certs.Count == 1)
            //{
            //    var cert = certs[0];
            //    return cert;
            //}

            var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));

            return cert;
        }
        finally
        {
            store?.Close();
        }
    }
}
</code>```

Body:
I am trying to use a client certificate to authenticate and authorize devices using a Web API and developed a simple proof of concept to work through issues with the potential solution.  I am running into an issue where the client certificate is not being received by the web application.  A number of people of reported this issue, including in this Q&A, but none of them have an answer.  My hope is to provide more detail to revive this issue and hopefully get an answer for my issue.  I am open to other solutions.  The main requirement is that a standalone process written in C# can call a Web API and be authenticated using a client certificate.

The Web API in this POC is very simple and just returns a single value.  It uses an attribute to validate that HTTPS is used and that a client certificate is present.

public class SecureController : ApiController
{
    [RequireHttps]
    public string Get(int id)
    {
        return "value";
    }

}

Here is the code for the RequireHttpsAttribute:

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            var cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            base.OnAuthorization(actionContext);
        }
    }
}

In this POC I am just checking for the availability of the client certificate.  Once this is working I can add checks for information in the certificate to validate against a list of certificates.

Here are the setting in IIS for SSL for this web application.

Here is the code for the client that sends the request with a client certificate.  This is a console application.

    private static async Task SendRequestUsingHttpClient()
    {
        WebRequestHandler handler = new WebRequestHandler();
        X509Certificate certificate = GetCert("ClientCertificate.cer");
        handler.ClientCertificates.Add(certificate);
        handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri("https://localhost:44398/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Secure/1");
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Received response: {0}",content);
            }
            else
            {
                Console.WriteLine("Error, received status code {0}: {1}", response.StatusCode, response.ReasonPhrase);
            }
        }
    }

    public static bool ValidateServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine("Validating certificate {0}", certificate.Issuer);
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }

When I run this test app I get back a status code of 403 Forbidden with a reason phrase of “Client Certificate Required” indicating that it is getting into my RequireHttpsAttribute and it is not finding any client certificates.  Running this through a debugger I have verified that the certificate is getting loaded and added to the WebRequestHandler.  The certificate is exported into a CER file that is being loaded.  The full certificate with the private key is located on the Local Machine’s Personal and Trusted Root stores for the web application server.  For this test the client and web application are being run on the same machine.

I can call this Web API method using Fiddler, attaching the same client certificate, and it works fine.  When using Fiddler it passes the tests in RequireHttpsAttribute and returns a successful status code of 200 and returns the expected value.

Has anybody run into the same issue where HttpClient does not send a client certificate in the request and found a solution?

Update 1:

I also tried getting the certificate from the certificate store that includes the private key.  Here is how I retrieved it:

    private static X509Certificate2 GetCert2(string hostname)
    {
        X509Store myX509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        myX509Store.Open(OpenFlags.ReadWrite);
        X509Certificate2 myCertificate = myX509Store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.GetNameInfo(X509NameType.SimpleName, false) == hostname);
        return myCertificate;
    }

I verified that this certificate was getting retrieved correctly and it was being added to the client certificate collection.  But I got the same results where the server code does not retrieve any client certificates.

For completeness here is the code used to retrieve the certificate from a file:

    private static X509Certificate GetCert(string filename)
    {
        X509Certificate Cert = X509Certificate.CreateFromCertFile(filename);
        return Cert;

    }

You will notice that when you get the certificate from a file it returns an object of type X509Certificate and when you retrieve it from the certificate store it is of type X509Certificate2.  The X509CertificateCollection.Add Method is expecting a type of X509Certificate.

Update 2:
I am still trying to figure this out and have tried many different options but to no avail.

I changed the web application to run on a host name instead of local host.

I set the web application to require SSL

I verified that the certificate was set for Client Authentication and that it is in the trusted root

Besides testing the client certificate in Fiddler I also validated it in Chrome.

At one point during trying these options it started working.  Then I started backing out changes to see what caused it to work. It continued to work.  Then I tried removing the certificate from the trusted root to validate that this was required and it stopped working and now I cannot get it back to working even though I put the certificate back in the trusted root.  Now Chrome will not even prompt me for a certificate like it used too and it fails in Chrome, but still works in Fiddler.  There must be some magic configuration I am missing.

I also tried enabling "Negotiate Client Certificate" in the binding but Chrome still will not prompt me for a client certificate.  Here is the settings using "netsh http show sslcert"

 IP:port                 : 0.0.0.0:44398
 Certificate Hash        : 429e090db21e14344aa5d75d25074712f120f65f
 Application ID          : {4dc3e181-e14b-4a21-b022-59fc669b0914}
 Certificate Store Name  : MY
 Verify Client Certificate Revocation    : Disabled
 Verify Revocation Using Cached Client Certificate Only    : Disabled
 Usage Check    : Enabled
 Revocation Freshness Time : 0
 URL Retrieval Timeout   : 0
 Ctl Identifier          : (null)
 Ctl Store Name          : (null)
 DS Mapper Usage    : Disabled
 Negotiate Client Certificate    : Enabled

Here is the client certificate I am using:

I am baffled as to what the issue is.  I am adding a bounty for anyone that can help me figure this out.

Body:
Update:

Example from Microsoft:

https://learn.microsoft.com/en-us/azure/app-service/app-service-web-configure-tls-mutual-auth#special-considerations-for-certificate-validation

Original

This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.

First I edited <src>\.vs\config\applicationhost.config and made this change: <section name="access" overrideModeDefault="Allow" />

This allows me to edit <system.webServer> in web.config and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.

For production follow a guide like this to set up the IIS:

https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb

web.config:

<security>
  <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>

API Controller:

[RequireSpecificCert]
public class ValuesController : ApiController
{
    // GET api/values
    public IHttpActionResult Get()
    {
        return Ok("It works!");
    }
}

Attribute:

public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            X509Certificate2 cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            else
            {
                X509Chain chain = new X509Chain();

                //Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
                chain.ChainPolicy = new X509ChainPolicy()
                {
                    RevocationMode = X509RevocationMode.NoCheck,
                };
                try
                {
                    var chainBuilt = chain.Build(cert);
                    Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));

                    var validCert = CheckCertificate(chain, cert);

                    if (chainBuilt == false || validCert == false)
                    {
                        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                        {
                            ReasonPhrase = "Client Certificate not valid"
                        };
                        foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                        {
                            Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }

            base.OnAuthorization(actionContext);
        }
    }

    private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
    {
        var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);

        var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);

        //Check that the certificate have been issued by a specific Root Certificate
        var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));

        //Check that the certificate thumbprint matches our expected thumbprint
        var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);

        return validRoot && validCert;
    }
}

Can then call the API with client certification like this, tested from another web project.

[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{

    public IHttpActionResult Get()
    {
        var handler = new WebRequestHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ClientCertificates.Add(GetClientCert());
        handler.UseProxy = false;
        var client = new HttpClient(handler);
        var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
        var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return Ok(resultString);
    }

    private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certificateSerialNumber= "81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

            //Does not work for some reason, could be culture related
            //var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

            //if (certs.Count == 1)
            //{
            //    var cert = certs[0];
            //    return cert;
            //}

            var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));

            return cert;
        }
        finally
        {
            store?.Close();
        }
    }
}


问:
How do I use the ES6 import function with a symbolic path to the source file?
I am trying to understand the ES6 import function better, and I need your help.

The Scenario

Let's assume that I have a subset of code within my application that is used frequently, and I arrange all that code into a folder so that it is together.

So now, in three separate files, I have something like the following (note: I'm using TypeScript, so the file names in the example end in '.ts'):

file0.ts:

```<code>import {AbstractCoreCommunicationClass} from '../../../core-packages/communication/abstract-core-communication'
</code>```

file1.ts:

```<code>import {AbstractCoreCommunicationClass} from '../communication/abstract-core-communication'
</code>```

file2.ts:

```<code>import {AbstractCoreCommunicationClass} from '../../../../../core-packages/communication/abstract-core-communication'
</code>```

My Hope

It is my hope that I could clean up these references to something like this:

file0.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

file1.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

file2.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

Things I have Tried

I know that in Laravel (a different framework) that modules can be created and loaded by editing one of the core loader definition files such as composer.json or the main config/app.php file.

I have looked for a similar kind of protocol that can be used in the package.json file to reference non-npm packages, but I have not found any such information. The closest information that I have found is a tutorial in which NPM explains how to use NPM private packages, which would accomplish the same goal as long as I want to pay $7/month for the rest of my life to have my package hosted on their servers.

There must be a way to handle this kind of package management locally, but I have not discovered what it is, and that is why I need YOUR help!

All help is appreciated. There are no wrong answers.  Even a bad answer can sometimes point me in the right direction, so give me your thoughts and let's figure this out together so that everyone can benefit!

答:
The solution is specific to the language and the environment. It's currently impossible to address this issue with ES modules alone.

TypeScript allows to specify paths configuration entry for path aliases.

Webpack allows to specify alias configuration entry for path aliases.
The same thing can be achieved in Rollup with a plugin.

NPM allows to specify local dependencies without a need for a repository. There's also a number of solutions for local NPM repositories, e.g. sinopia.

Given that there is TypeScript project that installs NPM dependencies and is being built with Webpack, any of listed solutions is applicable.

Body:
I am trying to understand the ES6 import function better, and I need your help.

The Scenario

Let's assume that I have a subset of code within my application that is used frequently, and I arrange all that code into a folder so that it is together.

So now, in three separate files, I have something like the following (note: I'm using TypeScript, so the file names in the example end in '.ts'):

file0.ts:

import {AbstractCoreCommunicationClass} from '../../../core-packages/communication/abstract-core-communication'

file1.ts:

import {AbstractCoreCommunicationClass} from '../communication/abstract-core-communication'

file2.ts:

import {AbstractCoreCommunicationClass} from '../../../../../core-packages/communication/abstract-core-communication'

My Hope

It is my hope that I could clean up these references to something like this:

file0.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

file1.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

file2.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

Things I have Tried

I know that in Laravel (a different framework) that modules can be created and loaded by editing one of the core loader definition files such as composer.json or the main config/app.php file.

I have looked for a similar kind of protocol that can be used in the package.json file to reference non-npm packages, but I have not found any such information. The closest information that I have found is a tutorial in which NPM explains how to use NPM private packages, which would accomplish the same goal as long as I want to pay $7/month for the rest of my life to have my package hosted on their servers.

There must be a way to handle this kind of package management locally, but I have not discovered what it is, and that is why I need YOUR help!

All help is appreciated. There are no wrong answers.  Even a bad answer can sometimes point me in the right direction, so give me your thoughts and let's figure this out together so that everyone can benefit!


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
Try this;

```<code>function count_occurences($char_string, $haystack, $case_sensitive = true){
    if($case_sensitive === false){
        $char_string = strtolower($char_string);
        $haystack = strtolower($haystack);
    }

    $characters = str_split($char_string);
    $character_count = 0;
    foreach($characters as $character){
        $character_count = $character_count + substr_count($haystack, $character);
    }
    return $character_count;
}
</code>```

To use;

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
print count_occurences($needle, $haystack);
</code>```

You can set the third parameter to false to ignore case.

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
Try this;

function count_occurences($char_string, $haystack, $case_sensitive = true){
    if($case_sensitive === false){
        $char_string = strtolower($char_string);
        $haystack = strtolower($haystack);
    }

    $characters = str_split($char_string);
    $character_count = 0;
    foreach($characters as $character){
        $character_count = $character_count + substr_count($haystack, $character);
    }
    return $character_count;
}

To use;

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
print count_occurences($needle, $haystack);

You can set the third parameter to false to ignore case.


问:
How to correlate a sample curve with a reference curve
I have a sensor that is continually collecting data (shown in blue) every minute  that outputs a voltage output. I have a reference sensor collecting data (shown in red) that outputs in the units that I am interested. I am interested in determining a scaling factor so that I can scale the blue sensor's data to match the red sensor's data.

Normally, I would do a simple linear regression between the values of two sensors at any given time, which would give me a scaling factor based on the slope of the regression. I have noticed, however, that red sensor is slower at sensing a change in the environment, and can anywhere from 6-15 minutes behind -- this makes a regression difficult because at any given time, the two sensors may be measuring different things.

I was wondering if there is any sort of curve fitting that can be performed such that I can extract a scaling factor so that I can scale the blue sensor's data to match the red sensors.

I typically work in Python, so any Python packages (e.g. Numpy/Scipy) that would help with this would be especially helpful.

答:
Thanks for the help. What I ended up doing was finding all the local maxima and minima on the reference curve, then used those peak locations to search for the same maxima or minima on the sample curve. I basically used the reference curve's maxima/minima points as the center of a "window" and I would search for the highest/lowest point on the sample curve within a few minutes of the center point.

Once I had found all the matched maxima/minima on the sample curve, I then could perform a linear regression between these points to determine a scaling factor.


问:
BuildFire: difference between userData and datastore?
I see that userData and datastore are 2 somewhat similar frameworks provided by BuildFire to help developers build robust mobile apps. In their respective documentation (listed below), they have similar wording. I get that they are both ways of storing data, but I would like to know what each framework's intended use is? What are the optimal use cases for each, and what is the criteria for choosing one over the other?

datastore: https://github.com/BuildFire/sdk/wiki/How-to-use-Datastore

userData: https://github.com/BuildFire/sdk/wiki/User-Data:-Save-user-data-from-the-widget

My "guess" would be that userData is for saving information that is user-specific, but can't this information also be stored in the datastore as well? I would love a clarification.

答:
So there are 3 data storage services in BuildFire.

DataStore: Think of this as a CMS. Read and Write on the control panel and Read-Only on the widget/app side. It also has draft and live mode. Basically as you change the data in the control panel the app doesnt see any of it until you hit publush

UserData: This is read/write on both the control and the widget side. However, this is tied to a particular user. Meaning, all data is under the scope the currently logged in user

PublicData: Is similar to UserData -read/write everywhere- however, its scope is across all users. Meaning, all users can access and change data in public data.

It is worth mentioning that all these methods are automatically scoped to a plugin instance. Which means that data changed in one plugin instance will be completely independent of all other plugins

I hope this helps


问:
Sorting string containing numbers entered from a file in C?
So I'm working on a program that reads lines from a file containing an "item number", "unit price" and "purchase date" for each line / item. I've made it to the point where I can scan the file and organize it in the chart format required, but I can't figure out how to sort the data by "Item number".

Here is my code:

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

int main() {

FILE *fp;

char ch;

fp = fopen("f.txt", "r"); //open the file named f.txt
if (fp == NULL) //In case we can't find the file, notify the user
    printf("File not found\n");

printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header

while ((ch = fgetc(fp)) != EOF) { //set the character equal to the character next in the file using fgetc, and
                                //if its not equal to the end of file
    if (ch == ',') {
        printf("\t\t"); //add two tabs every time a ',' is encountered.
    }
    else {
        printf("%c",ch); //just display the output from the file
    }
}

fclose(fp); //closes the file

return 0;
}
</code>```

Sample input

Sample output

See, I need the output to be sorted by Item number (the far left column).
My idea was to add each line to a string array (char array in c), then from there I don't know how to identify the item number, in order to sort it for the output. I'm slightly familiar with fscanf, but do not know how to apply it here.
Any help is greatly appreciated, thank you.

答:
Okay, I believe it would be nice to break this down into some steps.

Define a struct that is specific for your data

Read a file line by line

For each line, use strtok() to split the string

Add these values into your array of struct

Use qsort() to sort your array of struct

I highly recommend you read more about strtok() and qsort() functions if you are not familiar with them.

Here is the code:

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

// STEP 1
typedef struct
{
    int item;
    float price;
    char date[50];
} Data;

int compare (const void * a, const void * b)
{

  Data *dataA = (Data *)a;
  Data *dataB = (Data *)b;

  return ( dataA->item - dataB->item );  // Ascending order
//return ( dataB->item - dataA->item );  // Descending order
}

int main()
{
  FILE * fp;
  char line[150];
  Data data[3];
  int i = 0;

  fp = fopen("f.txt", "r");
  while (1)
  {
    // STEP 2
    if (fgets(line,150, fp) == NULL) break;

    // STEP 3-4
    char * pch;
    pch = strtok (line,",");
    data[i].item = atoi(pch);  // item part
    pch = strtok (NULL, ",");
    data[i].price = atof(pch); // unit price part
    pch = strtok (NULL, ",");
    strcpy(data[i].date, pch); // purchase date part

    i++;
  }

  printf("##### BEFORE #####\n");
  printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header
  for (int k = 0; k < 3; k++)
  {
    printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date);
  }

  // STEP 5
  qsort (data, 3, sizeof(Data), compare);

  printf("\n##### AFTER #####\n");
  printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header
  for (int k = 0; k < 3; k++)
  {
    printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date);
  }

  fclose(fp);
  return 0;
}
</code>```

Please note that this code is written for your test case only. If your data structure is different (if you have more than three columns etc.) you need to modify the code. Also, you are gonna need to do some more error-handling.

Here is the output:

```<code>##### BEFORE #####
Item        Unit Price  Purchase Date
583         13.500000   10/24/2005
3912        599.989990  7/27/2008
12          19.990000   3/16/2001

##### AFTER #####
Item        Unit Price  Purchase Date
12          19.990000   3/16/2001
583         13.500000   10/24/2005
3912        599.989990  7/27/2008
</code>```

Hope this helps.

Baris

Body:
So I'm working on a program that reads lines from a file containing an "item number", "unit price" and "purchase date" for each line / item. I've made it to the point where I can scan the file and organize it in the chart format required, but I can't figure out how to sort the data by "Item number".

Here is my code:

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

int main() {

FILE *fp;

char ch;

fp = fopen("f.txt", "r"); //open the file named f.txt
if (fp == NULL) //In case we can't find the file, notify the user
    printf("File not found\n");

printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header

while ((ch = fgetc(fp)) != EOF) { //set the character equal to the character next in the file using fgetc, and
                                //if its not equal to the end of file
    if (ch == ',') {
        printf("\t\t"); //add two tabs every time a ',' is encountered.
    }
    else {
        printf("%c",ch); //just display the output from the file
    }
}

fclose(fp); //closes the file

return 0;
}

Sample input

Sample output

See, I need the output to be sorted by Item number (the far left column).
My idea was to add each line to a string array (char array in c), then from there I don't know how to identify the item number, in order to sort it for the output. I'm slightly familiar with fscanf, but do not know how to apply it here.
Any help is greatly appreciated, thank you.

Body:
Okay, I believe it would be nice to break this down into some steps.

Define a struct that is specific for your data

Read a file line by line

For each line, use strtok() to split the string

Add these values into your array of struct

Use qsort() to sort your array of struct

I highly recommend you read more about strtok() and qsort() functions if you are not familiar with them.

Here is the code:

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

// STEP 1
typedef struct
{
    int item;
    float price;
    char date[50];
} Data;

int compare (const void * a, const void * b)
{

  Data *dataA = (Data *)a;
  Data *dataB = (Data *)b;

  return ( dataA->item - dataB->item );  // Ascending order
//return ( dataB->item - dataA->item );  // Descending order
}

int main()
{
  FILE * fp;
  char line[150];
  Data data[3];
  int i = 0;

  fp = fopen("f.txt", "r");
  while (1)
  {
    // STEP 2
    if (fgets(line,150, fp) == NULL) break;

    // STEP 3-4
    char * pch;
    pch = strtok (line,",");
    data[i].item = atoi(pch);  // item part
    pch = strtok (NULL, ",");
    data[i].price = atof(pch); // unit price part
    pch = strtok (NULL, ",");
    strcpy(data[i].date, pch); // purchase date part

    i++;
  }

  printf("##### BEFORE #####\n");
  printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header
  for (int k = 0; k < 3; k++)
  {
    printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date);
  }

  // STEP 5
  qsort (data, 3, sizeof(Data), compare);

  printf("\n##### AFTER #####\n");
  printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header
  for (int k = 0; k < 3; k++)
  {
    printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date);
  }

  fclose(fp);
  return 0;
}

Please note that this code is written for your test case only. If your data structure is different (if you have more than three columns etc.) you need to modify the code. Also, you are gonna need to do some more error-handling.

Here is the output:

##### BEFORE #####
Item        Unit Price  Purchase Date
583         13.500000   10/24/2005
3912        599.989990  7/27/2008
12          19.990000   3/16/2001

##### AFTER #####
Item        Unit Price  Purchase Date
12          19.990000   3/16/2001
583         13.500000   10/24/2005
3912        599.989990  7/27/2008

Hope this helps.

Baris


问:
Impossible to obtain a PHP variable in HTML file via AJAX/Jquery

I am really beginning in PHP/AJAX/Jquery. And I tried the hunijkah's code from this page Replacing HTML form with success message after submit, form sends mail using separate php file and the PHP file gave back: {"success":true,"errors":[]} on a blank page replacing the current page. And I received emails. So I assume that contact.php works.
 I wonder how to get back 'success' in my HTML file and write an answer below the form in my current page after the successful operation.

Here the form, I used:

```<code><form action="contact.php" method="post" id="mail_form">
  <fieldset>
    <legend>Coordonnées personnelles :</legend>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Prénom *" required name="firstname" maxlength="50"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Nom *" required name="lastname" maxlength="50"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="email" placeholder="Email *" required name="email"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="tel" placeholder="+681 12 34 56 *" required name="usrtel"></p>
  </fieldset>
  <fieldset>
    <legend>Informations :</legend>
    <p><input class="w3-input w3-padding-16 w3-border" type="number" placeholder="Combien de personne(s) *" required name="people" min="1" max="100"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Besoins particuliers *" required name="message"></p>
  </fieldset>
  <p>* Champs obligatoires</p>
  <br>
  <div class="g-recaptcha" data-theme="dark" data-sitekey="6LdMKTcUAAAAABNdlU76EOu6W3Wv61T7uKGM9HwB"></div>
  <p>Souhaitez-vous une copie de votre message ?
  <input type="radio" id="rep_oui" name="copie" value="oui" checked><label for="rep_oui">Oui</label>
  <input type="radio" id="rep_non" name="copie" value="non"><label for="rep_non">Non</label></p>
  <p id="error" class="w3-red w3-xlarge w3-center"></p>
  <p><button class="w3-button w3-light-grey w3-block" type="submit" name="submit">ENVOYER LE MESSAGE</button></p>
  <p><button class="w3-button w3-light-grey w3-block" type="reset">EFFACER</button></p>
</form>
</code>```

In HTML file, I put this script between the head tags :

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> // 2.1.3 -> 3.2.1
</code>```

And this script at the bottom of my file:

```<code><script>
  $('#mail_form').on('submit', function(event)
  {
    event.preventDefault();
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
    $.post( "./contact.php" , dataIn )
    .done(function( dataOut )
    {
      //dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
      var finalArray = JASON.parse ( dataOut );
      if ((finalArray['success'] == true) && (finalArray['error1'] == false) && (finalArray['error2'] == false))//Check if it was successfull.
      {
        $("#mail_form").html("<p class='w3-xxlarge w3-center w3-tag'><strong>Votre message a bien été envoyé !</strong></p>");
      }
      else //there were errors
      {
        if (finalArray['error1'] == true)
        {
          // message not sent
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît.</strong></p>");
        }
        else if (finalArray['error2'] == true)
        {
          // one of 7 variables (at least) is empty ...
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur.</strong></p>");
        }
        else
        {
          // recaptcha is false
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Problème d'authentification par le Recaptcha</strong></p>");
        };
      };
    });
      return false; //Make sure you do this or it will submit the form and redirect
  });
</script>
</code>```

I can't see my mistake(s). It's exactly the same code and I wonder what's wrong. Maybe someone can help me because after dayS I've hit a brick wall.
Can I use a test in the HTML file to be sure that success variable is passed by the PHP file ?

PS : PHP file

```<code><?php

    $success = true;
    $error1 = false;
    $error2 = false;

     // ReCAPTCHA
     // grab recaptcha library
     require_once "recaptchalib.php";

     // foreach ($_POST as $key => $value) {
     // echo '<p><strong>' . $key.':</strong> '.$value.'</p>';
     // }

     // your secret key
     $secret = "***_***";

     // empty response
     $response = null;

     // check secret key
     $reCaptcha = new ReCaptcha($secret);

     // if submitted check response
     if ($_POST["g-recaptcha-response"]) {
          $response = $reCaptcha->verifyResponse(
          $_SERVER["REMOTE_ADDR"],
          $_POST["g-recaptcha-response"]
          );
     }

/*
    ********************************************************************************************
    CONFIGURATION
    ********************************************************************************************
*/

// destinataire est votre adresse mail. Pour envoyer à plusieurs à la fois, séparez-les par une virgule
$destinataire = '***@***.**,***@***.**';

// copie ? (envoie une copie au visiteur)
// $copie = 'oui';

// objet du message
$objet = 'Contact depuis le site ***';

// Action du formulaire (si votre page a des paramètres dans l'URL)
// si cette page est index.php?page=contact alors mettez index.php?page=contact
// sinon, laissez vide
$form_action = '';

/*
    ********************************************************************************************
    FIN DE LA CONFIGURATION
    ********************************************************************************************
*/

/*
 * cette fonction sert à nettoyer et enregistrer un texte
 */
function Rec($text)
{
    $text = htmlspecialchars(trim($text), ENT_QUOTES);
    if (1 === get_magic_quotes_gpc())
    {
        $text = stripslashes($text);
    }

    $text = nl2br($text);
    return $text;
};

/*
 * Cette fonction sert à vérifier la syntaxe d'un email
 */
function IsEmail($email)
{
    $value = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
    return (($value === 0) || ($value === false)) ? false : true;
}

// formulaire envoyé, on récupère tous les champs.
    $firstnameint     = (isset($_POST['firstname']))     ? Rec($_POST['firstname'])        : '';
    $lastnameint      = (isset($_POST['lastname']))      ? Rec($_POST['lastname'])         : '';
    $email            = (isset($_POST['email']))         ? Rec($_POST['email'])            : '';
    $usrtelint        = (isset($_POST['usrtel']))        ? Rec($_POST['usrtel'])           : '';
    $people           = (isset($_POST['people']))        ? Rec($_POST['people'])           : '';
    $messageint       = (isset($_POST['message']))       ? Rec($_POST['message'])          : '';
    $copieint         = (isset($_POST['copie']))         ? Rec($_POST['copie'])            : '';

// traitement du numéro de téléphone et aux variables
    $firstname = htmlspecialchars($firstnameint);
    $lastname = htmlspecialchars($lastnameint);
    $usrtel = htmlspecialchars($usrtelint);
    $message = htmlspecialchars($messageint);
    $copie = htmlspecialchars($copieint);

// traitement du nombre de convives
    $people = sprintf("%d",$_POST['people']); // ici le nombre sera un entier
    $people = abs($people); // $people sera positif ou nul = valeur absolue (évite les âges négatifs !)
    $people = intval($people); // renvoie aussi une valeur entière
    if (is_numeric($people)) // n'effectue que si $people est numérique
    {
    } else {
        $people='0';
    }
    if ($people >= 1 && $people <= 100) // n'effectue que si $usrtel est borné
    {
    } else {
        $people='0';
    }

// On va vérifier les variables et l'email ...
     $email = (IsEmail($email)) ? $email : ''; // soit l'email est vide si erroné, soit il vaut l'email entré

if (isset($_POST['submit']))
{
    if ($response != null && $response->success)
    {
        if (($firstname != '') && ($lastname != '') && ($email != '') && ($usrtel != '') && ($people != '') && ($message != '') && ($copie != ''))
        {
            // les 6 variables sont remplies, on génère puis envoie le mail
            $headers  = 'MIME-Version: 1.0' . "\n";
            $headers .= 'From:'.$firstname.' '.$lastname.' <'.$email.'>' . "\n" .
            $headers .= 'Reply-To:'.$email. "\n" .
            $headers .= 'Content-Type: text/html; charset="utf-8"; DelSp="Yes"; format=flowed '."\n" .
            $headers .= 'X-Mailer:PHP/'.phpversion().
            $headers .= 'Content-Transfer-Encoding: 7bit'." \r\n" ;

            // envoyer une copie au visiteur ?
            if ($copie == 'oui')
            {
                $cible = $destinataire.';'.$email;
            }
            else
            {
                $cible = $destinataire;
            };

            // Remplacement de certains caractères spéciaux
            $message = str_replace("'","'",$message);
            $message = str_replace("’","'",$message);
            $message = str_replace(""",'"',$message);
            $message = str_replace('<br>','',$message);
            $message = str_replace('<br />','',$message);
            $message = str_replace("<","<",$message);
            $message = str_replace(">",">",$message);
            $message = str_replace("&","&",$message);

            // formatage du corps de l'email
            $msg = '<div style="width: 100%; text-align: left; color: #00002b; font-weight: bold"> Message de '.$firstname.' '.
            $lastname.'<br />E-mail : '.$email.' et numéro de téléphone : '.$usrtel.'<br /> nombre de personne(s) : '.$people.
            '<br /> Message : '.$message.'</div>';

            // Envoi du mail
            $num_emails = 0;
            $tmp = explode(';', $cible);
            foreach($tmp as $email_destinataire)
            {
                if (mail($email_destinataire, $objet, $msg, $headers))
                $num_emails++;
            }

            if ((($copie == 'oui') && ($num_emails == 2)) || (($copie == 'non') && ($num_emails == 1)))
            {
                // message sent
                // Votre message a bien été envoyé !
            }
            else
            {
                // message not sent
                // L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît
                $error1 = true;
            };
        }
        else
        {
            // one of 7 variables (at least) is empty ...
            // Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur
            $error2 = true;
        };
    }
    else
    {
        // recaptcha is false
        // Problème d'authentification par le Recaptcha
        $success = false;
    };
}; // fin du if (!isset($_POST['envoi']))

        $array['success'] = $success;
        $array['error1'] = $error1;
        $array['error2'] = $error2;
        $finalArray=json_encode($array);
        echo $finalArray;
?>
</code>```

答:
The code you wrote is missing a ) bracket....and you must see in console.log in browser what return after JSON.parse...i attach the code with the missing bracket.
PS:For Jquery, now it's on 3.2 version...i suggest to upgrade at the current version instead that continue to use version 2, but this doesn't affect your code.

```<code>          $('#mail_form').on('submit', function()
          {
            var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
            $.post("./contact.php", dataIn )
            .done(function( dataOut )
            {
              //dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
              var myArray = JSON.parse(dataOut);
              console.log(myArray);
              if (myArray['success'] == true) //Check if it was successfull.
              {
                $("#mail_form").html("Congrats! We just e-mailed you!");
              }
              else //there were errors
              {
                $('#error').html(""); //Clear error span
                $.each(myArray['errors'], function(i)
                {
                  $('#error').append(myArray['errors'][i] + "<br>");
                });//------->HERE WAS MISSING A );
              };
            });
              return false; //Make sure you do this or it will submit the form and redirect
          });
</code>```

Hy Falakiko i answer you here because i put an example, your error it's probabily a wrong codification of the json array that php send to client javascript i write what i usually do to manage json data, inside a fecth of a query i insert a "contatore"(1,2,3,etc...) and stored rows inside an array $risultatiArray[] = array(.....) out of the loop i defined the array response json with the respective KEYS success, the key records and the key totaleRisultati that is the total contatore..after json_encode response...add also /n /r replaced with space but can be ininfluent.

```<code>            while ($sql->fetch()){
                ++$contatore;
                $risultatiArray[] = array('recid'  => trim($contatore),
                                          'rowid' => $id,
                                          'utente' => trim($Utente),
                                          'mese'   => trim($Mese),
                                          'orePermesso' => trim($OrePermesso));

            }
            $response['status'] = 'success';
            $response['records'] = $risultatiArray;
            $response['totaleRisultati'] = $contatore;
            $response = json_encode($response);
            $response = str_replace("\n", "", $response);
            $response = str_replace("\r", "", $response);
            print $response;
</code>```

And the json looks like this:

```<code>  {"status":"success","records":[{"recid":"1","rowid":9,"utente":"Andrea","mese":"Aprile","orePermesso":"8"},{"recid":"2","rowid":8,"utente":"andrea","mese":"Gennaio","orePermesso":"8"}],"totaleRisultati":2}
</code>```

So your code using success and error like an array, because i suppose from your code that errors is an array($.each(myArray['errors'])) could be :

```<code>       $arrayErrori[] = array('1'=>'error1','2'=>'error2');
       $array['succes'] = true;
       $array['errors'] = $arrayErrori;
       $finalArray=json_encode($array);
       print $finalArray;
</code>```

and the json will look like this....but keep in mind that "true" could be recognize like a string, must see this on road...

```<code>    {"succes":true,"errors":[{"1":"error1","2":"error2"}]}
</code>```

Ok now I'VE SEEN your php your error is that you are parsing an object that was just parsed in the server side, your json is correct.The error is here:

```<code>       var myArray = JSON.parse( dataOut );
</code>```

the dataOut is just in json you don't need to reparse. So

```<code>            var myArray = dataOut //Don't need to reparse again
</code>```

an example of an ajax call and the php

```<code>        $.ajax({
          type: "POST",
          url: "MNYLINKPHPTOCALL JSON",
          dataType: "JSON",
          data:{},
          success:function(data){
                console.log(data);
                console.log(data.success);
                console.log(data.errors);
                console.log(data.errors[0]);
                console.log(data.errors[1]);
          },
          error:function(data){
            alert('Chiamata Fallita');
          }
        });
</code>```

AND THE JSON FROM THE PHP

```<code>$risultatiErrors= array("prova","prova2");
$output_array['success'] = true;
$output_array['errors'] = $risultatiErrors;
$final = json_encode($output_array);//<---------yOU ARE JUST ENCODING HERE
echo $final;
</code>```

Body:
I am really beginning in PHP/AJAX/Jquery. And I tried the hunijkah's code from this page Replacing HTML form with success message after submit, form sends mail using separate php file and the PHP file gave back: {"success":true,"errors":[]} on a blank page replacing the current page. And I received emails. So I assume that contact.php works.
 I wonder how to get back 'success' in my HTML file and write an answer below the form in my current page after the successful operation.

Here the form, I used:

<form action="contact.php" method="post" id="mail_form">
  <fieldset>
    <legend>Coordonnées personnelles :</legend>

<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Prénom *" required name="firstname" maxlength="50">

<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Nom *" required name="lastname" maxlength="50">

<input class="w3-input w3-padding-16 w3-border" type="email" placeholder="Email *" required name="email">

<input class="w3-input w3-padding-16 w3-border" type="tel" placeholder="+681 12 34 56 *" required name="usrtel">

  </fieldset>
  <fieldset>
    <legend>Informations :</legend>

<input class="w3-input w3-padding-16 w3-border" type="number" placeholder="Combien de personne(s) *" required name="people" min="1" max="100">

<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Besoins particuliers *" required name="message">

  </fieldset>

* Champs obligatoires

Souhaitez-vous une copie de votre message ?
  <input type="radio" id="rep_oui" name="copie" value="oui" checked>Oui
  <input type="radio" id="rep_non" name="copie" value="non">Non

<button class="w3-button w3-light-grey w3-block" type="submit" name="submit">ENVOYER LE MESSAGE</button>

<button class="w3-button w3-light-grey w3-block" type="reset">EFFACER</button>

</form>

In HTML file, I put this script between the head tags :

     // 2.1.3 -> 3.2.1

And this script at the bottom of my file:

I can't see my mistake(s). It's exactly the same code and I wonder what's wrong. Maybe someone can help me because after dayS I've hit a brick wall.
Can I use a test in the HTML file to be sure that success variable is passed by the PHP file ?

PS : PHP file

<?php

    $success = true;
    $error1 = false;
    $error2 = false;

     // ReCAPTCHA
     // grab recaptcha library
     require_once "recaptchalib.php";

     // foreach ($_POST as $key => $value) {
     // echo '
' . $key.': '.$value.'
';
     // }

     // your secret key
     $secret = "***_***";

     // empty response
     $response = null;

     // check secret key
     $reCaptcha = new ReCaptcha($secret);

     // if submitted check response
     if ($_POST["g-recaptcha-response"]) {
          $response = $reCaptcha->verifyResponse(
          $_SERVER["REMOTE_ADDR"],
          $_POST["g-recaptcha-response"]
          );
     }

/*
    ********************************************************************************************
    CONFIGURATION
    ********************************************************************************************
*/

// destinataire est votre adresse mail. Pour envoyer à plusieurs à la fois, séparez-les par une virgule
$destinataire = '***@***.**,***@***.**';

// copie ? (envoie une copie au visiteur)
// $copie = 'oui';

// objet du message
$objet = 'Contact depuis le site ***';

// Action du formulaire (si votre page a des paramètres dans l'URL)
// si cette page est index.php?page=contact alors mettez index.php?page=contact
// sinon, laissez vide
$form_action = '';

/*
    ********************************************************************************************
    FIN DE LA CONFIGURATION
    ********************************************************************************************
*/

/*
 * cette fonction sert à nettoyer et enregistrer un texte
 */
function Rec($text)
{
    $text = htmlspecialchars(trim($text), ENT_QUOTES);
    if (1 === get_magic_quotes_gpc())
    {
        $text = stripslashes($text);
    }

    $text = nl2br($text);
    return $text;
};

/*
 * Cette fonction sert à vérifier la syntaxe d'un email
 */
function IsEmail($email)
{
    $value = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
    return (($value === 0) || ($value === false)) ? false : true;
}

// formulaire envoyé, on récupère tous les champs.
    $firstnameint     = (isset($_POST['firstname']))     ? Rec($_POST['firstname'])        : '';
    $lastnameint      = (isset($_POST['lastname']))      ? Rec($_POST['lastname'])         : '';
    $email            = (isset($_POST['email']))         ? Rec($_POST['email'])            : '';
    $usrtelint        = (isset($_POST['usrtel']))        ? Rec($_POST['usrtel'])           : '';
    $people           = (isset($_POST['people']))        ? Rec($_POST['people'])           : '';
    $messageint       = (isset($_POST['message']))       ? Rec($_POST['message'])          : '';
    $copieint         = (isset($_POST['copie']))         ? Rec($_POST['copie'])            : '';

// traitement du numéro de téléphone et aux variables
    $firstname = htmlspecialchars($firstnameint);
    $lastname = htmlspecialchars($lastnameint);
    $usrtel = htmlspecialchars($usrtelint);
    $message = htmlspecialchars($messageint);
    $copie = htmlspecialchars($copieint);

// traitement du nombre de convives
    $people = sprintf("%d",$_POST['people']); // ici le nombre sera un entier
    $people = abs($people); // $people sera positif ou nul = valeur absolue (évite les âges négatifs !)
    $people = intval($people); // renvoie aussi une valeur entière
    if (is_numeric($people)) // n'effectue que si $people est numérique
    {
    } else {
        $people='0';
    }
    if ($people >= 1 && $people <= 100) // n'effectue que si $usrtel est borné
    {
    } else {
        $people='0';
    }

// On va vérifier les variables et l'email ...
     $email = (IsEmail($email)) ? $email : ''; // soit l'email est vide si erroné, soit il vaut l'email entré

if (isset($_POST['submit']))
{
    if ($response != null && $response->success)
    {
        if (($firstname != '') && ($lastname != '') && ($email != '') && ($usrtel != '') && ($people != '') && ($message != '') && ($copie != ''))
        {
            // les 6 variables sont remplies, on génère puis envoie le mail
            $headers  = 'MIME-Version: 1.0' . "\n";
            $headers .= 'From:'.$firstname.' '.$lastname.' <'.$email.'>' . "\n" .
            $headers .= 'Reply-To:'.$email. "\n" .
            $headers .= 'Content-Type: text/html; charset="utf-8"; DelSp="Yes"; format=flowed '."\n" .
            $headers .= 'X-Mailer:PHP/'.phpversion().
            $headers .= 'Content-Transfer-Encoding: 7bit'." \r\n" ;

            // envoyer une copie au visiteur ?
            if ($copie == 'oui')
            {
                $cible = $destinataire.';'.$email;
            }
            else
            {
                $cible = $destinataire;
            };

            // Remplacement de certains caractères spéciaux
            $message = str_replace("'","'",$message);
            $message = str_replace("’","'",$message);
            $message = str_replace(""",'"',$message);
            $message = str_replace('
','',$message);
            $message = str_replace('
','',$message);
            $message = str_replace("<","<",$message);
            $message = str_replace(">",">",$message);
            $message = str_replace("&","&",$message);

            // formatage du corps de l'email
            $msg = '
 Message de '.$firstname.' '.
            $lastname.'
E-mail : '.$email.' et numéro de téléphone : '.$usrtel.'
 nombre de personne(s) : '.$people.
            '
 Message : '.$message.'
';

            // Envoi du mail
            $num_emails = 0;
            $tmp = explode(';', $cible);
            foreach($tmp as $email_destinataire)
            {
                if (mail($email_destinataire, $objet, $msg, $headers))
                $num_emails++;
            }

            if ((($copie == 'oui') && ($num_emails == 2)) || (($copie == 'non') && ($num_emails == 1)))
            {
                // message sent
                // Votre message a bien été envoyé !
            }
            else
            {
                // message not sent
                // L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît
                $error1 = true;
            };
        }
        else
        {
            // one of 7 variables (at least) is empty ...
            // Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur
            $error2 = true;
        };
    }
    else
    {
        // recaptcha is false
        // Problème d'authentification par le Recaptcha
        $success = false;
    };
}; // fin du if (!isset($_POST['envoi']))

        $array['success'] = $success;
        $array['error1'] = $error1;
        $array['error2'] = $error2;
        $finalArray=json_encode($array);
        echo $finalArray;
?>

Body:
The code you wrote is missing a ) bracket....and you must see in console.log in browser what return after JSON.parse...i attach the code with the missing bracket.
PS:For Jquery, now it's on 3.2 version...i suggest to upgrade at the current version instead that continue to use version 2, but this doesn't affect your code.

          $('#mail_form').on('submit', function()
          {
            var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
            $.post("./contact.php", dataIn )
            .done(function( dataOut )
            {
              //dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
              var myArray = JSON.parse(dataOut);
              console.log(myArray);
              if (myArray['success'] == true) //Check if it was successfull.
              {
                $("#mail_form").html("Congrats! We just e-mailed you!");
              }
              else //there were errors
              {
                $('#error').html(""); //Clear error span
                $.each(myArray['errors'], function(i)
                {
                  $('#error').append(myArray['errors'][i] + "<br>");
                });//------->HERE WAS MISSING A );
              };
            });
              return false; //Make sure you do this or it will submit the form and redirect
          });

Hy Falakiko i answer you here because i put an example, your error it's probabily a wrong codification of the json array that php send to client javascript i write what i usually do to manage json data, inside a fecth of a query i insert a "contatore"(1,2,3,etc...) and stored rows inside an array $risultatiArray[] = array(.....) out of the loop i defined the array response json with the respective KEYS success, the key records and the key totaleRisultati that is the total contatore..after json_encode response...add also /n /r replaced with space but can be ininfluent.

            while ($sql->fetch()){
                ++$contatore;
                $risultatiArray[] = array('recid'  => trim($contatore),
                                          'rowid' => $id,
                                          'utente' => trim($Utente),
                                          'mese'   => trim($Mese),
                                          'orePermesso' => trim($OrePermesso));

            }
            $response['status'] = 'success';
            $response['records'] = $risultatiArray;
            $response['totaleRisultati'] = $contatore;
            $response = json_encode($response);
            $response = str_replace("\n", "", $response);
            $response = str_replace("\r", "", $response);
            print $response;

And the json looks like this:

  {"status":"success","records":[{"recid":"1","rowid":9,"utente":"Andrea","mese":"Aprile","orePermesso":"8"},{"recid":"2","rowid":8,"utente":"andrea","mese":"Gennaio","orePermesso":"8"}],"totaleRisultati":2}

So your code using success and error like an array, because i suppose from your code that errors is an array($.each(myArray['errors'])) could be :

       $arrayErrori[] = array('1'=>'error1','2'=>'error2');
       $array['succes'] = true;
       $array['errors'] = $arrayErrori;
       $finalArray=json_encode($array);
       print $finalArray;

and the json will look like this....but keep in mind that "true" could be recognize like a string, must see this on road...

    {"succes":true,"errors":[{"1":"error1","2":"error2"}]}

Ok now I'VE SEEN your php your error is that you are parsing an object that was just parsed in the server side, your json is correct.The error is here:

       var myArray = JSON.parse( dataOut );

the dataOut is just in json you don't need to reparse. So

            var myArray = dataOut //Don't need to reparse again

an example of an ajax call and the php

        $.ajax({
          type: "POST",
          url: "MNYLINKPHPTOCALL JSON",
          dataType: "JSON",
          data:{},
          success:function(data){
                console.log(data);
                console.log(data.success);
                console.log(data.errors);
                console.log(data.errors[0]);
                console.log(data.errors[1]);
          },
          error:function(data){
            alert('Chiamata Fallita');
          }
        });

AND THE JSON FROM THE PHP

$risultatiErrors= array("prova","prova2");
$output_array['success'] = true;
$output_array['errors'] = $risultatiErrors;
$final = json_encode($output_array);//<---------yOU ARE JUST ENCODING HERE
echo $final;


问:
Deploy Springboot TCP APP on PWS
Trying to deploy SpringBoot TCP server application on Pivotal Web Service(Cloud Foundry)

The following is in manifest.yml file

```<code>applications:
- name: myapp-api
  path: target/myapp-api-0.0.1-SNAPSHOT.jar
  host: app
  domain: cf-tcpapps.io
  memory: 1G
  instances: 1
</code>```

When i cf push i get this error

```<code>FAILED
Server error, status code: 400, error code: 310009, message: You have exceeded the total reserved route ports for your organization's quota.
</code>```

when i cf router-groups i get

```<code>FAILED
Failed fetching router groups.
Server error, status code: 401, error code: UnauthorizedError, message: You are not authorized to perform the requested action
</code>```

How can one deploy a spring mvc api that exposes a TCP port

答:
The cf router-groups command is an admin-only command.

If cf domains returns the cf-tcpapps.io domain, a router group has already been set up, but your org or space has not been given permission (i.e., a quota of available TCP ports) to use it.

Ask your platform operator/admin. They may be able to increase your quota, or create a new TCP domain for you to use.

Title: Deploy Springboot TCP APP on PWS

Body:
Trying to deploy SpringBoot TCP server application on Pivotal Web Service(Cloud Foundry)

The following is in manifest.yml file

applications:
- name: myapp-api
  path: target/myapp-api-0.0.1-SNAPSHOT.jar
  host: app
  domain: cf-tcpapps.io
  memory: 1G
  instances: 1

When i cf push i get this error

FAILED
Server error, status code: 400, error code: 310009, message: You have exceeded the total reserved route ports for your organization's quota.

when i cf router-groups i get

FAILED
Failed fetching router groups.
Server error, status code: 401, error code: UnauthorizedError, message: You are not authorized to perform the requested action

How can one deploy a spring mvc api that exposes a TCP port


问:
Alternative to finding elements using hard coded Xpath
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

```<code><div class="payment-form">
   <div class="payment-form__payment-type">
      <div class="false-label">Payment type</div>
      <div class="form-column">
         <div class="false-label">Name on card</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="name-on-card">Name on card</label> <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the name on card</p>
      </div>
      <div class="form-column">
         <div class="false-label">Card number</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="card-number">e.g 1111-2222-3333-4444</label> <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the card number</p>
      </div>
   </div>
</div>
</code>```

Now the problem I am having is with the validation messages which are the same class:

```<code><p class="validation-message validation-message--active" style="">
</code>```

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

```<code>public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");
</code>```

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

答:
Providing that the error message it self doesn't change you should be able to use the following Xpath:

```<code> //p[contains(text() ='Please correct the card number')]
</code>```

No matter where it is on the page it should continue to work as long as the actual error message doesn't change. I try to use the [contains] approach for all of the work I do with selenium. It makes the application more sturdy and less affected by html changes. If you have any control over the page then adding an id to the paragraph would probably be a better way to do it. Then you can use something like:

```<code> //p[@id='cardnumber_error']
</code>```

Body:
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

Payment type

Name on card

Name on card <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true">

Please correct the name on card

Card number

e.g 1111-2222-3333-4444 <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true">

Please correct the card number

Now the problem I am having is with the validation messages which are the same class:

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

Body:
Providing that the error message it self doesn't change you should be able to use the following Xpath:

 //p[contains(text() ='Please correct the card number')]

No matter where it is on the page it should continue to work as long as the actual error message doesn't change. I try to use the [contains] approach for all of the work I do with selenium. It makes the application more sturdy and less affected by html changes. If you have any control over the page then adding an id to the paragraph would probably be a better way to do it. Then you can use something like:

 //p[@id='cardnumber_error']