问:
Regex works in regex builder but not in C#
I've seen a few threads on this, and have tried the solutions presented in them, but I can't seem to fix this. I have a regular expression that checks for two dates in mm/dd/yyyy , mm/dd/yyyy format. There can be any number of spaces in between. My expression works on http://regexr.com/, but when I run the code in VS the regex check is always false. Any help would be greatly appreciated!

```<code>        var reg = new Regex(@"\d{1,2}\/\d{1,2}\/\d{1,4}[ ]{0,}\,[ ]{0,}\d{1,2}\/\d{1,2}\/\d{1,4}");

        Console.WriteLine("Please enter two dates in dd/mm/yyyy format seperated by a comma");
        string datesIn = Console.ReadLine();

        while (reg.IsMatch(datesIn) != true);
        {
            Console.WriteLine("Sorry, please make sure to enter your dates in dd/mm/yyyy format seperated by a comma.");
            datesIn.Replace(datesIn, Console.ReadLine());
        }

        String[] dates = datesIn.Split(',');

        foreach (var date in dates)
            Console.WriteLine(date.Trim());
        Console.ReadLine();
</code>```

答:
I strongly recommend you to let .NET do that job for you, using TryParse

```<code>using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var input = "12/10/2012, 12/15/2015";
        String[] dates = input.Split(',');

        if(dates.Length != 2){
            Console.WriteLine("I said 2 dates");
        } else {
            foreach (var date in dates)
            {
                DateTime parsedDate;
                if(DateTime.TryParse(date, new CultureInfo("es"), DateTimeStyles.None, out parsedDate))
                {
                    Console.WriteLine("{0} Perfect!", parsedDate);
                }
                else
                {
                    Console.WriteLine("{0} Not right sir!", date);
                }
            }
        }

        Console.ReadLine();
    }
}
</code>```

Source Code: https://dotnetfiddle.net/VGEQuM

Body:
I've seen a few threads on this, and have tried the solutions presented in them, but I can't seem to fix this. I have a regular expression that checks for two dates in mm/dd/yyyy , mm/dd/yyyy format. There can be any number of spaces in between. My expression works on http://regexr.com/, but when I run the code in VS the regex check is always false. Any help would be greatly appreciated!

        var reg = new Regex(@"\d{1,2}\/\d{1,2}\/\d{1,4}[ ]{0,}\,[ ]{0,}\d{1,2}\/\d{1,2}\/\d{1,4}");

        Console.WriteLine("Please enter two dates in dd/mm/yyyy format seperated by a comma");
        string datesIn = Console.ReadLine();

        while (reg.IsMatch(datesIn) != true);
        {
            Console.WriteLine("Sorry, please make sure to enter your dates in dd/mm/yyyy format seperated by a comma.");
            datesIn.Replace(datesIn, Console.ReadLine());
        }

        String[] dates = datesIn.Split(',');

        foreach (var date in dates)
            Console.WriteLine(date.Trim());
        Console.ReadLine();

Body:
I strongly recommend you to let .NET do that job for you, using TryParse

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var input = "12/10/2012, 12/15/2015";
        String[] dates = input.Split(',');

        if(dates.Length != 2){
            Console.WriteLine("I said 2 dates");
        } else {
            foreach (var date in dates)
            {
                DateTime parsedDate;
                if(DateTime.TryParse(date, new CultureInfo("es"), DateTimeStyles.None, out parsedDate))
                {
                    Console.WriteLine("{0} Perfect!", parsedDate);
                }
                else
                {
                    Console.WriteLine("{0} Not right sir!", date);
                }
            }
        }

        Console.ReadLine();
    }
}

Source Code: https://dotnetfiddle.net/VGEQuM


来源: stackexchange

问:
CASE Syntax error when > is used in the WHEN clause
This Query runs fine when I do not have the ">" symbol in the WHEN clause however I need this to work when the ProposalDate is any date later than '2017-04-10 00:00:00.000'. Not sure why I am getting a Syntax error when I add the > into the WHEN clause.</p>

```<code>SELECT *,
    CASE ProposalDate WHEN > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) +
             (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'
</code>```

答:
The shorthand case syntax doesn't use any operators, just a series of values which are evaluated with the = condition. If you want to use other operators, you have to use the full case syntax:

```<code>SELECT *,
       CASE WHEN ProposalDate > '2017-04-10 00:00:00.000'
            THEN (OrderTotal - ProposalWholesalePrice) +
                 (ProposalWholesalePrice * 1.02)
           ELSE OrderTotal
       END "New_OrderTotal"
FROM   webservices.dbo.DT_Open_Orders_Baseprice
WHERE  ProposalSerialNumber = '639036'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This Query runs fine when I do not have the ">" symbol in the WHEN clause however I need this to work when the ProposalDate is any date later than '2017-04-10 00:00:00.000'. Not sure why I am getting a Syntax error when I add the > into the WHEN clause.

SELECT *,
    CASE ProposalDate WHEN > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) +
             (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'

Body:
The shorthand case syntax doesn't use any operators, just a series of values which are evaluated with the = condition. If you want to use other operators, you have to use the full case syntax:

SELECT *,
       CASE WHEN ProposalDate > '2017-04-10 00:00:00.000'
            THEN (OrderTotal - ProposalWholesalePrice) +
                 (ProposalWholesalePrice * 1.02)
           ELSE OrderTotal
       END "New_OrderTotal"
FROM   webservices.dbo.DT_Open_Orders_Baseprice
WHERE  ProposalSerialNumber = '639036'


问:
CSS works locally but not on Dev server
I have a page that displays a ticket number from a ticketing system.  When the page loads it generates a ticket number and displays this number in a label.  It also dynamically adds a cssclass to the label based on the ticket that is generated.  This works fine locally but when I upload it to the dev server the cssclass does not show.  There is another item on the same aspx page that has a cssclass added on the front end and it is displaying fine.  I looked at the yiew source from the page from the dev server and it appears the class gets added fine on the backend.

Here is the aspx:

```<code><table width="300">
    <tr>
        <td class="ItemTxt">Customer Track Number</td>
    </tr>
    <tr>
        <td align="left">
            <p>The customer track number is: </p>
            <p style="text-align:center"><asp:Label ID="lblTrackNum" runat="server" Text="Label" CssClass="greenTicketColor"></asp:Label></p>
            <p>Click OK to continue and return to the Lobby Dash.</p>

            <p><asp:Button ID="btnOK" runat="server" Text="OK" onclick="btnOK_Click" /></p>
        </td>
    </tr>
</table>
enter code here
</code>```

Here is the codebehind

```<code>private void DisplayTicketNumber(string sTicketNumber)
    {
        string sTrackColor = sTicketNumber.Substring(0, 1);
        switch (sTrackColor)
        {
            case "G":
                lblTrackNum.CssClass = "greenTicketColor";
                break;
            case "R":
                lblTrackNum.CssClass = "redTicketColor";
                break;
            case "B":
                lblTrackNum.CssClass = "blueTicketColor";
                break;
            case "M":
                lblTrackNum.CssClass = "maoTicketColor";
                break;
            case "V":
                lblTrackNum.CssClass = "vandeTicketColor";
                break;
            case "A":
                lblTrackNum.CssClass = "afipTicketColor";
                break;
            case "E":
                lblTrackNum.CssClass = "ebtTicketColor";
                break;
            case "Q":
                lblTrackNum.CssClass = "qaTicketColor";
                break;
            case "F":
                lblTrackNum.CssClass = "fhTicketColor";
                break;
            default:
                break;
        }
        lblTrackNum.Text = sTicketNumber;
    }
</code>```

Here is the CSS

```<code>    .greenTicketColor
{
    color: #007F00;
    font-size: 50px;
    font-weight: bold;
}
.redTicketColor
{
    color: #DF0000;
    font-size: 50px;
    font-weight: bold;
}

.blueTicketColor
{
    color: #0065CB;
    font-size: 50px;
    font-weight: bold;
}

.maoTicketColor
{
    color: #959595;
    font-size: 50px;
    font-weight: bold;
}

.vandeTicketColor
{
    color: #7f007f;
    font-size: 50px;
    font-weight: bold;
}

.afipTicketColor
{
    color: #00cbfd;
    font-size: 50px;
    font-weight: bold;
}

.ebtTicketColor
{
    color: #fd98cb;
    font-size: 50px;
    font-weight: bold;
}

.qaTicketColor
{
    color: #cbfdcb;
    font-size: 50px;
    font-weight: bold;
}

.fhTicketColor
{
    color: #fdfd00;
    font-size: 50px;
    font-weight: bold;
}
</code>```

Here is the view source from the page displayed from server.  Notice it shows the class correctly added.

```<code><table width="300">
<tr>
    <td class="ItemTxt">Customer Track Number</td>
</tr>
<tr>
    <td align="left">
        <p>The customer track number is: </p>
        <p style="text-align:center"><span id="MainContent_lblTrackNum" class="blueTicketColor">B6</span></p>
        <p>Click OK to continue and return to the Lobby Dash.</p>

        <p><input type="submit" name="ctl00$MainContent$btnOK" value="OK" id="MainContent_btnOK" /></p>
    </td>
