问:
Compiling and executing c program in bash script not working because the compiled program is not found
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands

```<code>gcc stadist.c -lm
a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX
</code>```

Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.

答:
It seems that you do not fully grasp what your shellscript does. If you are getting "./a.out: not found" when you run the script it means that the program did not compile correctly. This is probably due to the line:

```<code>rm stadist.c
</code>```

where you actually delete your sourcefile, meaning the script will work at most once. You should check to see that you still have stadist.c somewhere and try to compile and run it outside of the script.

Body:
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands

gcc stadist.c -lm
a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX

Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.

Body:
It seems that you do not fully grasp what your shellscript does. If you are getting "./a.out: not found" when you run the script it means that the program did not compile correctly. This is probably due to the line:

rm stadist.c

where you actually delete your sourcefile, meaning the script will work at most once. You should check to see that you still have stadist.c somewhere and try to compile and run it outside of the script.


来源: stackexchange

问:
Sonarlint not processing files due to analysis errors
I am getting the following error when trying to process files in SonarLint

"File won't be refreshed because there were errors during analysis:"

Unfortunately SonarLint does not report which errors it is
  encountering.  I set sonar.log.level to DEBUG and sonar.verbose to
  true.

My project builds just fine and unit tests run.  I am running version 2.10.0.1922 of SonarLint and version 2017.1.4 of IntelliJ.  I have tried this on JDK 1.8.121 and JDK 1.8.131 but I get the same results.

Is there any way to retrieve what the errors are?  Am I missing something whith the logging parameters?

答:
Now I have an update in place en am finally getting some indication of what the problem was.  I should be able to take it from here.

So the issue is resolved by updating SonarLint

ContentLicense: CC BY-SA 3.0


问:
Anonymous method in Invoke call
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.

We have tried a number of different approaches, all to no avail.

For example:

```<code>myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
</code>```

where someParameter is local to this method

The above will result in a compiler error:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

答:
For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:</p>

```<code>//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
  SomeFunc();
  SomeOtherFunc();
});
</code>```

OwnerDisplayName: Duncan

Title: Anonymous method in Invoke call

Body:
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.

We have tried a number of different approaches, all to no avail.

For example:

myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });

where someParameter is local to this method

The above will result in a compiler error:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

Body:
For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:

//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
  SomeFunc();
  SomeOtherFunc();
});

ContentLicense: CC BY-SA 2.5


问:
Esper: How to fix error java.util.ConcurrentModificationException in core Esper engine?
When using Esper, I obtained this error.

What could be the cause?

```<code>2017-02-05 15:51:59,781 [...] ERROR com.espertech.esper.core.service.ExceptionHandlingService  - Exception encountered processing statement '...' statement text 'INSERT INTO Window
    SELECT *
    FROM TableWithJoins
    WHERE test=3
    ORDER BY (Math.abs(Total)) DESC
    LIMIT 10' : null
    java.util.ConcurrentModificationException
            at java.util.ArrayDeque$DeqIterator.next(ArrayDeque.java:643)
            at com.espertech.esper.event.EventBeanUtility.flatten(EventBeanUtility.java:186)
            at com.espertech.esper.collection.FlushedEventBuffer.getAndFlush(FlushedEventBuffer.java:41)
            at com.espertech.esper.view.internal.SingleStreamDispatchView.execute(SingleStreamDispatchView.java:56)
            at com.espertech.esper.core.context.util.EPStatementAgentInstanceHandle.internalDispatch(EPStatementAgentInstanceHandle.java:127)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.processHandle(NamedWindowServiceImpl.java:468)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.processDispatches(NamedWindowServiceImpl.java:247)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.dispatch(NamedWindowServiceImpl.java:214)
            at com.espertech.esper.core.service.EPRuntimeImpl.processThreadWorkQueueFront(EPRuntimeImpl.java:858)
            at com.espertech.esper.core.service.EPRuntimeImpl.processThreadWorkQueue(EPRuntimeImpl.java:810)
            at com.espertech.esper.core.service.EPRuntimeImpl.processWrappedEvent(EPRuntimeImpl.java:500)
            at com.espertech.esper.event.EventSenderBean.sendEvent(EventSenderBean.java:84)
</code>```

I am using Esper v5.2.

答:
This issue can be caused by a join in a previous insert statement.

To fix, add undirectional to one of the join statements.

The reason this works is that if there is a join statement in Esper, any incoming event from any of the join clauses can trigger an update. By adding "unidirectional", this means that only one thread pushes events downstream, rather than two, which solves any threading issues.

This issue may have been fixed in later versions of Esper.

Body:
When using Esper, I obtained this error.

What could be the cause?

2017-02-05 15:51:59,781 [...] ERROR com.espertech.esper.core.service.ExceptionHandlingService  - Exception encountered processing statement '...' statement text 'INSERT INTO Window
    SELECT *
    FROM TableWithJoins
    WHERE test=3
    ORDER BY (Math.abs(Total)) DESC
    LIMIT 10' : null
    java.util.ConcurrentModificationException
            at java.util.ArrayDeque$DeqIterator.next(ArrayDeque.java:643)
            at com.espertech.esper.event.EventBeanUtility.flatten(EventBeanUtility.java:186)
            at com.espertech.esper.collection.FlushedEventBuffer.getAndFlush(FlushedEventBuffer.java:41)
            at com.espertech.esper.view.internal.SingleStreamDispatchView.execute(SingleStreamDispatchView.java:56)
            at com.espertech.esper.core.context.util.EPStatementAgentInstanceHandle.internalDispatch(EPStatementAgentInstanceHandle.java:127)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.processHandle(NamedWindowServiceImpl.java:468)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.processDispatches(NamedWindowServiceImpl.java:247)
            at com.espertech.esper.epl.named.NamedWindowServiceImpl.dispatch(NamedWindowServiceImpl.java:214)
            at com.espertech.esper.core.service.EPRuntimeImpl.processThreadWorkQueueFront(EPRuntimeImpl.java:858)
            at com.espertech.esper.core.service.EPRuntimeImpl.processThreadWorkQueue(EPRuntimeImpl.java:810)
            at com.espertech.esper.core.service.EPRuntimeImpl.processWrappedEvent(EPRuntimeImpl.java:500)
            at com.espertech.esper.event.EventSenderBean.sendEvent(EventSenderBean.java:84)

I am using Esper v5.2.


问:
Get previous distinct number
I've got the following table:

```<code>    id         date           status
    1        2017-04-20        good
    1        2017-04-19        bad
    1        2017-04-18        bad
    2        2017-04-20        ok
    2        2017-04-19        ok
    2        2017-04-17        ok
    2        2017-04-16        bad
</code>```

What I need is to get the previous distinct value in status column per id.

Assuming that today is 2017-04-20, the result would look like this:

```<code>        id       previous_status
        1         bad
        2         bad
</code>```

Afterwards, I wanna use this information in the case statement:
Case when status = 'good' and previous_status = 'bad', ....

答:
You could you this for your first requirement:

```<code>SELECT id, status AS previous_status
FROM table_name
WHERE (id, date_col) IN (
        SELECT id, MAX(date_col)
        FROM table_name
        WHERE DATE(date_col) < "2017-04-20"
    );
</code>```

And this is for second requirement using CASE statement

```<code>SELECT t.id, t.status, t1.previous_status,
    CASE
        WHEN t.status = 'good' AND t1.previous_status = 'bad' THEN 'some_value'
        ELSE 'other_value'
    END AS case_col
FROM table_name t
INNER JOIN (
    SELECT id, status AS previous_status
    FROM table_name
    WHERE (id, date_col) IN (
            SELECT id, MAX(date_col)
            FROM table_name
            WHERE DATE(date_col) < "2017-04-20"
        )
) t1
ON t.id = t1.id
WHERE DATE(t.date_col) = "2017-04-20";
</code>```

This refer how_to_compare_date_google_big_query

Title: Get previous distinct number