</tr>
</code>```

Thanks for the responses. I know the easiest thing is the reference to the css file. If you look at this line the style is showing correctly:

```<code><td class="ItemTxt">Customer Track Number</td>
</code>```

The line of code above is on the aspx page. The style that is being added in the codebehind is not displaying. Here's my head content. This is from a Master Page. Don't know if that matters..

```<code><head runat="server">
<title>FAST Tracker</title>
<link href="~/Styles/FastTrackStyles.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
</code>```

答:
I had a similar issue and the resolution for me was to make sure the virtual directory permissions are setup properly, otherwise the CSS and images won't show. </p>

<p>You can usually right click on another web application in IIS to see the permissions to reference for your web application.  </p>

Title: CSS works locally but not on Dev server

Body:
I have a page that displays a ticket number from a ticketing system.  When the page loads it generates a ticket number and displays this number in a label.  It also dynamically adds a cssclass to the label based on the ticket that is generated.  This works fine locally but when I upload it to the dev server the cssclass does not show.  There is another item on the same aspx page that has a cssclass added on the front end and it is displaying fine.  I looked at the yiew source from the page from the dev server and it appears the class gets added fine on the backend.

Here is the aspx:

        Customer Track Number

The customer track number is:

<asp:Label ID="lblTrackNum" runat="server" Text="Label" CssClass="greenTicketColor"></asp:Label>

Click OK to continue and return to the Lobby Dash.

<asp:Button ID="btnOK" runat="server" Text="OK" onclick="btnOK_Click" />

enter code here

Here is the codebehind

private void DisplayTicketNumber(string sTicketNumber)
    {
        string sTrackColor = sTicketNumber.Substring(0, 1);
        switch (sTrackColor)
        {
            case "G":
                lblTrackNum.CssClass = "greenTicketColor";
                break;
            case "R":
                lblTrackNum.CssClass = "redTicketColor";
                break;
            case "B":
                lblTrackNum.CssClass = "blueTicketColor";
                break;
            case "M":
                lblTrackNum.CssClass = "maoTicketColor";
                break;
            case "V":
                lblTrackNum.CssClass = "vandeTicketColor";
                break;
            case "A":
                lblTrackNum.CssClass = "afipTicketColor";
                break;
            case "E":
                lblTrackNum.CssClass = "ebtTicketColor";
                break;
            case "Q":
                lblTrackNum.CssClass = "qaTicketColor";
                break;
            case "F":
                lblTrackNum.CssClass = "fhTicketColor";
                break;
            default:
                break;
        }
        lblTrackNum.Text = sTicketNumber;
    }

Here is the CSS

    .greenTicketColor
{
    color: #007F00;
    font-size: 50px;
    font-weight: bold;
}
.redTicketColor
{
    color: #DF0000;
    font-size: 50px;
    font-weight: bold;
}

.blueTicketColor
{
    color: #0065CB;
    font-size: 50px;
    font-weight: bold;
}

.maoTicketColor
{
    color: #959595;
    font-size: 50px;
    font-weight: bold;
}

.vandeTicketColor
{
    color: #7f007f;
    font-size: 50px;
    font-weight: bold;
}

.afipTicketColor
{
    color: #00cbfd;
    font-size: 50px;
    font-weight: bold;
}

.ebtTicketColor
{
    color: #fd98cb;
    font-size: 50px;
    font-weight: bold;
}

.qaTicketColor
{
    color: #cbfdcb;
    font-size: 50px;
    font-weight: bold;
}

.fhTicketColor
{
    color: #fdfd00;
    font-size: 50px;
    font-weight: bold;
}

Here is the view source from the page displayed from server.  Notice it shows the class correctly added.

    Customer Track Number

The customer track number is:

B6

Click OK to continue and return to the Lobby Dash.

<input type="submit" name="ctl00$MainContent$btnOK" value="OK" id="MainContent_btnOK" />

Thanks for the responses. I know the easiest thing is the reference to the css file. If you look at this line the style is showing correctly:

Customer Track Number

The line of code above is on the aspx page. The style that is being added in the codebehind is not displaying. Here's my head content. This is from a Master Page. Don't know if that matters..

<title>FAST Tracker</title>
<link href="~/Styles/FastTrackStyles.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>

Body:
I had a similar issue and the resolution for me was to make sure the virtual directory permissions are setup properly, otherwise the CSS and images won't show.

You can usually right click on another web application in IIS to see the permissions to reference for your web application.


问:
How do you properly synchronize threads on the native side of a JNI environment?
Question Brief

I am using C++ and Java in one process via JNI. For the use case in question, both a C++ thread and a Java thread are accessing the same data, they are doing so on the C++ side, and I want to properly synchronize the access.

So far, almost all of my JNI thread synchronization has been on the Java side where the answer is obvious: use the provided Java concurrency package and the built-in concurrency language features. Unfortunately, the answer is not so obvious on the C++ side.

What I've Tried so far Brief

I tried using a pthreads mutex thinking that it might work even though I'm not using pthreads to create threads, but that occasionally gets stuck when trying to lock - I'll show an example of that farther below.

Question Details

In my current, specific usage, c++ is polling for changes provided by Java on a 1 second timer (not what I'd like, but I'm not sure how I would make it event-driven given the nature of the legacy c++ code). The Java thread provides data by calling a native function and c++ copies the data into a c++ structure.

This is the type of situation in code (happens on 2 threads, Thread1 and Thread2):

Code Example

Note quite an SSCCE, as it's missing definitions for TheData and TheDataWrapper, but it doesn't really matter what they contain. Assume they merely contain a couple of public ints if that helps your thought process (though, in my case, it's actually multiple arrays of int and arrays of float).

C++:

```<code>class objectA
{
    void poll();
    void supplyData(JNIEnv* jni, jobject jthis, jobject data);
    TheDataWrapper cpp_data;
    bool isUpdated;

    void doStuff(TheDataWrapper* data);
};

// poll() happens on a c++ thread we will call Thread1
void objectA :: poll()
{
    // Here, both isUpdated and cpp_data need synchronization

    if(isUpdated)
    {
        do_stuff(&cpp_data);
        isUpdated = false;
    }
}