Body:
I've got the following table:

    id         date           status
    1        2017-04-20        good
    1        2017-04-19        bad
    1        2017-04-18        bad
    2        2017-04-20        ok
    2        2017-04-19        ok
    2        2017-04-17        ok
    2        2017-04-16        bad

What I need is to get the previous distinct value in status column per id.

Assuming that today is 2017-04-20, the result would look like this:

        id       previous_status
        1         bad
        2         bad

Afterwards, I wanna use this information in the case statement:
Case when status = 'good' and previous_status = 'bad', ....

Body:
You could you this for your first requirement:

SELECT id, status AS previous_status
FROM table_name
WHERE (id, date_col) IN (
        SELECT id, MAX(date_col)
        FROM table_name
        WHERE DATE(date_col) < "2017-04-20"
    );

And this is for second requirement using CASE statement

SELECT t.id, t.status, t1.previous_status,
    CASE
        WHEN t.status = 'good' AND t1.previous_status = 'bad' THEN 'some_value'
        ELSE 'other_value'
    END AS case_col
FROM table_name t
INNER JOIN (
    SELECT id, status AS previous_status
    FROM table_name
    WHERE (id, date_col) IN (
            SELECT id, MAX(date_col)
            FROM table_name
            WHERE DATE(date_col) < "2017-04-20"
        )
) t1
ON t.id = t1.id
WHERE DATE(t.date_col) = "2017-04-20";

This refer how_to_compare_date_google_big_query


问:
C# Error: OutOfMemoryException - Reading a large text file and replacing from dictionary
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

```<code>// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }
</code>```

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

```<code>            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();
</code>```

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

答:
Read file line by line and append changed line to other file. At the end replace source file with new one (create backup or not).</p>

```<code>var tmpFile = Path.GetTempFileName();
using (StreamReader sr = new StreamReader(logF))
{
    using (StreamWriter sw = new StreamWriter(tmpFile))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            foreach (var replacement in replacements)
                line = line.Replace(replacement.Key, replacement.Value);

            sw.WriteLine(line);
        }
    }
}
File.Replace(tmpFile, logF, null);// you can pass backup file name instead on null if you want a backup of logF file
</code>```

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

Body:
Read file line by line and append changed line to other file. At the end replace source file with new one (create backup or not).

var tmpFile = Path.GetTempFileName();
using (StreamReader sr = new StreamReader(logF))
{
    using (StreamWriter sw = new StreamWriter(tmpFile))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            foreach (var replacement in replacements)
                line = line.Replace(replacement.Key, replacement.Value);

            sw.WriteLine(line);
        }
    }
}
File.Replace(tmpFile, logF, null);// you can pass backup file name instead on null if you want a backup of logF file


问:
HTML - change image inside frame and keep frame size intact
My main goal is to have a simple frame (as you can see) with few text lines and images. The thing I want to do, is make this frame flexible. By that I mean - if I change picture inside of it (bigger -> smaller) the frame should change. It should stay fixed.

Online editor: https://www.bootply.com/Y09Zn1wir3#

HTML:

```<code><div class="col-md-4">
  <div class="single-image-wrap">
    <div class="single-image">
      <div class="name">NAME</div>
      <div class="img-wrap">
        <img src="https://cdn.pixabay.com/photo/2013/07/12/14/07/basketball-147794_960_720.png" class="first-image">
      </div>
      <div class="extra-info">
        <div class="bottom-text">ABC</div>
      </div>
    </div>
  </div>
</div>

<div class="col-md-4">
  <div class="single-image-wrap">
    <div class="single-image">
      <div class="name">NAME</div>
      <div class="img-wrap">
        <img src="https://cdn.pixabay.com/photo/2013/07/12/14/07/basketball-147794_960_720.png" class="second-image">
      </div>
      <div class="extra-info">
        <div class="bottom-text">ABC</div>
      </div>
    </div>
  </div>
</div>
</code>```

CSS:

```<code>/* CSS used here will be applied after bootstrap.css */
.single-image{
    border: 1px solid orange;
    width: 100%;
    text-align: center;
    margin: 0px 0px 15px 0px;
    float: right;
}

.name{
    padding: 20px 0px 0px 0px;
    color: black;
    height: 75px;
    font-size: 18px;
}

.img-wrap{
    padding-bottom: 50px;
    padding-top: 25px;
}

.first-image{
    width: 200px;
}

.second-image{
    width: 150px;
}

.extra-info{
    border-top: 1px solid orange;
}

.bottom-text{
    padding-top: 15px;
    height: 50px;
    letter-spacing: 0.1em;
}
</code>```

I tried to add height property to such as:

.single-image{
    ...
    height: 405px;
}

Result: https://www.codeply.com/go/2s2hH3nbju

But it doesn't look correct, as bottom text floats somewhere up.
I need a solution for different type of image sizes. Any ideas?

答:
Try to add this new line in your css code.

```<code>.img-wrap{
  min-height: 275px;
}
</code>```

it will looks like this

Output

Body:
My main goal is to have a simple frame (as you can see) with few text lines and images. The thing I want to do, is make this frame flexible. By that I mean - if I change picture inside of it (bigger -> smaller) the frame should change. It should stay fixed.

Online editor: https://www.bootply.com/Y09Zn1wir3#

HTML:

NAME

ABC

NAME

ABC

CSS:

/* CSS used here will be applied after bootstrap.css */
.single-image{
    border: 1px solid orange;
    width: 100%;
    text-align: center;
    margin: 0px 0px 15px 0px;
    float: right;
}

.name{
    padding: 20px 0px 0px 0px;
    color: black;
    height: 75px;
    font-size: 18px;
}

.img-wrap{
    padding-bottom: 50px;
    padding-top: 25px;
}

.first-image{
    width: 200px;
}

.second-image{
    width: 150px;
}

.extra-info{
    border-top: 1px solid orange;
}

.bottom-text{
    padding-top: 15px;
    height: 50px;
    letter-spacing: 0.1em;
}

I tried to add height property to such as:

.single-image{
    ...
    height: 405px;
}

Result: https://www.codeply.com/go/2s2hH3nbju

But it doesn't look correct, as bottom text floats somewhere up.
I need a solution for different type of image sizes. Any ideas?

Body:
Try to add this new line in your css code.

.img-wrap{
  min-height: 275px;
}

it will looks like this

Output


问:
Java Socket know when request to gmail
I'm trying to create an application event (java) that would raise as soon as the machine gets connected to gmail onto the login page (https://www.google.com/accounts/), so I'm trying to build a Socket that would listen to this particular httprequest.
but I can only create a ServerSocket that listens to a port, to a specific ip adress (gmail login page can have so many different ips), but not to a host...
anyone got an idea ?
thank you !</p>

答:
This should help you get started:

http://gforgeek.blogspot.com/2005/04/simple-packet-sniffer-using-java.html

EDIT:

I just checked and I think you're going to have a really hard time accomplishing this because gmail runs on HTTPS so even once you get the packet sniffer running you're going to have to decrypt all SSL communications. I'm not even sure that's possible.

Title: Java Socket know when request to gmail


问:
boost_log example with sinks fails to compile
I was considering using boost_log for one project and right at the beginning I faced following problem.

Boost Log Example I found at: http://www.boost.org/doc/libs/1_54_0/libs/log/example/doc/tutorial_file.cpp fails to compile. Other simpler examples (without sinks) I compile without problems.

```<code>g++ -std=c++11 boost_log_sinks.cpp -DBOOST_LOG_DYN_LINK -lboost_log -lpthread
</code>```

/usr/bin/ld: /tmp/ccApJdsi.o: undefined reference to symbol
  '_ZN5boost6detail12get_tss_dataEPKv'
  //usr/lib/x86_64-linux-gnu/libboost_thread.so.1.54.0: error adding
  symbols: DSO missing from command line collect2: error: ld returned 1
  exit status

I am working on Ubuntu14.04 my g++ version is g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2

Does anybody knows why is this happening?

答:
The boost_log library uses features from other boost libraries. Unfortunately the documentation fails to indicate which ones are these libraries. So whenever you use one of these features, you need to link with the corresponding lib in which that feature is in or you get the error message:

undefined reference to symbol

The solution I use is to loop all boost libs to search for that symbol (in your case _ZN5boost6detail12get_tss_dataEPKv.)

In Ubuntu 17.04 the boost libs are stored in /usr/lib/x86_64-linux-gnu/libboost_*

So with following script:

```<code>for i in /usr/lib/x86_64-linux-gnu/libboost_*
do
   echo $i
   nm $i|grep _ZN5boost6detail12get_tss_dataEPKv
done
</code>```

you get a list of libraries where the symbol is either used (U), e.g.:

```<code>/usr/lib/x86_64-linux-gnu/libboost_log.a
                 U _ZN5boost6detail12get_tss_dataEPKv
                 U _ZN5boost6detail12get_tss_dataEPKv
                 U _ZN5boost6detail12get_tss_dataEPKv
/usr/lib/x86_64-linux-gnu/libboost_log_setup.a
                 U _ZN5boost6detail12get_tss_dataEPKv
</code>```

or defined (T), e.g.:

```<code>/usr/lib/x86_64-linux-gnu/libboost_thread.a
0000000000000740 T _ZN5boost6detail12get_tss_dataEPKv
</code>```

This last one is the one you need. It tells that the symbol you are looking for is in the library libboost_thread.a. So all you have to do now is to include that lib in your link command:

```<code>g++ -std=c++11 boost_log_sinks.cpp -DBOOST_LOG_DYN_LINK -lboost_log -lboost_thread -lpthread
</code>```

Body:
I was considering using boost_log for one project and right at the beginning I faced following problem.

Boost Log Example I found at: http://www.boost.org/doc/libs/1_54_0/libs/log/example/doc/tutorial_file.cpp fails to compile. Other simpler examples (without sinks) I compile without problems.

g++ -std=c++11 boost_log_sinks.cpp -DBOOST_LOG_DYN_LINK -lboost_log -lpthread

/usr/bin/ld: /tmp/ccApJdsi.o: undefined reference to symbol
  '_ZN5boost6detail12get_tss_dataEPKv'
  //usr/lib/x86_64-linux-gnu/libboost_thread.so.1.54.0: error adding
  symbols: DSO missing from command line collect2: error: ld returned 1
  exit status

I am working on Ubuntu14.04 my g++ version is g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2

Does anybody knows why is this happening?

Body:
The boost_log library uses features from other boost libraries. Unfortunately the documentation fails to indicate which ones are these libraries. So whenever you use one of these features, you need to link with the corresponding lib in which that feature is in or you get the error message:

undefined reference to symbol

The solution I use is to loop all boost libs to search for that symbol (in your case _ZN5boost6detail12get_tss_dataEPKv.)

In Ubuntu 17.04 the boost libs are stored in /usr/lib/x86_64-linux-gnu/libboost_*

So with following script:

for i in /usr/lib/x86_64-linux-gnu/libboost_*
do
   echo $i
   nm $i|grep _ZN5boost6detail12get_tss_dataEPKv
done

you get a list of libraries where the symbol is either used (U), e.g.:

/usr/lib/x86_64-linux-gnu/libboost_log.a
                 U _ZN5boost6detail12get_tss_dataEPKv
                 U _ZN5boost6detail12get_tss_dataEPKv
                 U _ZN5boost6detail12get_tss_dataEPKv
/usr/lib/x86_64-linux-gnu/libboost_log_setup.a
                 U _ZN5boost6detail12get_tss_dataEPKv

or defined (T), e.g.:

/usr/lib/x86_64-linux-gnu/libboost_thread.a
0000000000000740 T _ZN5boost6detail12get_tss_dataEPKv

This last one is the one you need. It tells that the symbol you are looking for is in the library libboost_thread.a. So all you have to do now is to include that lib in your link command:

g++ -std=c++11 boost_log_sinks.cpp -DBOOST_LOG_DYN_LINK -lboost_log -lboost_thread -lpthread


问:
Linux Shell, Awk : Merge 2 Variable Data by Column
The left part data (in variable) like :

```<code> echo "$lpart"

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"
</code>```

The right part data (in variable) like :

```<code>echo "$rpart"

"qhy2"
"qhy2"
"Apple Setup"
"qhy2"
</code>```

I would like to merge the 2 data by column, it is :

```<code> "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "Apple Setup"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"  "qhy2"
</code>```

This request is the same as the post : how to combine two variable column-by-column in bash, but my busybox does not support paste command.
I have tried the commands :

```<code> awk 'BEGIN{print ARGV[1], ARGV[2]}' "$lpart"  "$rpart"
 awk -v awk_lpart="$lpart" -v awk_rpart="$rpart" 'BEGIN{print awk_lpart awk_rpart }'
</code>```

those will merge by row..

Could you give me suggestion how I could achieve the request ? Thank you.

Body:
The left part data (in variable) like :

 echo "$lpart"

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"

The right part data (in variable) like :

echo "$rpart"

"qhy2"
"qhy2"
"Apple Setup"
"qhy2"

I would like to merge the 2 data by column, it is :

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "Apple Setup"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"  "qhy2"

This request is the same as the post : how to combine two variable column-by-column in bash, but my busybox does not support paste command.
I have tried the commands :

 awk 'BEGIN{print ARGV[1], ARGV[2]}' "$lpart"  "$rpart"
 awk -v awk_lpart="$lpart" -v awk_rpart="$rpart" 'BEGIN{print awk_lpart awk_rpart }'

those will merge by row..

Could you give me suggestion how I could achieve the request ? Thank you.

Body:
Using awk you can do this:

awk 'NR==FNR {a[FNR]=$1; next} {print $0, a[FNR]}' <(echo "$rpart") <(echo "$lpart")
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "qhy2"
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "qhy2"
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "Apple
"2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55" "qhy2"


问:
c#: Invoking Methods
i am using the following function plot() to plot data on google maps.now when i am calling the same function from another button click event it is not getting executed rather going into else() statement.my plot function is as follows:

```<code> public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
 {
        if (this.InvokeRequired)
        {
            // do something
        }
        else { this.Close(); }
 }
</code>```

i am calling this function from button click event as follows:

```<code>private void button6_Click_1(object sender, EventArgs e) /// refresh button
{
      this.Invoke((MethodInvoker)(() =>
                   {
                        plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82");
                   }));
}
</code>```

when is the reason for this? i am new to invoking methods.please help
Edit:https://stackoverflow.com/a/43797637/6412780 The reason why i am using  invocation because i was plotting 5 markers simultaneously on gmap from different threads.so for synchronization i am using invocation method.BUT now i  want to update my data. i made a refresh button which contains new lat /long (passing manually here) to plot on the map.being on the same UI i called the plot() function directly ,but even then  i wasn't able to execute the if statement. that is what i am doing .

答:
Invocation is required if you try to access elements, that are exclusive to one Threadfrom another Thread. It is very common when accessing GUI elements from a background thread. Here is an example:

```<code>    Thread t = new Thread(() => plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82"));

    public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
    {
        if (this.InvokeRequired)
        {
           this.Invoke((MethodInvoker)(() =>
               {
                    this.Close();
               }));
        }
        else {
           this.Close();
        }
     }
</code>```

thisseems to be a Form. If you call the Close method from another Thread you will most likely get an Exception (There are ways to prevent this, but thats not considered good style). You need to invoke that method (let the Form decide, when it is ready to execute the command)

Title: c#: Invoking Methods

Body:
i am using the following function plot() to plot data on google maps.now when i am calling the same function from another button click event it is not getting executed rather going into else() statement.my plot function is as follows:

 public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
 {
        if (this.InvokeRequired)
        {
            // do something
        }
        else { this.Close(); }
 }