// supplyData happens on the Thread2, called as a native function from a java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    // some operation happens that copies the java data into a c++ equivalent
    // in my specific case this happens to be copying ints/floats from java arrays to c++ arrays
    // this needs to be synchronized
    cpp_data.copyFrom(data);
    isUpdated = true;
}
</code>```

Java:

```<code>class ObjectB
{
    // f() happens on a Java thread which we will call Thread2
    public void f()
    {
        // for the general case it doesn't really matter what the data is
        TheData data = TheData.prepareData();
        supplyData(data);
    }

    public native void supplyData(TheData data);
}
</code>```

What I've Tried so far Details

When I tried pthread's locking as below, sometimes execution gets stuck in pthread_mutex_lock. There should not be a deadlock in this situation, but just to test further I ran a scenario where supplyData was not getting called at all (no data was being supplied), so no deadlock should have been possible, yet the first call to poll will occasionally hang anyway. Perhaps using a pthreads mutex is not a good idea in this situation? Or perhaps I did something stupid and keep overlooking it.

So far, I tried using pthreads as below:

Code Example

C++:

```<code>class objectA
{
    pthread_mutex_t dataMutex;
    ... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
    pthread_mutex_lock(&dataMutex);

    ... // all the poll stuff from before

    pthread_mutex_unlock(&dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    pthread_mutex_lock(&dataMutex);

    ... // all the supplyData stuff from before

    pthread_mutex_unlock(&dataMutex);
}
</code>```

Another option I thought about but have not done

I also considered using JNI to call back into java to request a lock using java's concurrency control. That should work, as either thread should block on the java side as needed. However, since accessing java from c++ is overly verbose, I was hoping to avoid going through that headache. I probably could make a c++ class which encapsulates JNI calls into java to request a java lock; that would simplify c++ code, though I wonder about the overhead of crossing back and forth over JNI just for thread locks.

It seems this is not necessary, per the comment by @Radiodef. It appears JNI includes MonitorEnter/MonitorExit functions which already handle the locking on the c++ side. There are pitfalls when using these at the same time as conventional locks on the java side, so please read here before using. I will be trying this out, and I expect that MonitorEnter/MonitorExit will be the answer and I recommend @Radiodef make an answer out of the comment.

Closing

How could I properly synchronize this? Should pthread_mutex_(un)lock work? If not, what can I use to synchronize between the C++ thread and the Java thread?

No JNI-specific C++ code is provided here since the JNI bridge is working and I can pass data back and forth. The question is specifically about proper synchronization between c++/java threads that are otherwise correctly communicating.

As mentioned before, I would prefer to avoid the polling scheme, but that might end up being another question. The legacy c++ code displays its part of the user interface in X/motif, and if I recall correctly the c++ thread above happens to be the event thread for display. The java thread will end up being the java event dispatch thread once the java user interface for this class is plugged in, though for now the java thread is an automated test thread; either way, it's a separate java thread.

The C++ thread is attached to the JVM. In fact, that is the C++ thread that created the JVM, so it should be attached by default.

I have been successful with plugging in other Java user interface elements into this program, but this is the first time C++ has needed non-atomic data from Java which needed to be synchronized. Is there a generally accepted correct way to do this?

答:
If both threads are attached to the JVM, then you can access the JNI's synchronization via JNIEnv's MonitorEnter(jobject) and MonitorExit(jobject) functions. Just as it sounds, MonitorEnter aquires a lock on the provided jobject, and MonitorExit releases the lock on the provided jobject.

NOTE: There are some pitfalls to be aware of! Notice the second to last paragraph of MonitorEnter's description and the last paragraph of MonitorExit's description about mixing and matching MonitorEnter/MonitorExit with other similar mechanisms which you might otherwise think are compatible.

See here

MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred
  to by obj. Enters the monitor associated with the object referred to
  by obj. The obj reference must not be NULL.  Each Java object has a
  monitor associated with it. If the current thread already owns the
  monitor associated with obj, it increments a counter in the monitor
  indicating the number of times this thread has entered the monitor. If
  the monitor associated with obj is not owned by any thread, the
  current thread becomes the owner of the monitor, setting the entry
  count of this monitor to 1. If another thread already owns the monitor
  associated with obj, the current thread waits until the monitor is
  released, then tries again to gain ownership.

A monitor entered through a MonitorEnter JNI function call cannot be
  exited using the monitorexit Java virtual machine instruction or a
  synchronized method return. A MonitorEnter JNI function call and a
  monitorenter Java virtual machine instruction may race to enter the
  monitor associated with the same object.

To avoid deadlocks, a monitor entered through a MonitorEnter JNI
  function call must be exited using the MonitorExit JNI call, unless
  the DetachCurrentThread call is used to implicitly release JNI
  monitors.

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

and

MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with
  the underlying Java object referred to by obj. The thread decrements
  the counter indicating the number of times it has entered this
  monitor. If the value of the counter becomes zero, the current thread
  releases the monitor.

Native code must not use MonitorExit to exit a monitor entered through
  a synchronized method or a monitorenter Java virtual machine
  instruction.

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the
  monitor.

So the C++ code in the question which attempted to use pthreads should be changed as following (code assumes the JNIEnv* pointer was acquired somehow beforehand in typical JNI fashion):

```<code>class objectA
{
    jobject dataMutex;
    ... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
    // You will need to aquire jniEnv pointer somehow just as usual for JNI
    jniEnv->MonitorEnter(dataMutex);

    ... // all the poll stuff from before

    jniEnv->MonitorExit(dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    // You will need to aquire jniEnv pointer somehow just as usual for JNI
    jniEnv->MonitorEnter(dataMutex);

    ... // all the supplyData stuff from before

    jniEnv->MonitorExit(dataMutex);
}
</code>```

Kudos to @Radiodef who provided the answer. Unfortunately it was as a comment. I waited until afternoon next day to allow time for Radiodef to make it an answer, so now I'm doing it. Thank you Radiodef for providing the nudge I needed to fix this.

Body:
Question Brief

I am using C++ and Java in one process via JNI. For the use case in question, both a C++ thread and a Java thread are accessing the same data, they are doing so on the C++ side, and I want to properly synchronize the access.

So far, almost all of my JNI thread synchronization has been on the Java side where the answer is obvious: use the provided Java concurrency package and the built-in concurrency language features. Unfortunately, the answer is not so obvious on the C++ side.

What I've Tried so far Brief

I tried using a pthreads mutex thinking that it might work even though I'm not using pthreads to create threads, but that occasionally gets stuck when trying to lock - I'll show an example of that farther below.

Question Details

In my current, specific usage, c++ is polling for changes provided by Java on a 1 second timer (not what I'd like, but I'm not sure how I would make it event-driven given the nature of the legacy c++ code). The Java thread provides data by calling a native function and c++ copies the data into a c++ structure.

This is the type of situation in code (happens on 2 threads, Thread1 and Thread2):

Code Example

Note quite an SSCCE, as it's missing definitions for TheData and TheDataWrapper, but it doesn't really matter what they contain. Assume they merely contain a couple of public ints if that helps your thought process (though, in my case, it's actually multiple arrays of int and arrays of float).

C++:

class objectA
{
    void poll();
    void supplyData(JNIEnv* jni, jobject jthis, jobject data);
    TheDataWrapper cpp_data;
    bool isUpdated;

    void doStuff(TheDataWrapper* data);
};

// poll() happens on a c++ thread we will call Thread1
void objectA :: poll()
{
    // Here, both isUpdated and cpp_data need synchronization

    if(isUpdated)
    {
        do_stuff(&cpp_data);
        isUpdated = false;
    }
}

// supplyData happens on the Thread2, called as a native function from a java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    // some operation happens that copies the java data into a c++ equivalent
    // in my specific case this happens to be copying ints/floats from java arrays to c++ arrays
    // this needs to be synchronized
    cpp_data.copyFrom(data);
    isUpdated = true;
}

Java:

class ObjectB
{
    // f() happens on a Java thread which we will call Thread2
    public void f()
    {
        // for the general case it doesn't really matter what the data is
        TheData data = TheData.prepareData();
        supplyData(data);
    }

    public native void supplyData(TheData data);
}

What I've Tried so far Details

When I tried pthread's locking as below, sometimes execution gets stuck in pthread_mutex_lock. There should not be a deadlock in this situation, but just to test further I ran a scenario where supplyData was not getting called at all (no data was being supplied), so no deadlock should have been possible, yet the first call to poll will occasionally hang anyway. Perhaps using a pthreads mutex is not a good idea in this situation? Or perhaps I did something stupid and keep overlooking it.

So far, I tried using pthreads as below:

Code Example

C++:

class objectA
{
    pthread_mutex_t dataMutex;
    ... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
    pthread_mutex_lock(&dataMutex);

    ... // all the poll stuff from before

    pthread_mutex_unlock(&dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    pthread_mutex_lock(&dataMutex);

    ... // all the supplyData stuff from before

    pthread_mutex_unlock(&dataMutex);
}

Another option I thought about but have not done

I also considered using JNI to call back into java to request a lock using java's concurrency control. That should work, as either thread should block on the java side as needed. However, since accessing java from c++ is overly verbose, I was hoping to avoid going through that headache. I probably could make a c++ class which encapsulates JNI calls into java to request a java lock; that would simplify c++ code, though I wonder about the overhead of crossing back and forth over JNI just for thread locks.

It seems this is not necessary, per the comment by @Radiodef. It appears JNI includes MonitorEnter/MonitorExit functions which already handle the locking on the c++ side. There are pitfalls when using these at the same time as conventional locks on the java side, so please read here before using. I will be trying this out, and I expect that MonitorEnter/MonitorExit will be the answer and I recommend @Radiodef make an answer out of the comment.

Closing

How could I properly synchronize this? Should pthread_mutex_(un)lock work? If not, what can I use to synchronize between the C++ thread and the Java thread?

No JNI-specific C++ code is provided here since the JNI bridge is working and I can pass data back and forth. The question is specifically about proper synchronization between c++/java threads that are otherwise correctly communicating.

As mentioned before, I would prefer to avoid the polling scheme, but that might end up being another question. The legacy c++ code displays its part of the user interface in X/motif, and if I recall correctly the c++ thread above happens to be the event thread for display. The java thread will end up being the java event dispatch thread once the java user interface for this class is plugged in, though for now the java thread is an automated test thread; either way, it's a separate java thread.

The C++ thread is attached to the JVM. In fact, that is the C++ thread that created the JVM, so it should be attached by default.

I have been successful with plugging in other Java user interface elements into this program, but this is the first time C++ has needed non-atomic data from Java which needed to be synchronized. Is there a generally accepted correct way to do this?

Body:
If both threads are attached to the JVM, then you can access the JNI's synchronization via JNIEnv's MonitorEnter(jobject) and MonitorExit(jobject) functions. Just as it sounds, MonitorEnter aquires a lock on the provided jobject, and MonitorExit releases the lock on the provided jobject.

NOTE: There are some pitfalls to be aware of! Notice the second to last paragraph of MonitorEnter's description and the last paragraph of MonitorExit's description about mixing and matching MonitorEnter/MonitorExit with other similar mechanisms which you might otherwise think are compatible.

See here

MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred
  to by obj. Enters the monitor associated with the object referred to
  by obj. The obj reference must not be NULL.  Each Java object has a
  monitor associated with it. If the current thread already owns the
  monitor associated with obj, it increments a counter in the monitor
  indicating the number of times this thread has entered the monitor. If
  the monitor associated with obj is not owned by any thread, the
  current thread becomes the owner of the monitor, setting the entry
  count of this monitor to 1. If another thread already owns the monitor
  associated with obj, the current thread waits until the monitor is
  released, then tries again to gain ownership.

A monitor entered through a MonitorEnter JNI function call cannot be
  exited using the monitorexit Java virtual machine instruction or a
  synchronized method return. A MonitorEnter JNI function call and a
  monitorenter Java virtual machine instruction may race to enter the
  monitor associated with the same object.

To avoid deadlocks, a monitor entered through a MonitorEnter JNI
  function call must be exited using the MonitorExit JNI call, unless
  the DetachCurrentThread call is used to implicitly release JNI
  monitors.

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

and

MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with
  the underlying Java object referred to by obj. The thread decrements
  the counter indicating the number of times it has entered this
  monitor. If the value of the counter becomes zero, the current thread
  releases the monitor.

Native code must not use MonitorExit to exit a monitor entered through
  a synchronized method or a monitorenter Java virtual machine
  instruction.

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the
  monitor.

So the C++ code in the question which attempted to use pthreads should be changed as following (code assumes the JNIEnv* pointer was acquired somehow beforehand in typical JNI fashion):

class objectA
{
    jobject dataMutex;
    ... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
    // You will need to aquire jniEnv pointer somehow just as usual for JNI
    jniEnv->MonitorEnter(dataMutex);

    ... // all the poll stuff from before

    jniEnv->MonitorExit(dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
    // You will need to aquire jniEnv pointer somehow just as usual for JNI
    jniEnv->MonitorEnter(dataMutex);

    ... // all the supplyData stuff from before

    jniEnv->MonitorExit(dataMutex);
}

Kudos to @Radiodef who provided the answer. Unfortunately it was as a comment. I waited until afternoon next day to allow time for Radiodef to make it an answer, so now I'm doing it. Thank you Radiodef for providing the nudge I needed to fix this.


问:
One liner for extend loop python
I have the following code lines:

```<code>records = []

for future in futures:
  records.extends(future.result())
</code>```

each future returns a list.

How can I write the above code but in one liner?

```<code>records = [future.result() for future in futures]
</code>```

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list

答:
I think this is what you are looking for</p>

```<code>import functools
records = functools.reduce(lambda res, future: res + future.result()), futures, [])
</code>```

Title: One liner for extend loop python

Body:
I have the following code lines:

records = []

for future in futures:
  records.extends(future.result())

each future returns a list.

How can I write the above code but in one liner?

records = [future.result() for future in futures]

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list

Body:
I think this is what you are looking for

import functools
records = functools.reduce(lambda res, future: res + future.result()), futures, [])


问:
Elegantly handle different parameter types
I have a function that, in the simplest of cases, operates on an iterable of items.

```<code>def foo(items):
    for item in items:
        # do stuff
</code>```

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

```<code>def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above
</code>```

I can merge these two cases like this:

```<code>def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff
</code>```

This works just fine. Now I get a third use case that looks like this:

```<code>def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again
</code>```

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

答:
As it stands, you should probably use at least two methods here,the third just calling the first with the itertools.chain.from_iterable result. You could also potentially have a use for *args; it depends on your precise case (providing a real example is helpful). You can also use a simple helper function to return the right type of iterator.

Perhaps this might work out:

```<code>def _foo_iter(obj):
    try:
        return obj.iteritems()
    except AttributeError:
        return obj

def foo(*objs):
    for obj in objs:
        for item in _foo_iter(obj):
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a function that, in the simplest of cases, operates on an iterable of items.

def foo(items):
    for item in items:
        # do stuff

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above

I can merge these two cases like this:

def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff

This works just fine. Now I get a third use case that looks like this:

def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

Body:
As it stands, you should probably use at least two methods here,the third just calling the first with the itertools.chain.from_iterable result. You could also potentially have a use for *args; it depends on your precise case (providing a real example is helpful). You can also use a simple helper function to return the right type of iterator.

Perhaps this might work out:

def _foo_iter(obj):
    try:
        return obj.iteritems()
    except AttributeError:
        return obj

def foo(*objs):
    for obj in objs:
        for item in _foo_iter(obj):


问:
Get data from md-dialog on Angular4
I am implementing an md-dialag from Material Design on my Angular 4 application. I have currently achieved to pass data into the modal, but have not been successful to retrieve any data entered by the user on the dialog.

This is how I open a dialog:

```<code>ShowAddStop() {
    this.general = {fc: this.locationCtrl, fl: this.filteredLocations, selectedNewStop:this.selectedNewStop};
    let dialogRef = this.dialog.open(DialogAddStop,{data:this.general});
    dialogRef.afterClosed().subscribe(result => {
        console.log(result);
    });
}
</code>```

But for instance, on the dialog I have an input field which I want the user to fill:

```<code><input [(ngModel)]="ShortName">
</code>```

Where Shortname is a variable on the class from where I called the dialog, it won't change that variable, I think it creates its own scope and that's why it isn't using my class instance variables.

Is there something basic I'm missing on retrieving data back from the dialog?

答:
First, acquire a MdDialogRef<DialogAddStop> reference and a MD_DIALOG_DATA token in the dialog constructor:

constructor(
  @Inject(MD_DIALOG_DATA) private dialogData: any,
  private dialogRef: MdDialogRef<DialogAddStop>
) {}
```

<p>See also Using MdDialogConfig data on Angular 2 for some explanations regarding <code>MD_DIALOG_DATA</code>.</p>

<p><strong>Create</strong> a <code>shortName</code> variable inside the dialog class:</p>

<pre class="lang-typescript prettyprint-override"><code>public shortName: string
</code>```

Set initial value of shortName to the one provided by the parent component:

public ngOnInit(): void {
  this.shortName = this.dialogData['shortName']
}
```

<p><strong>Create</strong> a “saving” handler:</p>

<pre class="lang-typescript prettyprint-override"><code>public onSave() {
  this.dialogRef.close(this.shortName)
}
</code>```

Attach that handler to the Save button:

<button (click)="onSave()" md-button>Save</button>
```

Title: Get data from md-dialog on Angular4

Body:
I am implementing an md-dialag from Material Design on my Angular 4 application. I have currently achieved to pass data into the modal, but have not been successful to retrieve any data entered by the user on the dialog.

This is how I open a dialog:

ShowAddStop() {
    this.general = {fc: this.locationCtrl, fl: this.filteredLocations, selectedNewStop:this.selectedNewStop};
    let dialogRef = this.dialog.open(DialogAddStop,{data:this.general});
    dialogRef.afterClosed().subscribe(result => {
        console.log(result);
    });
}

But for instance, on the dialog I have an input field which I want the user to fill:

<input [(ngModel)]="ShortName">

Where Shortname is a variable on the class from where I called the dialog, it won't change that variable, I think it creates its own scope and that's why it isn't using my class instance variables.

Is there something basic I'm missing on retrieving data back from the dialog?

Body:
First, acquire a MdDialogRef<DialogAddStop> reference and a MD_DIALOG_DATA token in the dialog constructor:

constructor(
  @Inject(MD_DIALOG_DATA) private dialogData: any,
  private dialogRef: MdDialogRef<DialogAddStop>
) {}

See also Using MdDialogConfig data on Angular 2 for some explanations regarding MD_DIALOG_DATA.

Create a shortName variable inside the dialog class:

public shortName: string

Set initial value of shortName to the one provided by the parent component:

public ngOnInit(): void {
  this.shortName = this.dialogData['shortName']
}

Create a “saving” handler:

public onSave() {
  this.dialogRef.close(this.shortName)
}

Attach that handler to the Save button:

<button (click)="onSave()" md-button>Save</button>


问:
Spark Error Running "stats()": could not find implicit value for parameter num: Numeric[Double]
I'm learning spark/scala after just writing some MapReduce jobs.

I wrote some java beans to help me parse a file in HDFS and I want to use that to help speed up my progress in spark.

I've had success loading my file and creating an array of my java bean objects:

```<code>val input = sc.textFile("hdfs://host:port/user/test/path/out")
import my.package.Record
val clust_recs = clv_input.map(line => new my.package.Record(line))
clust_recs.map(rec => rec.getPremium()).stats()
</code>```

But the last line creates this error:

<console>:46: error: could not find implicit value for parameter num: Numeric[Double]

I've tested that the values in this field are all valid, so I am pretty sure I don't have any null values that could be causing this error.

Here is an example of values:

```<code>val dblArray = clust_recs.map(rec => rec.getPremium()).filter(!isNaN(_))
dblArray.take(10)
</code>```

OUTPUT:

```<code>res82: Array[Double] = Array(1250.6, 433.72, 567.07, 219.24, 310.32, 2173.48, 195.0, 697.94, 711.46, 42.718050000000005)
</code>```

I'm at a loss to how to resolve this error and wondering if I should just abandon the concept of using a JavaBean object that I've already created.

答:
Thanks for getting me in the right direction Jacek, your answer got me searching more about how to convert the java.lang.Double to scala.Double in the map function.

As a new user of scala, I'm struggling to get a handle on the differences with Java, especially implicit conversions.

I found this post very helpful: http://www.scala-archive.org/scala-Double-td1939353.html

and ultimately changed the code to this:

```<code>clust_recs.map(rec => rec.getPremium().doubleValue()).stats()
</code>```

OUTPUT:

```<code>res28: org.apache.spark.util.StatCounter = (count: 1000000, mean: 170.636, stdev: 28.13, max: 2180.000000, min: 0.000000)
</code>```

Body:
I'm learning spark/scala after just writing some MapReduce jobs.

I wrote some java beans to help me parse a file in HDFS and I want to use that to help speed up my progress in spark.

I've had success loading my file and creating an array of my java bean objects:

val input = sc.textFile("hdfs://host:port/user/test/path/out")
import my.package.Record
val clust_recs = clv_input.map(line => new my.package.Record(line))
clust_recs.map(rec => rec.getPremium()).stats()

But the last line creates this error:

<console>:46: error: could not find implicit value for parameter num: Numeric[Double]

I've tested that the values in this field are all valid, so I am pretty sure I don't have any null values that could be causing this error.

Here is an example of values:

val dblArray = clust_recs.map(rec => rec.getPremium()).filter(!isNaN(_))
dblArray.take(10)

OUTPUT:

res82: Array[Double] = Array(1250.6, 433.72, 567.07, 219.24, 310.32, 2173.48, 195.0, 697.94, 711.46, 42.718050000000005)

I'm at a loss to how to resolve this error and wondering if I should just abandon the concept of using a JavaBean object that I've already created.

Body:
Thanks for getting me in the right direction Jacek, your answer got me searching more about how to convert the java.lang.Double to scala.Double in the map function.

As a new user of scala, I'm struggling to get a handle on the differences with Java, especially implicit conversions.

I found this post very helpful: http://www.scala-archive.org/scala-Double-td1939353.html

and ultimately changed the code to this:

clust_recs.map(rec => rec.getPremium().doubleValue()).stats()

OUTPUT:

res28: org.apache.spark.util.StatCounter = (count: 1000000, mean: 170.636, stdev: 28.13, max: 2180.000000, min: 0.000000)


问:
Magento 2 REST API call to get logged in customer ID
I want to make a REST call from outside of Magento (but on the same domain) to get the currently logged in customer's ID. I don't want them to have to login again or provide a password, I just need to get their ID so I can redirect them somewhere based on their ID.

I see this endpoint in the URL:

```<code>http://.../rest/V1/customers/me
</code>```

but when I cURL that URL I get:

```<code>Consumer is not authorized to access %resources
</code>```

Do I still need to get a token to access this even though it is anonymous and based on the session? If so, what does this PHP call look like?

I just need to prove they are logged in and grab their ID.

答:
That should work, considering you are sending the PHPSESSID together with you request. As you said you're using cURL, that is probably not the case.

You could easily achieve that by making an ajax call to the API, something similar to the following:

```<code>jQuery.ajax({
    url: 'http://dev.magento2.com/rest/V1/customers/me',
    type: 'get',
    error: function() {
        alert('User not Logged In');
    },
    success: function() {
        alert('User logged in');
    }
});
</code>```

If you need to keep the requests on the server side, then you should add PHPSESSID to your requests:

```<code>$ch = curl_init('http://dev.magento2.com/rest/V1/customers/me');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

$json = json_decode($result);

if (isset($json->id)) {
    echo 'User logged in';
} else {
    echo 'User not logged in';
}
</code>```

(source for the cURL request: https://community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/m-p/62092#M1813)

Body:
I want to make a REST call from outside of Magento (but on the same domain) to get the currently logged in customer's ID. I don't want them to have to login again or provide a password, I just need to get their ID so I can redirect them somewhere based on their ID.

I see this endpoint in the URL:

http://.../rest/V1/customers/me

but when I cURL that URL I get:

Consumer is not authorized to access %resources

Do I still need to get a token to access this even though it is anonymous and based on the session? If so, what does this PHP call look like?

I just need to prove they are logged in and grab their ID.

Body:
That should work, considering you are sending the PHPSESSID together with you request. As you said you're using cURL, that is probably not the case.

You could easily achieve that by making an ajax call to the API, something similar to the following:

jQuery.ajax({
    url: 'http://dev.magento2.com/rest/V1/customers/me',
    type: 'get',
    error: function() {
        alert('User not Logged In');
    },
    success: function() {
        alert('User logged in');
    }
});

If you need to keep the requests on the server side, then you should add PHPSESSID to your requests:

$ch = curl_init('http://dev.magento2.com/rest/V1/customers/me');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

$json = json_decode($result);

if (isset($json->id)) {
    echo 'User logged in';
} else {
    echo 'User not logged in';
}

(source for the cURL request: https://community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/m-p/62092#M1813)


问:
remove kernel on jupyter notebook
How can I remove a kernel from jupyter notebook?

I have R kernel on my jupyter notebook. Recently kernel always dies right after I open a new notebook.

答:
If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

```<code>~/.local/share/jupyter/kernels/
</code>```

ContentLicense: CC BY-SA 4.0

Title: remove kernel on jupyter notebook

Body:
If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

~/.local/share/jupyter/kernels/


问:
Import data from Excel using SSIS without knowing sheet name
I have a spreadsheet that is updated by another server (out of my control) and I need to automate bringing that data into SQL 2005.  The data is always the first page of the spreadsheet.  However, the name of that sheet changes depending on the number of rows.

Is there a way to run an SSIS job that pulls in data from Excel without knowing the sheetname beforehand?  It seems to rely on the sheet name as the data source, but I'm looking to tell it "sheet number 1" or something similar.

答:
I have had this same issue myself in the past and was unable to find a solution to having an Excel file be read in which has its sheet name change from file to file.

My guess, which I was unable to get to work, would be to use expressions in the properties of the data connection.  You would need to somehow read the sheet name into a variable, then use that variable's result in the sheet name for the data connection.

Best of luck to you, and sorry I couldn't be of more help.


问:
HttpMediaTypeNotAcceptableException: Could not find acceptable representation in exceptionhandler
I have the following image download method in my controller (Spring 4.1):

```<code>@RequestMapping(value = "/get/image/{id}/{fileName}", method=RequestMethod.GET)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id, @PathVariable("fileName") String fileName) {
    setContentType(fileName); //sets contenttype based on extention of file
    return getImage(id, fileName);
}
</code>```

The following ControllerAdvice method should handle a non-existing file and return a json error response:

```<code>@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Map<String, String> handleResourceNotFoundException(ResourceNotFoundException e) {
    Map<String, String> errorMap = new HashMap<String, String>();
    errorMap.put("error", e.getMessage());
    return errorMap;
}
</code>```

My JUnit test works flawless

(EDIT this is because of extention .bla : this also works on appserver):

```<code>@Test
public void testResourceNotFound() throws Exception {
    String fileName = "bla.bla";
      mvc.perform(MockMvcRequestBuilders.get("/get/image/bla/" + fileName)
            .with(httpBasic("test", "test")))
            .andDo(print())
            .andExpect(jsonPath("$error").value(Matchers.startsWith("Resource not found")))
            .andExpect(status().is(404));
}
</code>```

and gives the following output:

```<code>MockHttpServletResponse:
          Status = 404
   Error message = null
         Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Content-Type=[application/json]}
    Content type = application/json
            Body = {"error":"Resource not found: bla/bla.bla"}
   Forwarded URL = null
  Redirected URL = null
         Cookies = []