i am calling this function from button click event as follows:

private void button6_Click_1(object sender, EventArgs e) /// refresh button
{
      this.Invoke((MethodInvoker)(() =>
                   {
                        plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82");
                   }));
}

when is the reason for this? i am new to invoking methods.please help
Edit:https://stackoverflow.com/a/43797637/6412780 The reason why i am using  invocation because i was plotting 5 markers simultaneously on gmap from different threads.so for synchronization i am using invocation method.BUT now i  want to update my data. i made a refresh button which contains new lat /long (passing manually here) to plot on the map.being on the same UI i called the plot() function directly ,but even then  i wasn't able to execute the if statement. that is what i am doing .

Body:
Invocation is required if you try to access elements, that are exclusive to one Threadfrom another Thread. It is very common when accessing GUI elements from a background thread. Here is an example:

    Thread t = new Thread(() => plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82"));

    public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
    {
        if (this.InvokeRequired)
        {
           this.Invoke((MethodInvoker)(() =>
               {
                    this.Close();
               }));
        }
        else {
           this.Close();
        }
     }

thisseems to be a Form. If you call the Close method from another Thread you will most likely get an Exception (There are ways to prevent this, but thats not considered good style). You need to invoke that method (let the Form decide, when it is ready to execute the command)


问:
How to attach PDF to email using PHP

This is php code and its working, all the form content successfully send to mail id, but i want to attach PDF file also to email using php this function.
  But how i can, i don't know.

I would like to add a specified PDF file as a file attachment to the email. How would I do that?

```<code><?php
$name  = $_REQUEST["name"];
$phone = $_REQUEST["phone"];
$email = $_REQUEST["email"];
$address = $_REQUEST["address"];
$message = $_REQUEST["message"];
date_default_timezone_set("Asia/Calcutta");
$todayis = date("y-m-d H:i:s", time());
$subject = "PVC Order From Website ";
$to      = "iamrightful@gmail.com";
$msg .= "<table width='600' border='0' align='center' cellpadding='0' ellspacing='0' style='font-family:Arial, Helvetica, sans-serif;
font-size:13pt; border:1px solid #0f3f6a;'>";
$msg .= "<tr>";
$msg .= "<td width='16' height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td width='96' bgcolor='#f9cf7b'>Name</td>";
$msg .= "<td width='10' height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$name</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>Mobile </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$phone</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<tr>";
$msg .= "<td height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>Email Id </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$email</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25'> </td>";
$msg .= "<td height='25'>Address</td>";
$msg .= "<td height='25'><strong>:</strong></td>";
$msg .= "<td height='25'>$address</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25'> </td>";
$msg .= "<td height='25'>Discription</td>";
$msg .= "<td height='25'><strong>:</strong></td>";
$msg .= "<td height='25'>$message</td>";
$msg .= "</tr>";
$msg .= "</table>";
$headers = "From: $c_name < $c_email >.";
$headers = "Bcc: admin < $Bcc >.";
$headers .= "\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $msg, $headers);
header("Location:thankyou.html");
</code>```

答:
Download the PHPMailer library from the link given below:

https://github.com/PHPMailer/PHPMailer

and then use this code

```<code>require_once('../PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From      = '';
$mail->FromName  = '';
$mail->Subject   = '';
$MESSAGE_BODY = "Name: ".$name." "."\r\n";
$MESSAGE_BODY .= "Email: ".$email." "."\r\n";
$MESSAGE_BODY .= "Contact No.: ".$cno." "."\r\n";
$MESSAGE_BODY .= "Message: ".$message." "."\r\n";
$mail->Body      = $MESSAGE_BODY;
$mail->AddAddress( '' );

$mail->AddAttachment($_FILES['file']['tmp_name'],
                 $_FILES['file']['name']);

if ($mail->Send())
{
    echo "Mail Sent";
}
else
{
    echo "Could not send mail";
}
</code>```

It will work fine.

Title: How to attach PDF to email using PHP

Body:
This is php code and its working, all the form content successfully send to mail id, but i want to attach PDF file also to email using php this function.
  But how i can, i don't know.

I would like to add a specified PDF file as a file attachment to the email. How would I do that?

<?php
$name  = $_REQUEST["name"];
$phone = $_REQUEST["phone"];
$email = $_REQUEST["email"];
$address = $_REQUEST["address"];
$message = $_REQUEST["message"];
date_default_timezone_set("Asia/Calcutta");
$todayis = date("y-m-d H:i:s", time());
$subject = "PVC Order From Website ";
$to      = "iamrightful@gmail.com";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Name	";
$msg .= ":	";
$msg .= "$name	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Mobile 	";
$msg .= ":	";
$msg .= "$phone	";
$msg .= "
";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Email Id 	";
$msg .= ":	";
$msg .= "$email	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Address	";
$msg .= ":	";
$msg .= "$address	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Discription	";
$msg .= ":	";
$msg .= "$message	";
$msg .= "
";
$msg .= "
";
$headers = "From: $c_name < $c_email >.";
$headers = "Bcc: admin < $Bcc >.";
$headers .= "\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $msg, $headers);
header("Location:thankyou.html");

Body:
Download the PHPMailer library from the link given below:

https://github.com/PHPMailer/PHPMailer

and then use this code

require_once('../PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From      = '';
$mail->FromName  = '';
$mail->Subject   = '';
$MESSAGE_BODY = "Name: ".$name." "."\r\n";
$MESSAGE_BODY .= "Email: ".$email." "."\r\n";
$MESSAGE_BODY .= "Contact No.: ".$cno." "."\r\n";
$MESSAGE_BODY .= "Message: ".$message." "."\r\n";
$mail->Body      = $MESSAGE_BODY;
$mail->AddAddress( '' );

$mail->AddAttachment($_FILES['file']['tmp_name'],
                 $_FILES['file']['name']);

if ($mail->Send())
{
    echo "Mail Sent";
}
else
{
    echo "Could not send mail";
}

It will work fine.


问:
Write junit for JPA repository
Hi I need to write junit test cases for JPA repository. Code is as below.

Test is written as below. I have already added @ContextConfiguration on the class.

```<code>@Autowired
@Qualifier("repository")
private Repository repository;

@Test
public void testCreate() {
    Object objRequest = getObjForRequest();
    Object obj = repository.create(objRequest);
    assertTrue(obj.getId().equals(objRequest.getId()));
}

private Object getObjForRequest() {
    Object obj = new Object();

    obj.setId(1);

    return obj;
}
</code>```

My Repository is written as below.

```<code>@Repository("repository")
public class Repository implements RepositoryInterface {

      @PersistenceContext
      private EntityManager entityManager;

      @Transactional(value = "springJpaTransactionManager")
      @Override
      public Object create(Object obj) {
             Object ob = obj;
             entityManager.persist(ob);
             entityManager.flush();
             return ob;
      }
}
</code>```

When I am running test case it is giving me below error.

```<code>javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:com.*.*.Object
</code>```

Can anybody help me resolving this.

Thanks

答:
remove setId from :

```<code>private Object getObjForRequest() {
    Object obj = new Object();
    obj.setId(1);
    return obj;
}
</code>```

you shouldn't set id , as id generated when object become persisted id DB. When you call repository.create(objRequest) with id , spring data do check what it should be - creation new object or update existed , and this check is based on id!=null;

you should check :

```<code>   assertNoNull(obj.getId());
   assertTrue(obj.getId().longValue()>0);
</code>```

you can compare that id as expected only where you update some existed entity.

Title: Write junit for JPA repository

Body:
Hi I need to write junit test cases for JPA repository. Code is as below.

Test is written as below. I have already added @ContextConfiguration on the class.

@Autowired
@Qualifier("repository")
private Repository repository;

@Test
public void testCreate() {
    Object objRequest = getObjForRequest();
    Object obj = repository.create(objRequest);
    assertTrue(obj.getId().equals(objRequest.getId()));
}

private Object getObjForRequest() {
    Object obj = new Object();

    obj.setId(1);

    return obj;
}

My Repository is written as below.

@Repository("repository")
public class Repository implements RepositoryInterface {

      @PersistenceContext
      private EntityManager entityManager;

      @Transactional(value = "springJpaTransactionManager")
      @Override
      public Object create(Object obj) {
             Object ob = obj;
             entityManager.persist(ob);
             entityManager.flush();
             return ob;
      }
}

When I am running test case it is giving me below error.

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:com.*.*.Object

Can anybody help me resolving this.

Thanks

Body:
remove setId from :

private Object getObjForRequest() {
    Object obj = new Object();
    obj.setId(1);
    return obj;
}

you shouldn't set id , as id generated when object become persisted id DB. When you call repository.create(objRequest) with id , spring data do check what it should be - creation new object or update existed , and this check is based on id!=null;

you should check :

   assertNoNull(obj.getId());
   assertTrue(obj.getId().longValue()>0);

you can compare that id as expected only where you update some existed entity.


问:
Is it possible to create a custom screen GUI in Bukkit?
I'm wondering if it's possible to add some custom screen GUI's to my Bukkit server. So I can display a lot of text on someone's screen. Or do I need to find another option to do this?

Thanks!

答:
As Cole Nelson mentioned, a custom inventory with lore displayed might work. A good guide for that can be found on the bukkit forums, and although it's a bit outdated it should still provide useful information.

Another possibility would be to utilize title screens; obviously those can't hold a ton of information, but the player is pretty much guaranteed to notice them immediatly.

I recommend using Title Api, as it's a bit tedious to directly work with packets.
Once you added the jar to your project and set the dependency, simply use:

```<code>TitleAPI.sendTitle(player,fadeIn,stay,fadeOut,"Title","Subtitle");
</code>```

to send a title with all corresponding attributes.

Example result:

Body:
As Cole Nelson mentioned, a custom inventory with lore displayed might work. A good guide for that can be found on the bukkit forums, and although it's a bit outdated it should still provide useful information.

Another possibility would be to utilize title screens; obviously those can't hold a ton of information, but the player is pretty much guaranteed to notice them immediatly.

I recommend using Title Api, as it's a bit tedious to directly work with packets.
Once you added the jar to your project and set the dependency, simply use:

TitleAPI.sendTitle(player,fadeIn,stay,fadeOut,"Title","Subtitle");

to send a title with all corresponding attributes.

Example result:


问:
UITextView scrollEnabled = YES not working after set scrollEnabled = NO in iOS8
I create a demo for checking UITextView scrollEnabled.
It only contains 1 UITextView and 2 button enable and disable scroll

I test on simulator and device iOS 8, if I click the disable scroll button, the UITextView will disable scroll correctly, but after that I
click on enable scroll, the UITextView  won't enable scroll

However, I test on device iOS9, the enable and disable scroll work well.

```<code>#import "ViewController.h"

@interface ViewController ()

    @property (weak, nonatomic) IBOutlet UITextView *myTextView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)enableScrollButtonPressed:(id)sender{
    self.myTextView.scrollEnabled = YES;
}

- (IBAction)disableScrollButtonPressed:(id)sender{
    self.myTextView.scrollEnabled = NO;
}

@end
</code>```

Any idea to fix this problem? If someone don't understand my explain please check
my demo project

Any help or suggestion would be great appreciated

答:
Try this one</p>

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
    tableView.setContentOffset(CGPoint.zero, animated: false)
}
</code>```

Body:
I create a demo for checking UITextView scrollEnabled.
It only contains 1 UITextView and 2 button enable and disable scroll

I test on simulator and device iOS 8, if I click the disable scroll button, the UITextView will disable scroll correctly, but after that I
click on enable scroll, the UITextView  won't enable scroll

However, I test on device iOS9, the enable and disable scroll work well.

#import "ViewController.h"

@interface ViewController ()

    @property (weak, nonatomic) IBOutlet UITextView *myTextView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)enableScrollButtonPressed:(id)sender{
    self.myTextView.scrollEnabled = YES;
}

- (IBAction)disableScrollButtonPressed:(id)sender{
    self.myTextView.scrollEnabled = NO;
}

@end

Any idea to fix this problem? If someone don't understand my explain please check
my demo project

Any help or suggestion would be great appreciated

Body:
Try this one

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    tableView.setContentOffset(CGPoint.zero, animated: false)
}


问:
How to remove Google Search engine placeholder (Cse)
I am trying to remove the placeholder of the google search engine using jquery addClass and css.

Website url: https://gragop.herokuapp.com

Inspect console: if you add class w3-hide inside gsc-input class it removes it but I don't know how to do it.

CSS

```<code>.w3-hide{display:none!important}
</code>```

Jquery I am trying with no success:

```<code>$(".gsc-input").addClass("gsc-input w3-hide");
</code>```

答:
```<code>$(document).ready(function(){
 $('#gsc-i-id1').attr("placeholder", "");
 $('#gsc-i-id1').css('background-image', 'none');
 $("#gsc-i-id1").blur(function() {
  $('#gsc-i-id1').css('background-image', 'none');
 });
});
</code>```

Body:
I am trying to remove the placeholder of the google search engine using jquery addClass and css.

Website url: https://gragop.herokuapp.com

Inspect console: if you add class w3-hide inside gsc-input class it removes it but I don't know how to do it.

CSS

.w3-hide{display:none!important}

Jquery I am trying with no success:

$(".gsc-input").addClass("gsc-input w3-hide");


问:
Optaplanner in osgi
I'm trying to get optaplanner 6.5.0 to work in an osgi environment.
I had to install following bundles to get all dependencies resolved:

```<code>OptaPlanner coreorg.optaplanner.core                                                            6.5.0.201610181310
XStream Corexstream                                                                             1.4.9
Apache Commons Mathorg.apache.commons.math3                                                     3.4.1
Drools :: Compilerorg.drools.compiler                                                           6.5.0.201610181300
Drools :: Coreorg.drools.core                                                                   6.5.0.201610181300
KIE :: Public APIorg.kie.api                                                                    6.5.0.201610181259
KIE :: Internalorg.kie.internalapi                                                              6.5.0.201610181259
Protocol Buffer Java APIcom.google.protobuf                                                     2.6.0
mvel2org.mvel2                                                                                2.2.8.Final
Apache ServiceMix :: Bundles :: javax.injectorg.apache.servicemix.bundles.javax-inject          1.0.0.2
XML Pull Parsing APIorg.xmlpull.v1                                                              1.1.4.redhat-1
Apache ServiceMix :: Bundles :: xpp3org.apache.servicemix.bundles.xpp3                          1.1.4.c
Apache ServiceMix :: Specs :: Activation API 1.4org.apache.servicemix.specs.activation-api-1.1  2.0.0
Apache ServiceMix :: Bundles :: jaxb-xjcorg.apache.servicemix.bundles.jaxb-xjc                  2.2.4.1
Apache ServiceMix :: Specs :: JAXB API 2.2org.apache.servicemix.specs.jaxb-api-2.2              2.9.0
Apache ServiceMix :: Specs :: Stax API 1.0org.apache.servicemix.specs.stax-api-1.0              2.9.0
Apache ServiceMix :: Bundles :: jaxb-implorg.apache.servicemix.bundles.jaxb-impl                2.2.11.1
Apache ServiceMix :: Bundles :: reflectionsorg.apache.servicemix.bundles.reflections            0.9.11.1
OptaPlanner persistence commonorg.optaplanner.persistence.common                                6.5.0.201610181310
Sling Metrics :: CQ Fragmentcom.github.digital-wonderland.sling-metrics.cq-metrics-fragment     0.1.0
Guava: Google Core Libraries for Javacom.google.guava                                           18.0.0
</code>```

When testing a simple example, which a got working through a junit test, I get following error:

```<code>java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:69)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:278)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:229)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:52)
    at com.bekaert.handling.allocation.optimizer.impl.OptimizerTest.before(OptimizerTest.java:55)
    at com.bekaert.handling.allocation.optimizer.impl.TestAllocationOptimizerImpl.activate(TestAllocationOptimizerImpl.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at java.lang.reflect.Method.invoke(Unknown Source)[:1.8.0_25]
    at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624)
    at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:376)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.initialize(BundleComponentActivator.java:172)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.<init>(BundleComponentActivator.java:120)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:258)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.access$000(Activator.java:45)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:185)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:479)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:414)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:443)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:869)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:790)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:515)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4429)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2100)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:976)[org.apache.felix.framework-4.4.1.jar:]
    at aQute.launcher.Launcher.update(Launcher.java:436)[biz.aQute.launcher-latest.jar:]
    at aQute.launcher.Launcher$1.run(Launcher.java:194)[biz.aQute.launcher-latest.jar:]
    at java.util.TimerThread.mainLoop(Unknown Source)[:1.8.0_25]
    at java.util.TimerThread.run(Unknown Source)[:1.8.0_25]
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Predicate not found by org.apache.servicemix.bundles.reflections [205]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1556)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:77)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1993)[org.apache.felix.framework-4.4.1.jar:]
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]
    ... 43 more
</code>```

What I noticed is that in the org.apache.servicemix.bundles.reflections bundle the import-package com.google.common.base is optional.
This means it should even be able to work without that package?
I cannot remove the com.google.guava bundle, because it is required for the org.optaplanner.core bundle.

What other things can I try to make this work? Anyone else already managed to get optaplanner working in an osgi environment?

Best regards,
Sigi

答:
What I noticed is that in the org.apache.servicemix.bundles.reflections bundle the import-package com.google.common.base is optional. This means it should even be able to work without that package?

In theory, this is true. However usually when you see resolution:=optional for an imported package, what it means is one or more of:

This was generated by a tool and I didn't really check what it was doing

This package is only used on some code paths, but not really optional. If you go down any of those code paths it will just explode at runtime

I just wanted to make my bundle easier to resolve, and didn't understand that the package really was needed.

From the issues you're seeing I'd guess this is a case of the package only being needed on some code paths.

What other things can I try to make this work? Anyone else already managed to get optaplanner working in an osgi environment?

From the stack trace it looks as though this is failing during configuration, so you may be able to configure around the problem by avoiding the feature that's broken. You could also install a bundle that actually provides com.google.common.base, satisfying the optional import.

Another way to go is to completely repackage the library, making sure that you get the OSGi metadata correct. You can also embed other libraries (or parts of libraries) into this repackaged bundle to limit its set of imported packages and/or to work around places where reflective class loading causes problems.

Title: Optaplanner in osgi

Body:
I'm trying to get optaplanner 6.5.0 to work in an osgi environment.
I had to install following bundles to get all dependencies resolved:

OptaPlanner coreorg.optaplanner.core                                                            6.5.0.201610181310
XStream Corexstream                                                                             1.4.9
Apache Commons Mathorg.apache.commons.math3                                                     3.4.1
Drools :: Compilerorg.drools.compiler                                                           6.5.0.201610181300
Drools :: Coreorg.drools.core                                                                   6.5.0.201610181300
KIE :: Public APIorg.kie.api                                                                    6.5.0.201610181259
KIE :: Internalorg.kie.internalapi                                                              6.5.0.201610181259
Protocol Buffer Java APIcom.google.protobuf                                                     2.6.0
mvel2org.mvel2                                                                                2.2.8.Final
Apache ServiceMix :: Bundles :: javax.injectorg.apache.servicemix.bundles.javax-inject          1.0.0.2
XML Pull Parsing APIorg.xmlpull.v1                                                              1.1.4.redhat-1
Apache ServiceMix :: Bundles :: xpp3org.apache.servicemix.bundles.xpp3                          1.1.4.c
Apache ServiceMix :: Specs :: Activation API 1.4org.apache.servicemix.specs.activation-api-1.1  2.0.0
Apache ServiceMix :: Bundles :: jaxb-xjcorg.apache.servicemix.bundles.jaxb-xjc                  2.2.4.1
Apache ServiceMix :: Specs :: JAXB API 2.2org.apache.servicemix.specs.jaxb-api-2.2              2.9.0
Apache ServiceMix :: Specs :: Stax API 1.0org.apache.servicemix.specs.stax-api-1.0              2.9.0
Apache ServiceMix :: Bundles :: jaxb-implorg.apache.servicemix.bundles.jaxb-impl                2.2.11.1
Apache ServiceMix :: Bundles :: reflectionsorg.apache.servicemix.bundles.reflections            0.9.11.1
OptaPlanner persistence commonorg.optaplanner.persistence.common                                6.5.0.201610181310
Sling Metrics :: CQ Fragmentcom.github.digital-wonderland.sling-metrics.cq-metrics-fragment     0.1.0
Guava: Google Core Libraries for Javacom.google.guava                                           18.0.0

When testing a simple example, which a got working through a junit test, I get following error:

java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:69)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:278)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:229)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:52)
    at com.bekaert.handling.allocation.optimizer.impl.OptimizerTest.before(OptimizerTest.java:55)
    at com.bekaert.handling.allocation.optimizer.impl.TestAllocationOptimizerImpl.activate(TestAllocationOptimizerImpl.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at java.lang.reflect.Method.invoke(Unknown Source)[:1.8.0_25]
    at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624)
    at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:376)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.initialize(BundleComponentActivator.java:172)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.<init>(BundleComponentActivator.java:120)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:258)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.access$000(Activator.java:45)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:185)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:479)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:414)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:443)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:869)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:790)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:515)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4429)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2100)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:976)[org.apache.felix.framework-4.4.1.jar:]
    at aQute.launcher.Launcher.update(Launcher.java:436)[biz.aQute.launcher-latest.jar:]
    at aQute.launcher.Launcher$1.run(Launcher.java:194)[biz.aQute.launcher-latest.jar:]
    at java.util.TimerThread.mainLoop(Unknown Source)[:1.8.0_25]
    at java.util.TimerThread.run(Unknown Source)[:1.8.0_25]
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Predicate not found by org.apache.servicemix.bundles.reflections [205]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1556)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:77)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1993)[org.apache.felix.framework-4.4.1.jar:]
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]
    ... 43 more

What I noticed is that in the org.apache.servicemix.bundles.reflections bundle the import-package com.google.common.base is optional.
This means it should even be able to work without that package?
I cannot remove the com.google.guava bundle, because it is required for the org.optaplanner.core bundle.

What other things can I try to make this work? Anyone else already managed to get optaplanner working in an osgi environment?

Best regards,
Sigi


问:
Looking for some Java good practice advice regarding distributed applications and message passing
Some background information. This is a distributed application with multiples nodes. A 'communication' thread sends and receives all messages sent between these nodes. This cannot be changed.

A 'doStuff' thread asks the 'communication' thread to send a message to a node. It then needs to wait for a response from the other node. The 'communication' thread will receive this response message. It then needs to deliver this message to the correct 'doStuff' thread.

I am unsure what sort of information needs to be stored at the node or within the message to ensure that the correct thread always receives the response message.

Looking for some advice upon how to achieve this. Thanks for reading :)

答:
You probably want to attach some sort of message id to the outgoing message to be included in the response. A sequential number or a UUID would probably do the job. Your communicator thread can then keep track (a map?) of what "doStuff" thread was waiting for a given response and pass it back.

You could also keep track of when the request was sent so that if a response isn't received the communicator thread can notify the doStuff thread that the response wasn't received.


问:
How to Seperate JSON data to display uniquely using Charts Library?
I am able to Display JSON data to show Line Chart using Charts Library.I have Displayed all marks and Subjects but I am trying to Display in TermWise.How can be JSON Data be Seperated using TermID?

```<code>import UIKit
import Charts
import Alamofire
import SwiftyJSON