</code>```

However on my appserver i get the following error message when trying to donwload non existing image:

(EDIT this is because of extention .jpg : this also fails on JUnit test with .jpg extention):

ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver  - Failed to invoke @ExceptionHandler method: public java.util.Map<java.lang.String, java.lang.String> nl.krocket.ocr.web.controller.ExceptionController.handleResourceNotFoundException(nl.krocket.ocr.web.backing.ResourceNotFoundException)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

I have configured messageconverters in my mvc configuration as follows:

```<code>@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(mappingJackson2HttpMessageConverter());
    converters.add(byteArrayHttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //objectMapper.registerModule(new JSR310Module());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    converter.setSupportedMediaTypes(getJsonMediaTypes());
    return converter;
}

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getImageMediaTypes());
    return arrayHttpMessageConverter;
}
</code>```

What am i missing? And why is the JUnit test working?

答:
Pay attention to your HTTP Accept header.
For example, if your controller produces "application/octet-stream" (in response), your Accept header should NOT be "application/json" (in request):</p>

```<code>@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void download(HttpServletResponse response) {}
</code>```

Body:
I have the following image download method in my controller (Spring 4.1):

@RequestMapping(value = "/get/image/{id}/{fileName}", method=RequestMethod.GET)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id, @PathVariable("fileName") String fileName) {
    setContentType(fileName); //sets contenttype based on extention of file
    return getImage(id, fileName);
}

The following ControllerAdvice method should handle a non-existing file and return a json error response:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Map<String, String> handleResourceNotFoundException(ResourceNotFoundException e) {
    Map<String, String> errorMap = new HashMap<String, String>();
    errorMap.put("error", e.getMessage());
    return errorMap;
}

My JUnit test works flawless

(EDIT this is because of extention .bla : this also works on appserver):

@Test
public void testResourceNotFound() throws Exception {
    String fileName = "bla.bla";
      mvc.perform(MockMvcRequestBuilders.get("/get/image/bla/" + fileName)
            .with(httpBasic("test", "test")))
            .andDo(print())
            .andExpect(jsonPath("$error").value(Matchers.startsWith("Resource not found")))
            .andExpect(status().is(404));
}

and gives the following output:

MockHttpServletResponse:
          Status = 404
   Error message = null
         Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Content-Type=[application/json]}
    Content type = application/json
            Body = {"error":"Resource not found: bla/bla.bla"}
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

However on my appserver i get the following error message when trying to donwload non existing image:

(EDIT this is because of extention .jpg : this also fails on JUnit test with .jpg extention):

ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver  - Failed to invoke @ExceptionHandler method: public java.util.Map<java.lang.String, java.lang.String> nl.krocket.ocr.web.controller.ExceptionController.handleResourceNotFoundException(nl.krocket.ocr.web.backing.ResourceNotFoundException)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

I have configured messageconverters in my mvc configuration as follows:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(mappingJackson2HttpMessageConverter());
    converters.add(byteArrayHttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //objectMapper.registerModule(new JSR310Module());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    converter.setSupportedMediaTypes(getJsonMediaTypes());
    return converter;
}

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getImageMediaTypes());
    return arrayHttpMessageConverter;
}

What am i missing? And why is the JUnit test working?

Body:
Pay attention to your HTTP Accept header.
For example, if your controller produces "application/octet-stream" (in response), your Accept header should NOT be "application/json" (in request):

@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void download(HttpServletResponse response) {}


问:
Move dynamic text from text string in MySQL to another location in the string
I have a few thousand MySQL records that contain strings of text saved in a MySQL database that contain unique values after a URL variable called "additional_development" with data like 'Chestnut%20Estates' in each record:

```<code><a class="button" href="http://www.websitedomain.com/search-results/?fullinfo=&Location=all&additional_development=Chestnut%20Estates&additional_postal_code=
</code>```

They dynamic value is always in the &additional_development= variable.  If there is no value here it simply looks like this additional_development=&additional_postal_code=

I need to remove the dynamic text from this location to the ?fullinfo= variable without knowing the contents (Chestnut Estates) to move, only the location of where this value resides in the URL.

Desired Effect:

```<code><a class="button" href="http://www.websitedomain.com/?fullinfo=Chestnut%20Estates&Location=all&additional_development=&additional_postal_code=
</code>```

Using this question, I found I could not do this with regex. So I've attempted different degrees of Update commands with still no effect.

Any suggestions on the best way to achieve the desired result in a MySQL query?

Table name is wp_posts and column name is post_content.

答:
Is additional_development the only dynamic part?  If so this is a simple string replace:

```<code>UPDATE table_name SET column_name=replace( column_name, '?fullinfo=&Location=all&additional_development=', '?fullinfo=' )
</code>```

Otherwise it looks like you will have to implement this in another way, either by implementing a regular expression replace yourself in MySQL (there are plenty of examples around), or doing it in your programming language of choice via select, regexp in language, update.  It is slower to do it that way of course, but you don't have much choice (other than switching databases).

Sorry

Body:
I have a few thousand MySQL records that contain strings of text saved in a MySQL database that contain unique values after a URL variable called "additional_development" with data like 'Chestnut%20Estates' in each record:

<a class="button" href="http://www.websitedomain.com/search-results/?fullinfo=&Location=all&additional_development=Chestnut%20Estates&additional_postal_code=

They dynamic value is always in the &additional_development= variable.  If there is no value here it simply looks like this additional_development=&additional_postal_code=

I need to remove the dynamic text from this location to the ?fullinfo= variable without knowing the contents (Chestnut Estates) to move, only the location of where this value resides in the URL.

Desired Effect:

<a class="button" href="http://www.websitedomain.com/?fullinfo=Chestnut%20Estates&Location=all&additional_development=&additional_postal_code=

Using this question, I found I could not do this with regex. So I've attempted different degrees of Update commands with still no effect.

Any suggestions on the best way to achieve the desired result in a MySQL query?

Table name is wp_posts and column name is post_content.

Body:
Is additional_development the only dynamic part?  If so this is a simple string replace:

UPDATE table_name SET column_name=replace( column_name, '?fullinfo=&Location=all&additional_development=', '?fullinfo=' )

Otherwise it looks like you will have to implement this in another way, either by implementing a regular expression replace yourself in MySQL (there are plenty of examples around), or doing it in your programming language of choice via select, regexp in language, update.  It is slower to do it that way of course, but you don't have much choice (other than switching databases).

Sorry


问:
Utilizing browser back/forward buttons in a vue.js app
I have an app that has a bunch of dropdown components that alter state.  .  The state of the dropdowns control a main datatable that has info based around the params.  Cool.

I want to also alter the URL so users can share urls with their coworkers and simply have the datatable show up without choosing dropdown parameters.

Example: http://localhost:8080/?region=372&pc=341&pc=375 or http://localhost:8080/?region=372&pc=341&vendor=123456

Right now I've got this working by manually watching the dropdown parameters selected (via watch) and building a url and using this.$router.push to update browser history when things change.  I have a feeling this isn't totally correct, but it's the only reliable way I've been able to make the url update consistently.

The main issue is that when I hit the browser's back/forward buttons, the components do not update their state based on the url.  The application remains in it's current state if I hit back/forward.  How do I properly go about this?

答:
It looks like you're effectively trying to bind the state of your dropdown to your URL query. VueRouter, unfortunately, doesn't have a baked-in solution for this.

I'm not sure how your data is structured, so let's assume you have an object dropdownParams containing the relevant parameters:

```<code>dropdownParams: {
  region: 372,
  pc: 341,
  vendor: 123456,
}
</code>```

You need to set a watcher on dropdownParams to update the query in the $route when those are updated. Use $router.replace instead of $router.push so that the history doesn't change:

```<code>watch: {
  dropdownParams(params) {
    // format the data however you want this is an example with lodash
    let query = _.pickBy(params, p => !_.isEmpty(p));
    this.$router.replace({ query: query });
  }
}
</code>```

Then, in the mounted hook, you can set the dropdownParams object based on any relevant $route.query parameters, if they already exist:

```<code>mounted() {
  let keys = _.keys(this.dropdownParams);
  _.assign(this.dropdownParams, _.pick(this.$route.query, keys));
}
</code>```

Now, when the user changes the dropdown parameters, those changes will be reflected in the URL. And, if the user loads the component with URL query parameters already present, the component will set those values to the dropdown.

Body:
It looks like you're effectively trying to bind the state of your dropdown to your URL query. VueRouter, unfortunately, doesn't have a baked-in solution for this.

I'm not sure how your data is structured, so let's assume you have an object dropdownParams containing the relevant parameters:

dropdownParams: {
  region: 372,
  pc: 341,
  vendor: 123456,
}

You need to set a watcher on dropdownParams to update the query in the $route when those are updated. Use $router.replace instead of $router.push so that the history doesn't change:

watch: {
  dropdownParams(params) {
    // format the data however you want this is an example with lodash
    let query = _.pickBy(params, p => !_.isEmpty(p));
    this.$router.replace({ query: query });
  }
}

Then, in the mounted hook, you can set the dropdownParams object based on any relevant $route.query parameters, if they already exist:

mounted() {
  let keys = _.keys(this.dropdownParams);
  _.assign(this.dropdownParams, _.pick(this.$route.query, keys));
}

Now, when the user changes the dropdown parameters, those changes will be reflected in the URL. And, if the user loads the component with URL query parameters already present, the component will set those values to the dropdown.


问:
PHP 'addslashes' not behaving as expected
This has been driving be crazy, but I can't seem to find an answer. We run a technical knowledge base that will sometimes include Windows samba paths for mapping to network drives.

For example: \\servername\sharename

When we include paths that have two backslashes followed by each other, they are not escaped properly when running 'addslashes'. My expected results would be "\\\\servername\\sharename", however it returns "\\servername\\sharename". Obviously, when running 'stripslashes' later on, the double backslash prefix is only a single slash. I've also tried using a str_replace("\\", "\", $variable); however it returns "\servername\sharename" when I would expect "\\servername\sharename".

So with addslashes, it ignores the first set of double-backslashes and with str_replace it changes the double-backslashes into a single, encoded backslash.

We need to run addslashes and stripslashes for database insertion; using pg_escape_string won't work in our specific case.

This is running on PHP 5.3.1 on Apache.

EDIT: Example Code

$variable = 'In the box labeled Folder type: \\servername\sharename';

echo addslashes($variable);

This returns: In the box labeled Folder type: \\servername\\sharename

EDIT: Example Code #2

$variable = 'In the box labeled Folder type: \\servername\sharename';

echo str_replace('\\', '\', $variable);

This returns: In the box labeled Folder type: \servername\sharename

I'd also like to state that using a single quotes or double-quotes does not give me different results (as you would expect). Using either or both give me the same exact results.

Does anyone have any suggestions on what I can possibly do?

答:
Ran a test on the problem you described, and the only way I could get the behavior you desired was to couple a conditional with a regex and anticipate the double slashes at the start.

```<code>$str = '\\servername\sharename';
    if(substr($str,0,1) == '\\'){
    //String starts with double backslashes, let's append an escape one.
    //Exclaimation used for demonstration purposes.
    $str = '\\'.$str;
    echo addslashes(preg_replace('#\\\\\\\\#', '!',$str ));

    }