class ViewController: UIViewController , ChartViewDelegate{

    @IBOutlet weak var text: UILabel!
    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var menu: UIBarButtonItem!
    var login_details : Login?
    var markdetail : [Marks] = []
    var markd : Marks?
    var myResponse  :   JSON    =   nil
//    var Subjects: [String] = []
    var subjectss : [String] = []
    var marks01 : [Double] = []
    var setname = String()

    let Subjects = ["eng" , "sci", "math", "soc"]
    let marks1 = [45,55,70,80]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        menu.target = self.revealViewController()

        menu.action = #selector(SWRevealViewController.revealToggle(_:))

        if self.revealViewController() != nil {

            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
            self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
        }

//        text.text = markd?.NAME

//        forlineView()
        getmarks()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func getmarks(){
        let student_id = login_details?.masterid
        let std_id_String = student_id?.replacingOccurrences(of: "[^0-9 ]", with: "", options: NSString.CompareOptions.regularExpression, range:nil)
        print("numberic",std_id_String!)

        let url = NSURL(string: "http://**********/api/academics//getSingleStudentsMarks"+"?StdID=" + std_id_String!)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        Alamofire.request(request).responseJSON(){ response in
            switch response.result{
            case.success(let data):
                print("success",data)

                let myresponse = JSON(data)
                for marks in myresponse.array!{
                    let marksObj = Marks(MarksJson: marks)
                    self.markdetail.append(marksObj)

                    self.subjectss.append(marksObj.CourseName)
                    self.marks01.append(marksObj.marks)
//                    for name in markdetail{
//
//                    }

                    self.setname.append(marksObj.examDescription)

                    print("Markss",marksObj.marks)
                    self.forlineView()
                    self.textdisplay()
                }

            case.failure(let error):
                print("Not Success",error)
            }

        }
    }

    func forlineView() {
        // 1
        self.lineChartView.delegate = self
        // 2
        self.lineChartView.chartDescription?.text = "Tap node for details"
        // 3
        self.lineChartView.chartDescription?.textColor = UIColor.red
        self.lineChartView.gridBackgroundColor = UIColor.darkGray
//        self.lineChartView.backgroundColor = UIColor.darkGray
        // 4
        self.lineChartView.noDataText = "No data provided"
        // 5
        setChartData(subject: subjectss)

    }

    func setChartData(subject : [String]) {

        // 1 - creating an array of data entries
        var yVals1 : [ChartDataEntry] = [ChartDataEntry]()

        for i in 0..<subject.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: Double(marks01[i])))
        }

        // 2 - create a data set with our array
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: setname)
        set1.axisDependency = .left // Line will correlate with left axis values
        set1.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set1.setCircleColor(UIColor.red) // our circle will be dark red
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0 // the radius of the node circle
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.red
        set1.highlightColor = UIColor.red
        set1.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)

        //4 - pass our months in for our x-axis label value along with our dataSets
        let data: LineChartData = LineChartData(dataSets: dataSets)
        data.setValueTextColor(UIColor.red)

        //5 - finally set our data
        self.lineChartView.data = data

        //6 - add x-axis label
        let xaxis = self.lineChartView.xAxis
        xaxis.valueFormatter = MyXAxisFormatter(subject)

    }

    func textdisplay(){
        for d in self.markdetail{

            self.text.text = d.NAME

        }
    }

}

class MyXAxisFormatter: NSObject, IAxisValueFormatter {

    let subjectss: [String]

    init(_ subjects: [String]) {
        self.subjectss = subjects
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return subjectss[Int(value) % subjectss.count]
    }

}
</code>```

currently i am getting

JSON

```<code> (
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 45;
        NAME = "Calvin Patterson";
        Sno = 2107;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 90;
        NAME = "Calvin Patterson";
        Sno = 2108;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 52;
        NAME = "Calvin Patterson";
        Sno = 2109;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 2110;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 50;
        NAME = "Calvin Patterson";
        Sno = 4119;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 60;
        NAME = "Calvin Patterson";
        Sno = 4120;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 4121;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 80;
        NAME = "Calvin Patterson";
        Sno = 4122;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    }
)
</code>```

required

I have displayed all JSON Data in charts.I want to Display marks and
  Subjects in TermWise .How it can be Done? I want to display marks and
  subjects in first term and Second, these terms have same subjects but
  marks are different and want to plot in same chart

Model class

```<code>class Marks {
    var classno = String()
    var class_id = String()
    var  course_id = String()
    var marks = Double()
    var Sno = String()
    var stdid = String()
    var TermID = String()
    var CourseName = String()
    var Terminal_FM = String()
    var Terminal_PM = String()
    var UT_FM = String()
    var UT_PM = String()
    var examDescription = String()
    var type =  String()
    var transferRate = String()
    var NAME = String()

    init(MarksJson:JSON) {
        self.classno = MarksJson["CLASSNO"].stringValue
        self.class_id = MarksJson["CLASS_ID"].stringValue
        self.course_id = MarksJson["CourseID"].stringValue
        self.marks = MarksJson["Marks"].double!
        self.Sno = MarksJson["Sno"].stringValue
        self.stdid = MarksJson["StdID"].stringValue
        self.TermID = MarksJson["TermID"].stringValue
        self.CourseName = MarksJson["CourseName"].stringValue
        self.Terminal_FM = MarksJson["Terminal_FM"].stringValue
        self.Terminal_PM = MarksJson["Terminal_PM"].stringValue
        self.UT_FM = MarksJson["UT_FM"].stringValue
        self.UT_PM = MarksJson["UT_PM"].stringValue
        self.examDescription = MarksJson["examDescription"].stringValue
        self.type =  MarksJson["type"].stringValue
        self.transferRate = MarksJson["transferRate"].stringValue
        self.NAME = MarksJson["NAME"].stringValue

    }

}
</code>```

答:
```<code>Change your code like this,

     for marks in myresponse.array!
        {
        let marksObj = Marks(MarksJson: marks)
        if marksObj.examDescription == "First Term"
        {
        self.markdetail.append(marksObj)
        self.subjectss.append(marksObj.CourseName)
        self.marks01.append(marksObj.marks)
        self.setname = marksObj.examDescription
        print("Markss",marksObj.marks)
        self.forlineView(examDescription: marksObj.examDescription)
        self.textdisplay(marks: marksObj)
        }
        else if marksObj.examDescription == "Second Term"
        {
        self.markdetailForSecondTerm.append(marksObj)
        self.subjectssForSecondTerm.append(marksObj.CourseName)
        self.marks01ForSecondTerm.append(marksObj.marks)
        self.setname = marksObj.examDescription
        print("Markss",marksObj.marks)
        self.forlineView(examDescription: marksObj.examDescription)
        self.textdisplay(marks: marksObj)
        }
        }
    }

    func forlineView(examDescription: String)
    {
        if examDescription ==  "First Term"
        {
            // 1
            self.lineChartView.delegate = self
            // 2
            self.lineChartView.chartDescription?.text = "Tap node for details"
            // 3
            self.lineChartView.chartDescription?.textColor = UIColor.red
            self.lineChartView.gridBackgroundColor = UIColor.darkGray
            //        self.lineChartView.backgroundColor = UIColor.darkGray
            // 4
            self.lineChartView.noDataText = "No data provided"
            // 5
            setChartData(subject: subjectss,marks: marks01,exam: examDescription)
        }
        else if examDescription ==  "Second Term"
        {
            // 1
            self.lineChartView.delegate = self
            // 2
            self.lineChartView.chartDescription?.text = "Tap node for details"
            // 3
            self.lineChartView.chartDescription?.textColor = UIColor.green
            self.lineChartView.gridBackgroundColor = UIColor.darkGray
            //        self.lineChartView.backgroundColor = UIColor.darkGray
            // 4
            self.lineChartView.noDataText = "No data provided"
            // 5
            setChartData(subject: subjectssForSecondTerm,marks: marks01ForSecondTerm,exam: examDescription)
        }
    }

    func setChartData(subject : [String], marks : [Double], exam: String) {

    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    if (exam == "First Term")
    {

        for i in 0..<subject.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: Double(marks[i])))
        }
        // 2 - create a data set with our array
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: "First Term")
        set1.axisDependency = .left // Line will correlate with left axis values
        set1.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set1.setCircleColor(UIColor.red) // our circle will be dark red
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0 // the radius of the node circle
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.red
        set1.highlightColor = UIColor.red
        set1.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        dataSets.append(set1)

        //4 - pass our months in for our x-axis label value along with our dataSets

    }

    else if (exam == "Second Term")
    {
        var yVals2 : [ChartDataEntry] = [ChartDataEntry]()
        for i in 0..<subject.count {
            yVals2.append(ChartDataEntry(x: Double(i), y: Double(marks[i])))
        }
        // 2 - create a data set with our array
        let set2: LineChartDataSet = LineChartDataSet(values: yVals2, label: "Second Term")
        set2.axisDependency = .left // Line will correlate with left axis values
        set2.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set2.setCircleColor(UIColor.red) // our circle will be dark red
        set2.lineWidth = 2.0
        set2.circleRadius = 6.0 // the radius of the node circle
        set2.fillAlpha = 65 / 255.0
        set2.fillColor = UIColor.red
        set2.highlightColor = UIColor.red
        set2.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        dataSets.append(set2)

    }

    let data: LineChartData = LineChartData(dataSets: dataSets)
    data.setValueTextColor(UIColor.red)

    //5 - finally set our data
    self.lineChartView.data = data

    //6 - add x-axis label
    let xaxis = self.lineChartView.xAxis
    xaxis.valueFormatter = MyXAxisFormatter(subject)

}

    func textdisplay(markDetails: [Marks]){
        for d in self.markDetails{

            self.text.text = d.NAME

        }
    }