</code>```

This outputs:

```<code>!servername\\sharename
</code>```

While this may not be an outright answer, it does work and illustrates a difference in how the escape character is treated by these two constructs.  If used, the ! could easily be replaced with the desired characters using another regex.

Body:
Ran a test on the problem you described, and the only way I could get the behavior you desired was to couple a conditional with a regex and anticipate the double slashes at the start.

$str = '\\servername\sharename';
    if(substr($str,0,1) == '\\'){
    //String starts with double backslashes, let's append an escape one.
    //Exclaimation used for demonstration purposes.
    $str = '\\'.$str;
    echo addslashes(preg_replace('#\\\\\\\\#', '!',$str ));

    }

This outputs:

!servername\\sharename

While this may not be an outright answer, it does work and illustrates a difference in how the escape character is treated by these two constructs.  If used, the ! could easily be replaced with the desired characters using another regex.


问:
Cannot get OpenCV to compile because of undefined references?
The code is simple and is essentially straight from this tutorial. I am running Arch Linux and have the OpenCV library stored at /usr/include/. I have also checked to ensure that /usr/include is in my PATH.

```<code>#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>

using namespace cv;

int main(int argc, char** argv){
    Mat image;
    Mat grayImage;

    if(!argv[1]){
        std::cerr << "No image data!" << std::endl;
        return -1;
    }

    image = imread(argv[1], 1);
    cvtColor(image, grayImage, CV_BGR2GRAY);
    imwrite("Gray_Image.jpg", grayImage);

    namedWindow(argv[1], CV_WINDOW_AUTOSIZE);
    namedWindow("Gray Image", CV_WINDOW_AUTOSIZE);

    imshow(argv[1], image);
    imshow("Gray Image", grayImage);

    waitKey(0);
    return 0;
}
</code>```

The compiler process successfully finds and include these header files, but I still get undefined reference errors at compile-time. If you look into the header files I included they further include other files in /usr/include/opencv2. I have checked and such header files do exist.

Any ideas?

```<code>/tmp/ccudBcqD.o: In function `main':
test.cpp:(.text+0xc0): undefined reference to `cv::imread(std::string const&, int)'
test.cpp:(.text+0x11f): undefined reference to `cv::_OutputArray::_OutputArray(cv::Mat&)'
test.cpp:(.text+0x138): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x158): undefined reference to `cv::cvtColor(cv::_InputArray const&, cv::_OutputArray const&, int, int)'
test.cpp:(.text+0x180): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x1ca): undefined reference to `cv::imwrite(std::string const&, cv::_InputArray const&, std::vector<int, std::allocator<int> > const&)'
test.cpp:(.text+0x241): undefined reference to `cv::namedWindow(std::string const&, int)'
test.cpp:(.text+0x291): undefined reference to `cv::namedWindow(std::string const&, int)'
test.cpp:(.text+0x2bf): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x2ff): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
test.cpp:(.text+0x32d): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x361): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
test.cpp:(.text+0x383): undefined reference to `cv::waitKey(int)'
/tmp/ccudBcqD.o: In function `cv::Mat::~Mat()':
test.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x39): undefined reference to `cv::fastFree(void*)'
/tmp/ccudBcqD.o: In function `cv::Mat::operator=(cv::Mat const&)':
test.cpp:(.text._ZN2cv3MataSERKS0_[_ZN2cv3MataSERKS0_]+0x111): undefined reference to `cv::Mat::copySize(cv::Mat const&)'
/tmp/ccudBcqD.o: In function `cv::Mat::release()':
test.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x47): undefined reference to `cv::Mat::deallocate()'
collect2: error: ld returned 1 exit status
[Finished in 1.1s with exit code 1]
[shell_cmd: g++ "/home/branden/Desktop/OpenCV/test.cpp" -o "/home/branden/Desktop/OpenCV/test"]
[dir: /home/branden/Desktop/OpenCV]
[path: /usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/vendor_perl:/usr/bin/core_perl]
</code>```

答:
follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial

read the example from openCV

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(opencv_example_project)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
    # Add OpenCV headers location to your include paths
    include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})
</code>```