</code>```

Body:
I am able to Display JSON data to show Line Chart using Charts Library.I have Displayed all marks and Subjects but I am trying to Display in TermWise.How can be JSON Data be Seperated using TermID?

import UIKit
import Charts
import Alamofire
import SwiftyJSON

class ViewController: UIViewController , ChartViewDelegate{

    @IBOutlet weak var text: UILabel!
    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var menu: UIBarButtonItem!
    var login_details : Login?
    var markdetail : [Marks] = []
    var markd : Marks?
    var myResponse  :   JSON    =   nil
//    var Subjects: [String] = []
    var subjectss : [String] = []
    var marks01 : [Double] = []
    var setname = String()

    let Subjects = ["eng" , "sci", "math", "soc"]
    let marks1 = [45,55,70,80]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        menu.target = self.revealViewController()

        menu.action = #selector(SWRevealViewController.revealToggle(_:))

        if self.revealViewController() != nil {

            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
            self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
        }

//        text.text = markd?.NAME

//        forlineView()
        getmarks()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func getmarks(){
        let student_id = login_details?.masterid
        let std_id_String = student_id?.replacingOccurrences(of: "[^0-9 ]", with: "", options: NSString.CompareOptions.regularExpression, range:nil)
        print("numberic",std_id_String!)

        let url = NSURL(string: "http://**********/api/academics//getSingleStudentsMarks"+"?StdID=" + std_id_String!)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        Alamofire.request(request).responseJSON(){ response in
            switch response.result{
            case.success(let data):
                print("success",data)

                let myresponse = JSON(data)
                for marks in myresponse.array!{
                    let marksObj = Marks(MarksJson: marks)
                    self.markdetail.append(marksObj)

                    self.subjectss.append(marksObj.CourseName)
                    self.marks01.append(marksObj.marks)
//                    for name in markdetail{
//
//                    }

                    self.setname.append(marksObj.examDescription)

                    print("Markss",marksObj.marks)
                    self.forlineView()
                    self.textdisplay()
                }

            case.failure(let error):
                print("Not Success",error)
            }

        }
    }

    func forlineView() {
        // 1
        self.lineChartView.delegate = self
        // 2
        self.lineChartView.chartDescription?.text = "Tap node for details"
        // 3
        self.lineChartView.chartDescription?.textColor = UIColor.red
        self.lineChartView.gridBackgroundColor = UIColor.darkGray
//        self.lineChartView.backgroundColor = UIColor.darkGray
        // 4
        self.lineChartView.noDataText = "No data provided"
        // 5
        setChartData(subject: subjectss)

    }

    func setChartData(subject : [String]) {

        // 1 - creating an array of data entries
        var yVals1 : [ChartDataEntry] = [ChartDataEntry]()

        for i in 0..<subject.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: Double(marks01[i])))
        }

        // 2 - create a data set with our array
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: setname)
        set1.axisDependency = .left // Line will correlate with left axis values
        set1.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set1.setCircleColor(UIColor.red) // our circle will be dark red
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0 // the radius of the node circle
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.red
        set1.highlightColor = UIColor.red
        set1.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)

        //4 - pass our months in for our x-axis label value along with our dataSets
        let data: LineChartData = LineChartData(dataSets: dataSets)
        data.setValueTextColor(UIColor.red)

        //5 - finally set our data
        self.lineChartView.data = data

        //6 - add x-axis label
        let xaxis = self.lineChartView.xAxis
        xaxis.valueFormatter = MyXAxisFormatter(subject)

    }

    func textdisplay(){
        for d in self.markdetail{

            self.text.text = d.NAME

        }
    }

}

class MyXAxisFormatter: NSObject, IAxisValueFormatter {

    let subjectss: [String]

    init(_ subjects: [String]) {
        self.subjectss = subjects
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return subjectss[Int(value) % subjectss.count]
    }

}

currently i am getting

JSON

 (
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 45;
        NAME = "Calvin Patterson";
        Sno = 2107;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 90;
        NAME = "Calvin Patterson";
        Sno = 2108;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 52;
        NAME = "Calvin Patterson";
        Sno = 2109;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 2110;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 50;
        NAME = "Calvin Patterson";
        Sno = 4119;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 60;
        NAME = "Calvin Patterson";
        Sno = 4120;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 4121;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 80;
        NAME = "Calvin Patterson";
        Sno = 4122;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    }
)

required

I have displayed all JSON Data in charts.I want to Display marks and
  Subjects in TermWise .How it can be Done? I want to display marks and
  subjects in first term and Second, these terms have same subjects but
  marks are different and want to plot in same chart

Model class

class Marks {
    var classno = String()
    var class_id = String()
    var  course_id = String()
    var marks = Double()
    var Sno = String()
    var stdid = String()
    var TermID = String()
    var CourseName = String()
    var Terminal_FM = String()
    var Terminal_PM = String()
    var UT_FM = String()
    var UT_PM = String()
    var examDescription = String()
    var type =  String()
    var transferRate = String()
    var NAME = String()

    init(MarksJson:JSON) {
        self.classno = MarksJson["CLASSNO"].stringValue
        self.class_id = MarksJson["CLASS_ID"].stringValue
        self.course_id = MarksJson["CourseID"].stringValue
        self.marks = MarksJson["Marks"].double!
        self.Sno = MarksJson["Sno"].stringValue
        self.stdid = MarksJson["StdID"].stringValue
        self.TermID = MarksJson["TermID"].stringValue
        self.CourseName = MarksJson["CourseName"].stringValue
        self.Terminal_FM = MarksJson["Terminal_FM"].stringValue
        self.Terminal_PM = MarksJson["Terminal_PM"].stringValue
        self.UT_FM = MarksJson["UT_FM"].stringValue
        self.UT_PM = MarksJson["UT_PM"].stringValue
        self.examDescription = MarksJson["examDescription"].stringValue
        self.type =  MarksJson["type"].stringValue
        self.transferRate = MarksJson["transferRate"].stringValue
        self.NAME = MarksJson["NAME"].stringValue

    }

}