main.cpp

```<code>/**
 * @file LinearBlend.cpp
 * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

using namespace cv;

/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;

//![on_trackbar]
/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
static void on_trackbar( int, void* )
{
    alpha = (double) alpha_slider/alpha_slider_max ;

    beta = ( 1.0 - alpha );

    addWeighted( src1, alpha, src2, beta, 0.0, dst);

    imshow( "Linear Blend", dst );
}
//![on_trackbar]

/**
 * @function main
 * @brief Main function
 */
int main( void )
{
    //![load]
    /// Read images ( both have to be of the same size and type )
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    //![load]

    if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
    if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }

    /// Initialize values
    alpha_slider = 0;

    //![window]
    namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
    //![window]

    //![create_trackbar]
    char TrackbarName[50];
    sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
    createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
    //![create_trackbar]

    /// Show some stuff
    on_trackbar( alpha_slider, 0 );

    /// Wait until user press some key
    waitKey(0);
    return 0;
}
</code>```

Tested in linux mint 17

Body:
The code is simple and is essentially straight from this tutorial. I am running Arch Linux and have the OpenCV library stored at /usr/include/. I have also checked to ensure that /usr/include is in my PATH.

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>

using namespace cv;

int main(int argc, char** argv){
    Mat image;
    Mat grayImage;

    if(!argv[1]){
        std::cerr << "No image data!" << std::endl;
        return -1;
    }

    image = imread(argv[1], 1);
    cvtColor(image, grayImage, CV_BGR2GRAY);
    imwrite("Gray_Image.jpg", grayImage);

    namedWindow(argv[1], CV_WINDOW_AUTOSIZE);
    namedWindow("Gray Image", CV_WINDOW_AUTOSIZE);

    imshow(argv[1], image);
    imshow("Gray Image", grayImage);

    waitKey(0);
    return 0;
}

The compiler process successfully finds and include these header files, but I still get undefined reference errors at compile-time. If you look into the header files I included they further include other files in /usr/include/opencv2. I have checked and such header files do exist.

Any ideas?

/tmp/ccudBcqD.o: In function `main':
test.cpp:(.text+0xc0): undefined reference to `cv::imread(std::string const&, int)'
test.cpp:(.text+0x11f): undefined reference to `cv::_OutputArray::_OutputArray(cv::Mat&)'
test.cpp:(.text+0x138): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x158): undefined reference to `cv::cvtColor(cv::_InputArray const&, cv::_OutputArray const&, int, int)'
test.cpp:(.text+0x180): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x1ca): undefined reference to `cv::imwrite(std::string const&, cv::_InputArray const&, std::vector<int, std::allocator<int> > const&)'
test.cpp:(.text+0x241): undefined reference to `cv::namedWindow(std::string const&, int)'
test.cpp:(.text+0x291): undefined reference to `cv::namedWindow(std::string const&, int)'
test.cpp:(.text+0x2bf): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x2ff): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
test.cpp:(.text+0x32d): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test.cpp:(.text+0x361): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
test.cpp:(.text+0x383): undefined reference to `cv::waitKey(int)'
/tmp/ccudBcqD.o: In function `cv::Mat::~Mat()':
test.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x39): undefined reference to `cv::fastFree(void*)'
/tmp/ccudBcqD.o: In function `cv::Mat::operator=(cv::Mat const&)':
test.cpp:(.text._ZN2cv3MataSERKS0_[_ZN2cv3MataSERKS0_]+0x111): undefined reference to `cv::Mat::copySize(cv::Mat const&)'
/tmp/ccudBcqD.o: In function `cv::Mat::release()':
test.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x47): undefined reference to `cv::Mat::deallocate()'
collect2: error: ld returned 1 exit status
[Finished in 1.1s with exit code 1]
[shell_cmd: g++ "/home/branden/Desktop/OpenCV/test.cpp" -o "/home/branden/Desktop/OpenCV/test"]
[dir: /home/branden/Desktop/OpenCV]
[path: /usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/vendor_perl:/usr/bin/core_perl]

Body:
follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial

read the example from openCV

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(opencv_example_project)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
    # Add OpenCV headers location to your include paths
    include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})

main.cpp

/**
 * @file LinearBlend.cpp
 * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

using namespace cv;

/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;

//![on_trackbar]
/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
static void on_trackbar( int, void* )
{
    alpha = (double) alpha_slider/alpha_slider_max ;

    beta = ( 1.0 - alpha );

    addWeighted( src1, alpha, src2, beta, 0.0, dst);

    imshow( "Linear Blend", dst );
}
//![on_trackbar]

/**
 * @function main
 * @brief Main function
 */
int main( void )
{
    //![load]
    /// Read images ( both have to be of the same size and type )
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    //![load]

    if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
    if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }

    /// Initialize values
    alpha_slider = 0;

    //![window]
    namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
    //![window]

    //![create_trackbar]
    char TrackbarName[50];
    sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
    createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
    //![create_trackbar]

    /// Show some stuff
    on_trackbar( alpha_slider, 0 );

    /// Wait until user press some key
    waitKey(0);
    return 0;
}

Tested in linux mint 17


问:
Pandas autocorrelation function error: 'DataFrame' object has no attribute 'autocorr'
I want to find autocorrelation in Google Trends historical data. The unofficial API uses Pandas Dataframes for which I decided to use its built in autocorrelation function, here's the code:

```<code>from pytrends.request import TrendReq

z = ["animales"]

google_username = "xxx@gmail.com"
google_password = "xxxxxxxxx"
path = ""

pytrend = TrendReq(google_username, google_password, custom_useragent='')

pytrend.build_payload(kw_list=z, timeframe='today 5-y', geo='MX')

interest_over_time_df = pytrend.interest_over_time()

print(interest_over_time_df[z].autocorr(lag=1))
</code>```

This has worked before and am not sure what did I change, my code throws the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/Rafael/PycharmProjects/untitled/test.py", line 19, in <module>
     print(interest_over_time_df[z].autocorr(lag=1))
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pandas\core\generic.py", line 2744, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'autocorr'
</code>```

答: some_dataframe["col_name"] returns a Series.  some_dataframe[["col_name"]] returns a DataFrame.  autocorr is a Series function.

Body:
I want to find autocorrelation in Google Trends historical data. The unofficial API uses Pandas Dataframes for which I decided to use its built in autocorrelation function, here's the code:

from pytrends.request import TrendReq

z = ["animales"]

google_username = "xxx@gmail.com"
google_password = "xxxxxxxxx"
path = ""

pytrend = TrendReq(google_username, google_password, custom_useragent='')

pytrend.build_payload(kw_list=z, timeframe='today 5-y', geo='MX')

interest_over_time_df = pytrend.interest_over_time()

print(interest_over_time_df[z].autocorr(lag=1))

This has worked before and am not sure what did I change, my code throws the following error:

Traceback (most recent call last):
  File "C:/Users/Rafael/PycharmProjects/untitled/test.py", line 19, in <module>
     print(interest_over_time_df[z].autocorr(lag=1))
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pandas\core\generic.py", line 2744, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'autocorr'


问:
Hover over an image in one column to make text appear in a different column
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

```<code><div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img10" src="Resources/img/10.jpg" alt="Pastel Pink Placard and Pearls">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img11" src="Resources/img/11.jpg" alt="Naked Wedding Cake with fresh fruit">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img12" src="Resources/img/12.jpg" alt="Gold Damask and Pearls">
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="Resources/img/1.jpg" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>
</code>```

答:
Here is a way that I would accomplish what you want. You´d normally have two images a small thumbnail and a larger image. You could put the thumbnail location in the src of your img inside .cake-image. Then you would have a link to your full size image, wich would be in the href of a.image-preview. This would make your page load faster, since you would originally only load the thumbnails, and load the full image only when needed.

For the text part, I would add a data attribute like data-description where i would put the description or other values you want. This then can be extracted using something along the lines of $("element_selector").data("wha-is-after-hypen"). See the code below.

NOTE: I´m assuming you´re using twitter boostrap and jquery, hence the links at the beggining of the code.

(function($) {
  $(document).ready(function() { //execute this when the document is ready
    $(".image-preview").on("mouseover click", mouseoverHandler); //Bind actions to the mouseover and click events. Why click? because if someone clicks on your link you will be redirected to the image.

    function mouseoverHandler(event) {
      event.preventDefault(); //Prevent the default action, in this case click is the trouvlesome one
      $("#preview").prop("src", $(this).attr('href')); // replace the previews src with the href of your link
      $("#info").html($(this).data('description')); //Add the data description to your info element
    };
  });
})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-xs-3">
    <ul class="cake-thumbs">
      <li>

          <figure class="cake-img">
            <img id="img10" src="https://s-media-cache-ak0.pinimg.com/736x/7a/18/07/7a18076909f51c90242c4d03e5be012f.jpg" alt="Pastel Pink Placard and Pearls" width="100px">
          </figure>

      </li>
      <li>

          <figure class="cake-img">
            <img id="img11" src="https://s-media-cache-ak0.pinimg.com/736x/cb/e7/99/cbe79953ed564435600981aaffe5593c.jpg" alt="Naked Wedding Cake with fresh fruit" width="100px">
          </figure>

      </li>
      <li>

          <figure class="cake-img">
            <img id="img12" src="https://apis.xogrp.com/media-api/images/b4adc5bb-71b3-f0de-edeb-25f42dc2cf91~sc_320.320" alt="Gold Damask and Pearls" width="100px">
          </figure>

      </li>
    </ul>
  </div>
  <div class="col-xs-6">
    <img id="preview" src="" alt="" width="200">
  </div>
  <div class="col-xs-3">
    <p id="info">Price and servings here: </p>
  </div>
</div></code>```

Body:
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

Price and servings here

Body:
Here is a way that I would accomplish what you want. You´d normally have two images a small thumbnail and a larger image. You could put the thumbnail location in the src of your img inside .cake-image. Then you would have a link to your full size image, wich would be in the href of a.image-preview. This would make your page load faster, since you would originally only load the thumbnails, and load the full image only when needed.

For the text part, I would add a data attribute like data-description where i would put the description or other values you want. This then can be extracted using something along the lines of $("element_selector").data("wha-is-after-hypen"). See the code below.

NOTE: I´m assuming you´re using twitter boostrap and jquery, hence the links at the beggining of the code.

(function($) {
  $(document).ready(function() { //execute this when the document is ready
    $(".image-preview").on("mouseover click", mouseoverHandler); //Bind actions to the mouseover and click events. Why click? because if someone clicks on your link you will be redirected to the image.

    function mouseoverHandler(event) {
      event.preventDefault(); //Prevent the default action, in this case click is the trouvlesome one
      $("#preview").prop("src", $(this).attr('href')); // replace the previews src with the href of your link
      $("#info").html($(this).data('description')); //Add the data description to your info element
    };
  });
})(jQuery);

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-xs-3">
    <ul class="cake-thumbs">
      <li>
        <a class="image-preview" href="https://s-media-cache-ak0.pinimg.com/736x/7a/18/07/7a18076909f51c90242c4d03e5be012f.jpg" data-description="5">
          <figure class="cake-img">
            <img id="img10" src="https://s-media-cache-ak0.pinimg.com/736x/7a/18/07/7a18076909f51c90242c4d03e5be012f.jpg" alt="Pastel Pink Placard and Pearls" width="100px">
          </figure>
        </a>
      </li>
      <li>
        <a class="image-preview" href="https://s-media-cache-ak0.pinimg.com/736x/cb/e7/99/cbe79953ed564435600981aaffe5593c.jpg" data-description="8">
          <figure class="cake-img">
            <img id="img11" src="https://s-media-cache-ak0.pinimg.com/736x/cb/e7/99/cbe79953ed564435600981aaffe5593c.jpg" alt="Naked Wedding Cake with fresh fruit" width="100px">
          </figure>
        </a>
      </li>
      <li>
        <a class="image-preview" href="https://apis.xogrp.com/media-api/images/b4adc5bb-71b3-f0de-edeb-25f42dc2cf91~sc_320.320" alt="Naked Wedding Cake with fresh fruit" data-description="3">
          <figure class="cake-img">
            <img id="img12" src="https://apis.xogrp.com/media-api/images/b4adc5bb-71b3-f0de-edeb-25f42dc2cf91~sc_320.320" alt="Gold Damask and Pearls" width="100px">
          </figure>
        </a>
      </li>
    </ul>
  </div>
  <div class="col-xs-6">
    <img id="preview" src="" alt="" width="200">
  </div>
  <div class="col-xs-3">
    <p id="info">Price and servings here: </p>
  </div>
</div>


问:
How can I exit the program when user type E and or else V (view)?
I want to end this code in the beginning IF the user enters E or e or else V or v to the question:

Are you sure want to view the Result? If no type 'E' to exit \nIf you want to View Type 'V'

How to do this when the user enters e it'll exit and if enters v it'll show the grades?

Code:

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

int main(void)
{
    int marks;
    printf("Enter The Marks:");
    scanf("%d", &marks);
    printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");
    if(marks>=90) {
        printf("%d, A+\n");
    }
    else if(marks>=80) {
        printf("%d, A\n");
    }
    else if(marks>=70) {
        printf("%d, B\n");
    }
    else if(marks>=60) {
        printf("%d, C\n");
    }
    else if(marks>=50) {
        printf("%d, S\n");
    }
    else if(marks>=40) {
        printf("%d, W\n");
    }
    else if(marks>=30) {
        printf("%d,Try getting more marks for your exams\n");
    }
    return 0;
}
</code>```

答:
If I have understood your problem, you have to manage the different cases.
To do that, you can use "IF" loops or switchs. </p>

```<code>if(marks == 'e' || marks =='E')
{
//do something
}
else if(marks == 'v' || marks =='V')
{
//do something
}
</code>```

<p>Why don't using 2 others variables to manage the exit/stay into the program ? </p>

Body:
I want to end this code in the beginning IF the user enters E or e or else V or v to the question:

Are you sure want to view the Result? If no type 'E' to exit \nIf you want to View Type 'V'

How to do this when the user enters e it'll exit and if enters v it'll show the grades?

Code:

#include <stdio.h>

int main(void)
{
    int marks;
    printf("Enter The Marks:");
    scanf("%d", &marks);
    printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");
    if(marks>=90) {
        printf("%d, A+\n");
    }
    else if(marks>=80) {
        printf("%d, A\n");
    }
    else if(marks>=70) {
        printf("%d, B\n");
    }
    else if(marks>=60) {
        printf("%d, C\n");
    }
    else if(marks>=50) {
        printf("%d, S\n");
    }
    else if(marks>=40) {
        printf("%d, W\n");
    }
    else if(marks>=30) {
        printf("%d,Try getting more marks for your exams\n");
    }
    return 0;
}

Body:
If I have understood your problem, you have to manage the different cases.
To do that, you can use "IF" loops or switchs.

if(marks == 'e' || marks =='E')
{
//do something
}
else if(marks == 'v' || marks =='V')
{
//do something
}

Why don't using 2 others variables to manage the exit/stay into the program ?