问:
JavaFX Use Chart Legend to toggle show/hide Series possible?
Is it possible to use a chart's legend to toggle show/hide a series?

I got a LineChart with a legend and there are too many Series so you can't read out the information well. I was wondering if there is a possibility to use the legend to toggle the series to show/hide?

Most of the names of my Series are pretty long and it looks very weird if they are written twice once in the legend so you know which color belongs to which Series and a second time besides a CheckBox to toggle them.

Edit1: Maybe I was unclear, even if there is no built in function for this, I could use some input for how a workaround could look like, because I can't come up with anything.

答:
For reference, a similar approach works with JFreeChart in JavaFX as shown here. Adapted from this example, the variation below adds a ChartMouseListenerFX to the ChartViewer. Click on a series or its legend item to make a series invisible; click anywhere else to restore it.

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.LegendItemEntity;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.chart.fx.ChartViewer;
import org.jfree.chart.fx.interaction.ChartMouseEventFX;
import org.jfree.chart.fx.interaction.ChartMouseListenerFX;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * @see https://stackoverflow.com/a/44967809/230513
 * @see https://stackoverflow.com/a/43286042/230513
 */
public class VisibleTest extends Application {

    @Override
    public void start(Stage stage) {
        XYSeriesCollection dataset = new XYSeriesCollection();
        for (int i = 0; i < 3; i++) {
            XYSeries series = new XYSeries("value" + i);
            for (double t = 0; t < 2 * Math.PI; t += 0.5) {
                series.add(t, Math.sin(t) + i);
            }
            dataset.addSeries(series);
        }
        NumberAxis xAxis = new NumberAxis("domain");
        NumberAxis yAxis = new NumberAxis("range");
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, true);
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
        JFreeChart chart = new JFreeChart("Test", plot);
        ChartViewer viewer = new ChartViewer(chart);
        viewer.addChartMouseListener(new ChartMouseListenerFX() {
            @Override
            public void chartMouseClicked(ChartMouseEventFX e) {
                ChartEntity ce = e.getEntity();
                if (ce instanceof XYItemEntity) {
                    XYItemEntity item = (XYItemEntity) ce;
                    renderer.setSeriesVisible(item.getSeriesIndex(), false);
                } else if (ce instanceof LegendItemEntity) {
                    LegendItemEntity item = (LegendItemEntity) ce;
                    Comparable key = item.getSeriesKey();
                    renderer.setSeriesVisible(dataset.getSeriesIndex(key), false);
                } else {
                    for (int i = 0; i < dataset.getSeriesCount(); i++) {
                        renderer.setSeriesVisible(i, true);
                    }
                }
            }

            @Override
            public void chartMouseMoved(ChartMouseEventFX e) {}
        });
        stage.setScene(new Scene(viewer));
        stage.setTitle("JFreeChartFX");
        stage.setWidth(640);
        stage.setHeight(480);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
For reference, a similar approach works with JFreeChart in JavaFX as shown here. Adapted from this example, the variation below adds a ChartMouseListenerFX to the ChartViewer. Click on a series or its legend item to make a series invisible; click anywhere else to restore it.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.LegendItemEntity;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.chart.fx.ChartViewer;
import org.jfree.chart.fx.interaction.ChartMouseEventFX;
import org.jfree.chart.fx.interaction.ChartMouseListenerFX;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * @see https://stackoverflow.com/a/44967809/230513
 * @see https://stackoverflow.com/a/43286042/230513
 */
public class VisibleTest extends Application {

    @Override
    public void start(Stage stage) {
        XYSeriesCollection dataset = new XYSeriesCollection();
        for (int i = 0; i < 3; i++) {
            XYSeries series = new XYSeries("value" + i);
            for (double t = 0; t < 2 * Math.PI; t += 0.5) {
                series.add(t, Math.sin(t) + i);
            }
            dataset.addSeries(series);
        }
        NumberAxis xAxis = new NumberAxis("domain");
        NumberAxis yAxis = new NumberAxis("range");
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, true);
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
        JFreeChart chart = new JFreeChart("Test", plot);
        ChartViewer viewer = new ChartViewer(chart);
        viewer.addChartMouseListener(new ChartMouseListenerFX() {
            @Override
            public void chartMouseClicked(ChartMouseEventFX e) {
                ChartEntity ce = e.getEntity();
                if (ce instanceof XYItemEntity) {
                    XYItemEntity item = (XYItemEntity) ce;
                    renderer.setSeriesVisible(item.getSeriesIndex(), false);
                } else if (ce instanceof LegendItemEntity) {
                    LegendItemEntity item = (LegendItemEntity) ce;
                    Comparable key = item.getSeriesKey();
                    renderer.setSeriesVisible(dataset.getSeriesIndex(key), false);
                } else {
                    for (int i = 0; i < dataset.getSeriesCount(); i++) {
                        renderer.setSeriesVisible(i, true);
                    }
                }
            }

            @Override
            public void chartMouseMoved(ChartMouseEventFX e) {}
        });
        stage.setScene(new Scene(viewer));
        stage.setTitle("JFreeChartFX");
        stage.setWidth(640);
        stage.setHeight(480);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


来源: stackexchange

问:
ÅÄÖ gets out wrong in sending from a form
Im trying to get my mails from a form right with Swedish ÅÄÖåäö but it comes out wrong in mails. Anyone?
The server is set to UTF8
My header is:

```<code><?php header('Content-Type: text/html; charset=iso-8859-1'); ?>
<html>
<head>
<title>xxxxxx</title>
</head>
<body bgcolor="#CCCCCC">
<table align="center" border="0">
<tr><td>
</html>
</code>```

My mail.inc.php is coded like this:

```<code><?php header("Content-Type: text/html; charset=iso-8859-1");
function mail_file($to, $from, $subject, $body, $file) {
$boundary = md5(rand());
$headers = array(
    'MIME-Version: 1.0',
    //"Content-Type: multipart/mixed; charset=iso-8859-1; boundary=\"{$boundary}\"", - 170707
    "Content-Type: multipart/mixed; boundary=\"{$boundary}\"",
    "From: {$from}"
);
$message = array(
    "--{$boundary}",
    'Content-Type: text/HTML; charset=iso-8859-1',
    'Content-Transfer-Encoding: quoted-printable',
    '',
    quoted_printable_encode($body),         '',
    "--{$boundary}",
    "Content-Type: {$file['type']}; name=\"{$file['name']}\"",
    "Content-Disposition: attachment; filename=\"{$file['name']}\"",
    "Content-Transfer-Encoding: base64",
    '',
    chunk_split(base64_encode(file_get_contents($file['tmp_name']))),
    "--{$boundary}--",
    '',
);
mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));
}
?>
</code>```

This drives me nuts. Please help

答:
i don't know if its best way to archive
Try this before your mail() function $subject like that

$subject = '=?UTF-8?B?'.base64_encode($subject).'?=';

and then send mail

mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));

OR

mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', implode("\r\n", $message), implode("\r\n", $headers));

ContentLicense: CC BY-SA 3.0

Body:
Im trying to get my mails from a form right with Swedish ÅÄÖåäö but it comes out wrong in mails. Anyone?
The server is set to UTF8
My header is:

<?php header('Content-Type: text/html; charset=iso-8859-1'); ?>

<title>xxxxxx</title>

My mail.inc.php is coded like this:

<?php header("Content-Type: text/html; charset=iso-8859-1");
function mail_file($to, $from, $subject, $body, $file) {
$boundary = md5(rand());
$headers = array(
    'MIME-Version: 1.0',
    //"Content-Type: multipart/mixed; charset=iso-8859-1; boundary=\"{$boundary}\"", - 170707
    "Content-Type: multipart/mixed; boundary=\"{$boundary}\"",
    "From: {$from}"
);
$message = array(
    "--{$boundary}",
    'Content-Type: text/HTML; charset=iso-8859-1',
    'Content-Transfer-Encoding: quoted-printable',
    '',
    quoted_printable_encode($body),         '',
    "--{$boundary}",
    "Content-Type: {$file['type']}; name=\"{$file['name']}\"",
    "Content-Disposition: attachment; filename=\"{$file['name']}\"",
    "Content-Transfer-Encoding: base64",
    '',
    chunk_split(base64_encode(file_get_contents($file['tmp_name']))),
    "--{$boundary}--",
    '',
);
mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));
}
?>

This drives me nuts. Please help


问:
Can't move a file in python? Errno 13- Permission Denied
this is my code:

```<code>def unpack(folders):
for folder in folders:
    files = os.listdir(folder)
    print (files)
    while len(os.listdir(folder)) != 0:
        for file in files:
            if os.path.isdir(file)==False:
                print (file)
                shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
            else:
                unpack(file)

    if len(os.listdir(folder))==0:
        os.rmdir(folder)
</code>```

When I call this on the directory this program is in, everything works fine, but I can't copy a file called 'desktop.ini'. This is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 544, in move
    os.rename(src, real_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 37, in <module>
    unpack(folders_list)
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 30, in unpack
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 558, in move
    copy_function(src, real_dst)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 257, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 121, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'
</code>```

I'm guessing this is a system file or something. How do I get past this? It's not completely necessary to move the file, skipping it is fine.

答:
Your error already contains all information needed: FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'.

A desktop.ini file is a hidden system file on Windows, containing Information about special appearances or names of folders.

An example content from a desktop.ini file in my Documents folder:

```<code>[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235
</code>```

You can see it contains information about a localized Name (on a German Windows it is automatically displayed as Dokumente), a special Icon and sometimes properties of "virutal folders". This means you should not try to move around these files, as they could break the proper appearance and properties of folders (think about the recycle bin).

As there are lots of desktop.ini files on an average windows system, it is not uncommon to run into this kind of problem. On my system, there are currently 166 such files:

```<code>>>> from glob import glob
>>> print(len(glob(r"c:\**\desktop.ini", recursive=True)))
166
</code>```

Personally I would suggest the same as Nuageux - just try to move and log/ignore errors:

```<code>try:
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
except FileExistsError as e:
    print("The file {} already exists. Error message: {}".format(os.path.join(cur_dir,file), e))
</code>```

Another way would be to check for every file, if its name is desktop.ini.

Body:
this is my code:

def unpack(folders):
for folder in folders:
    files = os.listdir(folder)
    print (files)
    while len(os.listdir(folder)) != 0:
        for file in files:
            if os.path.isdir(file)==False:
                print (file)
                shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
            else:
                unpack(file)

    if len(os.listdir(folder))==0:
        os.rmdir(folder)

When I call this on the directory this program is in, everything works fine, but I can't copy a file called 'desktop.ini'. This is the error:

Traceback (most recent call last):
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 544, in move
    os.rename(src, real_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 37, in <module>
    unpack(folders_list)
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 30, in unpack
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 558, in move
    copy_function(src, real_dst)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 257, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 121, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

I'm guessing this is a system file or something. How do I get past this? It's not completely necessary to move the file, skipping it is fine.

Body:
Your error already contains all information needed: FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'.

A desktop.ini file is a hidden system file on Windows, containing Information about special appearances or names of folders.

An example content from a desktop.ini file in my Documents folder:

[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235

You can see it contains information about a localized Name (on a German Windows it is automatically displayed as Dokumente), a special Icon and sometimes properties of "virutal folders". This means you should not try to move around these files, as they could break the proper appearance and properties of folders (think about the recycle bin).

As there are lots of desktop.ini files on an average windows system, it is not uncommon to run into this kind of problem. On my system, there are currently 166 such files:

>>> from glob import glob
>>> print(len(glob(r"c:\**\desktop.ini", recursive=True)))
166

Personally I would suggest the same as Nuageux - just try to move and log/ignore errors:

try:
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
except FileExistsError as e:
    print("The file {} already exists. Error message: {}".format(os.path.join(cur_dir,file), e))

Another way would be to check for every file, if its name is desktop.ini.


问:
How is Jersey framework implement JAX-RS API in REST?
I know there are a lot of answers on this questions , but i am still confused about difference between JAX-RS API(the specification), and Jersey framework( reference implementation).

I read that:

Jersey framework basically uses com.sun.jersey.spi.container.servlet.ServletContainer servlet to intercept all the incoming requests. As we configure in our projects web.xml, that all the incoming rest request should be handled by that servlet. There is an init-param that is configured with the jersey servlet to find your REST service classes. REST service classes are not Servlet and they need NOT to extend the HttpServlet as you did in your code. These REST service classes are simple POJOs annotated to tell the jersey framework about different properties such as path, consumes, produces etc. When you return from your service method, jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream

My question is when you say :" jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream",  what you mean by jersey , what is actual class or library  that handles objects .

I am confused when i read that jersey is the engine that handles JAX-RS API specification. Can someone please explain what exactly is behind word jersey in this sentence? What actual class from Jersey do do the job of processing requests and responses in Jersey?

答:
You already pointed that JAX-RS is a specification and Jersey is the implementation which is how is Java especially Java EE work, maybe this article can explain more better.

To summarize JAX-RS is just a specification, there is no real implementation. The real implementation was done by Jersey and other library that following JAX-RS specification.


问:
Can I git checkout from GitHub Desktop?
Is there a way to rewrite repository directory files to current branch state in GitHub Desktop?

Or can I only do it from command line with git checkout mybranch

and does GitHub Desktop keep all files of all branches in directory?

答: To do git checkout mybranch on Github Desktop, you simply click on the dropdown menu on the upper left hand corner of the client, and pick the branch you want to switch to. It manages files exactly like git does, so all files are stored in their respective branches.

ContentLicense: CC BY-SA 4.0

Title: Can I git checkout from GitHub Desktop?


问:
C++ struct pointers
my code is not working. I have an error of -fpermissive ("invalid conversion from 'int' to 'persona*' [-fpermessive]").
Can you help me? This is my first real program, sorry for the errors and the bad english.

```<code>    #include <iostream>

using namespace std;

struct persona
{
    char nome[20];
    unsigned int eta;
    unsigned int altezza;
    unsigned int peso;
};

int totale = 0;
struct persona prs[100];

void leggere_dati(persona* prs)
{
    cout << "Persona numero: " << (totale + 1) << endl;
    cout << "Nome: " << prs->nome << endl;
    cout << "Eta': " << prs->eta << endl;
    cout << "Altezza: " << prs->altezza << endl;
    cout << "Peso: " << prs->peso << endl;
    cout << "-----------------------------------------------\n";
}

void inserire_dati(persona* prs)
{
    cout << "Nome? ";
    cin >> prs -> nome;
    cout << "\nEta'? ";
    cin >> prs -> eta;
    cout << "\nAltezza? ";
    cin >> prs -> altezza;
    cout << "\nPeso? ";
    cin >> prs -> peso;
}

int main()
{
     int risposte = 0;
    char risp = 0;

        do{
        inserire_dati(totale);
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
        if (risp == 'S')
    {
        risposte += 1;
        totale++;
        continue;
    }
    } while (risp == 's' || risp == 'S');

    if (risp == 'n' || risp == 'N')
    {
        for (totale = 0; totale <=  risposte; totale++)
            leggere_dati(totale);
    }
}
</code>```

答:
You are calling:

```<code> inserire_dati(totale);
</code>```

Defined as:

```<code>void inserire_dati(persona* prs);
</code>```

While totale is:

```<code>int totale = 0;
</code>```

That is the obvious error. But the background problem is that you don't have an object of the persona structure to read the data in. As I understand your code, that line should be:

```<code>inserire_dati(&prs[totale]);
</code>```

You are accepting a pointer to the persona structure in that function, which is correct, since you are going to modify the structure's contents. totale holds the last position occupied (I think, but you should increment totale unconditionally). In order to get a pointer to the structure you use &, preceded with the object, which is prs[totale]. Since the name of the vector is a pointer to its beginning, prs + totale is also acceptable. In that case, you would be using pointer arithmetic, which is less readable.

Also, I don't understand the last part of main().

Finally, if you are really using C++, there is no real reason to use char[] instead of string.

The complete main() becomes:

```<code>int main()
{
    char risp = 0;

    do {
        inserire_dati(&prs[totale]);
        ++totale;
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
    } while (risp == 's' || risp == 'S');

    for(int i = 0; i < totale; ++i) {
         leggere_dati(&prs[totale]);
    }
}
</code>```

But, well, getting further, I see you are using totale as a global variable. I'd wrap totale and prs in a whole structure.

```<code>struct personas {
    static const int Max = 100;
    struct prs[Max];
    int totale;
};
</code>```

And a few other changes which you can find in IDEOne.

Hope this helps.

Title: C++ struct pointers

Body:
my code is not working. I have an error of -fpermissive ("invalid conversion from 'int' to 'persona*' [-fpermessive]").
Can you help me? This is my first real program, sorry for the errors and the bad english.

    #include <iostream>

using namespace std;

struct persona
{
    char nome[20];
    unsigned int eta;
    unsigned int altezza;
    unsigned int peso;
};

int totale = 0;
struct persona prs[100];

void leggere_dati(persona* prs)
{
    cout << "Persona numero: " << (totale + 1) << endl;
    cout << "Nome: " << prs->nome << endl;
    cout << "Eta': " << prs->eta << endl;
    cout << "Altezza: " << prs->altezza << endl;
    cout << "Peso: " << prs->peso << endl;
    cout << "-----------------------------------------------\n";
}

void inserire_dati(persona* prs)
{
    cout << "Nome? ";
    cin >> prs -> nome;
    cout << "\nEta'? ";
    cin >> prs -> eta;
    cout << "\nAltezza? ";
    cin >> prs -> altezza;
    cout << "\nPeso? ";
    cin >> prs -> peso;
}

int main()
{
     int risposte = 0;
    char risp = 0;

        do{
        inserire_dati(totale);
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
        if (risp == 'S')
    {
        risposte += 1;
        totale++;
        continue;
    }
    } while (risp == 's' || risp == 'S');

    if (risp == 'n' || risp == 'N')
    {
        for (totale = 0; totale <=  risposte; totale++)
            leggere_dati(totale);
    }
}

Body:
You are calling:

 inserire_dati(totale);

Defined as:

void inserire_dati(persona* prs);

While totale is:

int totale = 0;

That is the obvious error. But the background problem is that you don't have an object of the persona structure to read the data in. As I understand your code, that line should be:

inserire_dati(&prs[totale]);

You are accepting a pointer to the persona structure in that function, which is correct, since you are going to modify the structure's contents. totale holds the last position occupied (I think, but you should increment totale unconditionally). In order to get a pointer to the structure you use &, preceded with the object, which is prs[totale]. Since the name of the vector is a pointer to its beginning, prs + totale is also acceptable. In that case, you would be using pointer arithmetic, which is less readable.

Also, I don't understand the last part of main().

Finally, if you are really using C++, there is no real reason to use char[] instead of string.

The complete main() becomes:

int main()
{
    char risp = 0;

    do {
        inserire_dati(&prs[totale]);
        ++totale;
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
    } while (risp == 's' || risp == 'S');

    for(int i = 0; i < totale; ++i) {
         leggere_dati(&prs[totale]);
    }
}

But, well, getting further, I see you are using totale as a global variable. I'd wrap totale and prs in a whole structure.

struct personas {
    static const int Max = 100;
    struct prs[Max];
    int totale;
};

And a few other changes which you can find in IDEOne.

Hope this helps.


问:
Recommendations for open/source text indexing and search
I just discovered Lucene (Java library) and starting to read up on it.

I'm interesting in taking some works of literature (for example, Philo, Josephus), and indexing them, then doing the following types of analysis (similar to what some Bible software programs do):

1) find word x within 2 or 3 words of word y

2) find "work* of * hand*" - would find "works of your hands", "work of his hand" etc...

3) find literary patterns (also called "motiffs") such as they author uses the phrase "in that day".  (I think this might be the trickiest, might have to find all combinations of 2-7 word phrases then count them and rank them, only showing the top 25 for example).  This might show for example that Josephus like to use one sets of phrases, and Philo another.

Are there any open-source libraries that you would recommend?
My language preferences would probably be 1) Python, 2) C#, 3) Java.
Ideally no dependencies on any proprietary database.

Thanks,

Neal

答:
Lucene is the best one out there in my opinion in terms of popularity, community, activity and tooling. I suggest you look at Solr which is built on top of Lucene. Another open source indexing framework I found is Egothor which I am not sure what is the adoption rate.

And here is a survey that might be help you in choosing the right one.

Here you can find more open source and commercial libraries. I have seen few of them supporting bindings for more than 1 programming language. If you have decided to go with Lucene, then you might need Luke for your debugging purposes.

ContentLicense: CC BY-SA 2.5


问:
WPF How to simply updating the UI from another class
I have a problem when I used to Update a UI from another Class;

This is my Situation.

First I have this class called PersonalData

```<code>namespace WPF_APPLICATION

public class PersonalData
{
    private string iDNumber;
    private string firstName;

    public PersonalData()
    {

    }

    public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
        }
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
        }
    }
}
</code>```

And PersonalData was created by a FirstPage.xaml.cs

```<code>namespace WPF_APPLICATION

public partial class FirstPage
{

    PersonalData person;

    public FirstPage()
    {
        InitializeComponent();
        person = new PersonalData();
        person.IDNumber = "1659880";
    }

    private void firstBTN_Click(object sender, RoutedEventArgs e)
    {
        person.Firstname = "John";
    }

}
</code>```

and all I want is I want the Object person that created by FirstPage.xaml.cs will go to Update UI to another page (Such as SeconePage.xaml, ThirdPage.xaml) every time button clicked or property changed.

I've tried an INotifyPropertyChanged but it doesn't work, maybe I missed some concept of WPF.

This is my SeconePage.xaml that I've tried.

```<code><Page x:Class="WPF_APPLICATION.SeconePage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WPF_APPLICATION"
  xmlns:m="clr-namespace:WPF_APPLICATION"
  mc:Ignorable="d"
  d:DesignHeight="240" d:DesignWidth="1080"
  Title="ScalePage">
<Page.Resources>
    <m:PersonalData x:Key="myperson"/>
</Page.Resources>

<Grid DataContext="{Binding Source={StaticResource myperson}}" Background="#eee">
    <TextBox x:Name="Value1" Text="{Binding IDNumber}"/>

    <TextBox x:Name="Value2" Text="{Binding FirstName}" Margin="0,40"/>
</Grid>

</Page>
</code>```

and Personal Class that Implement INotifypropertyChanged

```<code> namespace WPF_APPLICATION

public class PersonalData : INotifyPropertyChanged
{
    private string iDNumber;
    private string firstName;

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public PersonalData()
    {

    }

    public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
            OnPropertyChanged("IDNumber");
        }
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
}
</code>```

Thank you in advance.

答:
I can give you an ok solution and you can go with it BUT it is NOT the best way to solve your problem.

1. Open a new Window

To open a new Window you need an instance of the View for ex.:

```<code>SeconePage seconePage = new SeconePage();
</code>```

Now you are able to make the new Window  appear with the following code:

```<code>seconePage.Show();
</code>```

2. Perform code from step 1 OnPropertyChanged()

First create new Variable for the current Window:

```<code>public int currentWindow = 1;
</code>```

Then create a method for the Windows you want to show for ex.:

```<code> public void ShowNextWindow(int window)
    {
        switch (window)
        {
            case 2:
            SeconePage seconePage = new SeconePage();
            seconePage.Show();
            currentWindow += 1;
                break;
            case 3:
                ThirdPage thirdPage = new ThirdPage();
                thirdPage.Show();
                currentWindow += 1;
                break;
        }
    }
</code>```

Now go to your Personal Class and add ShowNextWindow(); to your setter. It should look something like this:

```<code>public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
            ShowNextWindow(currentWindow);
            OnPropertyChanged("IDNumber");
        }
    }
</code>```

Now if the value changes the next Window will be displayed.

3. Perform code from step 1 on Button.click()

Just perform ShowNextWindow(currentWindow); on the button which should switch the view.

Body:
I have a problem when I used to Update a UI from another Class;

This is my Situation.

First I have this class called PersonalData

namespace WPF_APPLICATION

public class PersonalData
{
    private string iDNumber;
    private string firstName;

    public PersonalData()
    {

    }

    public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
        }
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
        }
    }
}

And PersonalData was created by a FirstPage.xaml.cs

namespace WPF_APPLICATION

public partial class FirstPage
{

    PersonalData person;

    public FirstPage()
    {
        InitializeComponent();
        person = new PersonalData();
        person.IDNumber = "1659880";
    }

    private void firstBTN_Click(object sender, RoutedEventArgs e)
    {
        person.Firstname = "John";
    }

}

and all I want is I want the Object person that created by FirstPage.xaml.cs will go to Update UI to another page (Such as SeconePage.xaml, ThirdPage.xaml) every time button clicked or property changed.

I've tried an INotifyPropertyChanged but it doesn't work, maybe I missed some concept of WPF.

This is my SeconePage.xaml that I've tried.

<Page x:Class="WPF_APPLICATION.SeconePage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WPF_APPLICATION"
  xmlns:m="clr-namespace:WPF_APPLICATION"
  mc:Ignorable="d"
  d:DesignHeight="240" d:DesignWidth="1080"
  Title="ScalePage">
<Page.Resources>
    <m:PersonalData x:Key="myperson"/>
</Page.Resources>

<Grid DataContext="{Binding Source={StaticResource myperson}}" Background="#eee">
    <TextBox x:Name="Value1" Text="{Binding IDNumber}"/>

    <TextBox x:Name="Value2" Text="{Binding FirstName}" Margin="0,40"/>
</Grid>

</Page>

and Personal Class that Implement INotifypropertyChanged

 namespace WPF_APPLICATION

public class PersonalData : INotifyPropertyChanged
{
    private string iDNumber;
    private string firstName;

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public PersonalData()
    {

    }

    public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
            OnPropertyChanged("IDNumber");
        }
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
}

Thank you in advance.

Body:
I can give you an ok solution and you can go with it BUT it is NOT the best way to solve your problem.

1. Open a new Window

To open a new Window you need an instance of the View for ex.:

SeconePage seconePage = new SeconePage();

Now you are able to make the new Window  appear with the following code:

seconePage.Show();

2. Perform code from step 1 OnPropertyChanged()

First create new Variable for the current Window:

public int currentWindow = 1;

Then create a method for the Windows you want to show for ex.:

 public void ShowNextWindow(int window)
    {
        switch (window)
        {
            case 2:
            SeconePage seconePage = new SeconePage();
            seconePage.Show();
            currentWindow += 1;
                break;
            case 3:
                ThirdPage thirdPage = new ThirdPage();
                thirdPage.Show();
                currentWindow += 1;
                break;
        }
    }

Now go to your Personal Class and add ShowNextWindow(); to your setter. It should look something like this:

public string IDNumber
    {
        get
        {
            return iDNumber;
        }

        set
        {
            iDNumber = value;
            ShowNextWindow(currentWindow);
            OnPropertyChanged("IDNumber");
        }
    }

Now if the value changes the next Window will be displayed.

3. Perform code from step 1 on Button.click()

Just perform ShowNextWindow(currentWindow); on the button which should switch the view.


问:
OpenCV: can't get segmentation of image using k-means
Before going into deep of my question, I want you to know that I've read other posts on this forum, but none regards my problem.
In particular, the post here answers the question "how to do this?" with k-means, while I already know that I have to use it and I'd like to know why my implementation doesn't work.

I want to use k-means algorithm to divide pixels of an input image into clusters, according to their color. Then, after completing such task, I want each pixel to have the color of the center of the cluster it's been assigned to.
Taking as reference the OpenCV examples and other stuff retrieved on the web, I've designed the following code:

```<code>#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main( int argc, char** argv )
{

    Mat src = imread( argv[1], 1 );

    // reshape matrix
    Mat resized(src.rows*src.cols, 3, CV_8U);
    int row_counter = 0;

    for(int i = 0; i<src.rows; i++)
    {
        for(int j = 0; j<src.cols; j++)
        {
            Vec3b channels = src.at<Vec3b>(i,j);
            resized.at<char>(row_counter,0) = channels(0);
            resized.at<char>(row_counter,1) = channels(1);
            resized.at<char>(row_counter,2) = channels(2);

            row_counter++;
        }
    }

    //cout << src << endl;

    // change data type
    resized.convertTo(resized, CV_32F);

    // determine termination criteria and number of clusters
    TermCriteria criteria(TermCriteria::COUNT + TermCriteria::EPS, 10, 1.0);
    int K = 8;

    // apply k-means
    Mat labels, centers;
    double compactness = kmeans(resized, K, labels, criteria, 10, KMEANS_RANDOM_CENTERS, centers);

    // change data type in centers
    centers.convertTo(centers, CV_8U);

    // create output matrix
    Mat result = Mat::zeros(src.rows, src.cols, CV_8UC3);

    row_counter = 0;
    int matrix_row_counter = 0;
    while(row_counter < result.rows)
    {
        for(int z = 0; z<result.cols; z++)
        {
            int index = labels.at<char>(row_counter+z, 0);
            //cout << index << endl;
            Vec3b center_channels(centers.at<char>(index,0),centers.at<char>(index,1), centers.at<char>(index,2));
            result.at<Vec3b>(matrix_row_counter, z) = center_channels;
        }

        row_counter += result.cols;
        matrix_row_counter++;
    }

    cout << "Labels " << labels.rows << " " << labels.cols << endl;
    //cvtColor( src, gray, CV_BGR2GRAY );
    //gray.convertTo(gray, CV_32F);

    imshow("Result", result);
    waitKey(0);

    return 0;
}
</code>```

Anyway, at the end of computation, I simply get a black image.
Do you know why?
Strangely, if I initialize result matrix as

```<code>Mat result(src.size(), src.type())
</code>```

at the end of algorithm it will display exactly the input image, without any segmentation.

In particular, I have two doubts:

1) is it correct to lay the RGB values of a pixel on each row of matrix resized the way I've done it? is there a way to do it without a loop?

2) what's exactly the content of centers, after k-means function finishes working? it's a 3 columns matrix, does it contains the RGB values of clusters' centers?

thanks for support.

答:
 -The below posted OpenCV program assigns the user preferred color to a particular pixel value in an image

-ScanImageAndReduceC() is a predefined method in OpenCV to scan through all the pixels of an Image

-I.atuchar>(10, 10) = 255;  is used to access a particular pixel value of an image

Here is the code:

Mat& ScanImageAndReduceC(Mat& I)
{

// accept only char type matrices
CV_Assert(I.depth() == CV_8U);

```int channels = I.channels();

int nRows = I.rows;
int nCols = I.cols * channels;

if (I.isContinuous())
{
    nCols *= nRows;
    nRows = 1;
}

int i, j;
uchar* p;
for (i = 0; i < nRows; ++i)
{
    p = I.ptr<uchar>(i);
    for (j = 0; j < nCols; ++j)
    {
        I.at<uchar>(10, 10) = 255;
    }
}
return I;
</code>```

}

-------Main Program-------

  Calling the above method in our main program

```diff = ScanImageAndReduceC(diff);

namedWindow("Difference", WINDOW_AUTOSIZE);// Create a window for display.
imshow("Difference", diff);                   // Show our image inside it.

waitKey(0);                                          // Wait for a keystroke in the window
return 0;
</code>```

}

Body:
Before going into deep of my question, I want you to know that I've read other posts on this forum, but none regards my problem.
In particular, the post here answers the question "how to do this?" with k-means, while I already know that I have to use it and I'd like to know why my implementation doesn't work.

I want to use k-means algorithm to divide pixels of an input image into clusters, according to their color. Then, after completing such task, I want each pixel to have the color of the center of the cluster it's been assigned to.
Taking as reference the OpenCV examples and other stuff retrieved on the web, I've designed the following code:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main( int argc, char** argv )
{

    Mat src = imread( argv[1], 1 );

    // reshape matrix
    Mat resized(src.rows*src.cols, 3, CV_8U);
    int row_counter = 0;

    for(int i = 0; i<src.rows; i++)
    {
        for(int j = 0; j<src.cols; j++)
        {
            Vec3b channels = src.at<Vec3b>(i,j);
            resized.at<char>(row_counter,0) = channels(0);
            resized.at<char>(row_counter,1) = channels(1);
            resized.at<char>(row_counter,2) = channels(2);

            row_counter++;
        }
    }

    //cout << src << endl;

    // change data type
    resized.convertTo(resized, CV_32F);

    // determine termination criteria and number of clusters
    TermCriteria criteria(TermCriteria::COUNT + TermCriteria::EPS, 10, 1.0);
    int K = 8;

    // apply k-means
    Mat labels, centers;
    double compactness = kmeans(resized, K, labels, criteria, 10, KMEANS_RANDOM_CENTERS, centers);

    // change data type in centers
    centers.convertTo(centers, CV_8U);

    // create output matrix
    Mat result = Mat::zeros(src.rows, src.cols, CV_8UC3);

    row_counter = 0;
    int matrix_row_counter = 0;
    while(row_counter < result.rows)
    {
        for(int z = 0; z<result.cols; z++)
        {
            int index = labels.at<char>(row_counter+z, 0);
            //cout << index << endl;
            Vec3b center_channels(centers.at<char>(index,0),centers.at<char>(index,1), centers.at<char>(index,2));
            result.at<Vec3b>(matrix_row_counter, z) = center_channels;
        }

        row_counter += result.cols;
        matrix_row_counter++;
    }

    cout << "Labels " << labels.rows << " " << labels.cols << endl;
    //cvtColor( src, gray, CV_BGR2GRAY );
    //gray.convertTo(gray, CV_32F);

    imshow("Result", result);
    waitKey(0);

    return 0;
}

Anyway, at the end of computation, I simply get a black image.
Do you know why?
Strangely, if I initialize result matrix as

Mat result(src.size(), src.type())

at the end of algorithm it will display exactly the input image, without any segmentation.

In particular, I have two doubts:

1) is it correct to lay the RGB values of a pixel on each row of matrix resized the way I've done it? is there a way to do it without a loop?

2) what's exactly the content of centers, after k-means function finishes working? it's a 3 columns matrix, does it contains the RGB values of clusters' centers?

thanks for support.

Body:
 -The below posted OpenCV program assigns the user preferred color to a particular pixel value in an image

-ScanImageAndReduceC() is a predefined method in OpenCV to scan through all the pixels of an Image

-I.atuchar>(10, 10) = 255;  is used to access a particular pixel value of an image

Here is the code:

Mat& ScanImageAndReduceC(Mat& I)
{

// accept only char type matrices
CV_Assert(I.depth() == CV_8U);

int channels = I.channels();

int nRows = I.rows;
int nCols = I.cols * channels;

if (I.isContinuous())
{
    nCols *= nRows;
    nRows = 1;
}

int i, j;
uchar* p;
for (i = 0; i < nRows; ++i)
{
    p = I.ptr<uchar>(i);
    for (j = 0; j < nCols; ++j)
    {
        I.at<uchar>(10, 10) = 255;
    }
}
return I;

}

-------Main Program-------

  Calling the above method in our main program

diff = ScanImageAndReduceC(diff);

namedWindow("Difference", WINDOW_AUTOSIZE);// Create a window for display.
imshow("Difference", diff);                   // Show our image inside it.

waitKey(0);                                          // Wait for a keystroke in the window
return 0;

}


问:
DropDown menu with QtQuickControls2 on Qt application
on qt quick controls 2, how can I configure a button Item with a dropdown menu of others buttons. When the user click on this button is triggered onClicked signal and under the button should be open a dropdown menu with other buttons. I have try with ButtonGroup but I don't know if this is the best practice. There is some Controls2 item to be use? Thanks in advice

Best Regards
Daniele

答:
There is Menu  from QtQuick.Controls 2.0 that can do what you want.

Example taken from the documentation :

```<code>Button {
    id: fileButton
    text: "File"
    onClicked: menu.open()

    Menu {
        id: menu
        y: fileButton.height

        MenuItem {
            text: "New..."
        }
        MenuItem {
            text: "Open..."
        }
        MenuItem {
            text: "Save"
        }
    }
}
</code>```

Body:
There is Menu  from QtQuick.Controls 2.0 that can do what you want.

Example taken from the documentation :

Button {
    id: fileButton
    text: "File"
    onClicked: menu.open()

    Menu {
        id: menu
        y: fileButton.height

        MenuItem {
            text: "New..."
        }
        MenuItem {
            text: "Open..."
        }
        MenuItem {
            text: "Save"
        }
    }
}


问:
Desktop-like layout using Bootstrap
I'm developing a web application that should behave more or less like a desktop app, with the following features:

It must take all the browser space (100% width and height, no scrolling), with the following 4 main elements:

A header. It will contain the main menu. It must be fixed to top.

A left sidebar with an object pane.

The main content area, right to the sidebar, where it will display a grid and data. Must be scrollable when content is large.

A footer fixed to the bottom of the screen, only visible when the user double click on an object of the left sidebar. It also has to be collapsable by clicking on an 'X' button on the upper right border.

The tricky part is that, when I double click on an object, the footer (about 150-200px) must be visible and show the object data. Both the sidebar and the main content area must shrink in height so the footer doesn't overlap them, and they are back to full height when the user closes the footer.

Is it possible to do such a layout using Bootstrap framework? I've been playing around with it but I couldn't get it working correctly...

Thanks in advance, cheers!

答:
Sorry for posting such a generic question, I was tired after spending all the day doing tests on bootply without finding an appropiate solution so I decided to ask here.

I've decided to move from Bootstrap to Foundation, as it provides the exact feature I was looking for on its XY Grid. Using this framework, my application layout will be as simple as this:

```<code><div class="grid-y medium-grid-frame">
  <div class="cell shrink header medium-cell-block-container">

    <!-- NAVIGATION BAR -->

  </div>

  <div class="cell medium-auto medium-cell-block-container">

    <div class="grid-x grid-padding-x">
      <div class="cell medium-4 medium-cell-block-y">

        <!-- SIDEBAR -->

      </div>

      <div class="cell medium-8 medium-cell-block-y">

        <!-- MAIN CONTENT -->

      </div>
    </div>

  </div>

  <div class="cell shrink footer">

    <!-- FOOTER -->

  </div>
</div>
</code>```

I'll be more concise next time, cheers!

Title: Desktop-like layout using Bootstrap

Body:
Sorry for posting such a generic question, I was tired after spending all the day doing tests on bootply without finding an appropiate solution so I decided to ask here.

I've decided to move from Bootstrap to Foundation, as it provides the exact feature I was looking for on its XY Grid. Using this framework, my application layout will be as simple as this:

<div class="grid-y medium-grid-frame">
  <div class="cell shrink header medium-cell-block-container">

    <!-- NAVIGATION BAR -->

  </div>

  <div class="cell medium-auto medium-cell-block-container">

    <div class="grid-x grid-padding-x">
      <div class="cell medium-4 medium-cell-block-y">

        <!-- SIDEBAR -->

      </div>

      <div class="cell medium-8 medium-cell-block-y">

        <!-- MAIN CONTENT -->

      </div>
    </div>

  </div>

  <div class="cell shrink footer">

    <!-- FOOTER -->

  </div>
</div>

I'll be more concise next time, cheers!


问:
RxJava wait for the response to be retrieved before moving on
```<code>        getRemarks(licensePlate)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                Store.remarks(response);
            }, throwable -> {
                Timber.e("Error", throwable);
            });

    public static Observable<List<Remark>> getRemarks(String number) {
        return getApiService().getRemarks(number);
    }
</code>```

<p>So, for now this is my code but I need to wait until this method get the response before moving on with the code. As I saw I need .toBlocking (but it blocked my code indefinitely) and I read somewhere that I need .forEach method but don't know how to use it. </p>

答:
Instead of subscribe use:

```<code>.toBlocking()
.forEach(new Action1<List<Remark>>() {
    @Override
    public void call(List<Remark> remarks) {
        Store.remarks(remarks);
    }
});
</code>```

Anyway, unless you are using this for test, I would avoid to use toBlocking and I would look for a different strategy. toBlocking, indeed, returns a BlockingObservable that as the documentation says:

It can be useful for testing and demo purposes, but is
  generally inappropriate for production applications.

Consider to exploit the real power of RxJava, through the stream compositions. You can take a look here for understanding which are the available options for combining Observables

Body:
        getRemarks(licensePlate)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                Store.remarks(response);
            }, throwable -> {
                Timber.e("Error", throwable);
            });

    public static Observable<List<Remark>> getRemarks(String number) {
        return getApiService().getRemarks(number);
    }

So, for now this is my code but I need to wait until this method get the response before moving on with the code. As I saw I need .toBlocking (but it blocked my code indefinitely) and I read somewhere that I need .forEach method but don't know how to use it.

Body:
Instead of subscribe use:

.toBlocking()
.forEach(new Action1<List<Remark>>() {
    @Override
    public void call(List<Remark> remarks) {
        Store.remarks(remarks);
    }
});

Anyway, unless you are using this for test, I would avoid to use toBlocking and I would look for a different strategy. toBlocking, indeed, returns a BlockingObservable that as the documentation says:

It can be useful for testing and demo purposes, but is
  generally inappropriate for production applications.

Consider to exploit the real power of RxJava, through the stream compositions. You can take a look here for understanding which are the available options for combining Observables


问:
Limit iOS App even after the user re-installs it
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?

答:
You can handle this problem in a two different way.

Approach 1: Store identifer in the KeyChain

First check the value from keychain if the user already installed
the app on this device or not.

If it is first time install then provide the free coins and store the user id/flag in the keychain to identify future install.

You will lose this keychain data, if user reset their device.

After reset the device you will provide the coins again because your flag/identifier will not be there in the keychain.

If you want avoid this situation then you have to go with the second approach.

Approach 2: Store identifier on the server

Instead of storing the details on the device keychain. You have to save it on your server. App first launch you have to check with your server to provide the details.

This approach always works even user reset their device


问:
sql query for by periods
I will have 2 fields in my table, NEXTTIME and ENDTIME, the table name is VISIT.

I will get a value from my page which is 00:05:00 or sth like that. the minimum is 5 minute.

I will have to query from the database based on that value.

I will get the earliest NEXTTIME and that time + 00:05:00.

Let's say the earlist NEXTTIME is 06:44.

My query will be like 06:45, 06:50, and so on..

I will also have another input value which is interval time.

Nvm that.

I just wanna know how to get the query by interval.

The result would be looked like this.

NEXTTIME : ENDTIME

06:55:00 ~ 06:58:00

07:25:00 ~ 07:28:00

07:35:00 ~ 08:52:00

08:38:00 ~ 08:48:00

08:40:00 ~ 08:54:00

08:43:00 ~ 09:36:00

09:12:00 ~ 09:30:00

答:
Here's based on the information provided and my understanding of your question the solution I'm proposing. In order to meet the chart periods, only change the periods within both the select statements and the where clauses for each unioned query.

```<code>USE master
GO

create database Tests
GO

USE Tests
GO

create table Visits (
    nexttime    datetime    not null
    , endtime   datetime    not null
)
GO

BEGIN TRANSACTION

insert into Visits (nexttime, endtime) select N'06:55:00', N'06:58:00'
insert into Visits (nexttime, endtime) select N'07:25:00', N'07:28:00'
insert into Visits (nexttime, endtime) select N'07:35:00', N'08:52:00'
insert into Visits (nexttime, endtime) select N'08:38:00', N'08:48:00'
insert into Visits (nexttime, endtime) select N'08:40:00', N'08:54:00'
insert into Visits (nexttime, endtime) select N'08:43:00', N'09:36:00'
insert into Visits (nexttime, endtime) select N'09:12:00', N'09:30:00'

COMMIT

select N'06:30 - 07:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'06:30:00', 108) and CONVERT(datetime, N'07:00:00', 108)
union
select N'07:00 - 07:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'07:00:00', 108) and CONVERT(datetime, N'07:30:00', 108)
union
select N'07:30 - 08:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'07:30:00', 108) and CONVERT(datetime, N'08:00:00', 108)
union
select N'08:00 - 08:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'08:00:00', 108) and CONVERT(datetime, N'08:30:00', 108)
union
select N'08:30 - 09:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'08:30:00', 108) and CONVERT(datetime, N'09:00:00', 108)
union
select N'09:00 - 09:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'09:00:00', 108) and CONVERT(datetime, N'09:30:00', 108)
</code>```

Output

```<code>╔══════════════╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╗
║06:30 - 07:00 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║07:00 - 07:30 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║07:30 - 08:00 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 1 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║08:00 - 08:30 ║   ║   ║   ║   ║   ║   ║   ║   ║   ║   ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║08:30 - 09:00 ║ 1 ║ 2 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 1 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║09:00 - 09:30 ║ 0 ║ 0 ║ 1 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╚══════════════╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╝
</code>```

Feel free to say whether I have correctly understood your question or not.

Title: sql query for by periods

Body:
Here's based on the information provided and my understanding of your question the solution I'm proposing. In order to meet the chart periods, only change the periods within both the select statements and the where clauses for each unioned query.

USE master
GO

create database Tests
GO

USE Tests
GO

create table Visits (
    nexttime    datetime    not null
    , endtime   datetime    not null
)
GO

BEGIN TRANSACTION

insert into Visits (nexttime, endtime) select N'06:55:00', N'06:58:00'
insert into Visits (nexttime, endtime) select N'07:25:00', N'07:28:00'
insert into Visits (nexttime, endtime) select N'07:35:00', N'08:52:00'
insert into Visits (nexttime, endtime) select N'08:38:00', N'08:48:00'
insert into Visits (nexttime, endtime) select N'08:40:00', N'08:54:00'
insert into Visits (nexttime, endtime) select N'08:43:00', N'09:36:00'
insert into Visits (nexttime, endtime) select N'09:12:00', N'09:30:00'

COMMIT

select N'06:30 - 07:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'06:30:00', 108) and CONVERT(datetime, N'07:00:00', 108)
union
select N'07:00 - 07:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'07:00:00', 108) and CONVERT(datetime, N'07:30:00', 108)
union
select N'07:30 - 08:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'07:30:00', 108) and CONVERT(datetime, N'08:00:00', 108)
union
select N'08:00 - 08:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'08:00:00', 108) and CONVERT(datetime, N'08:30:00', 108)
union
select N'08:30 - 09:00' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'08:30:00', 108) and CONVERT(datetime, N'09:00:00', 108)
union
select N'09:00 - 09:30' as period
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 5 and 10 then 1 else 0 end) as [5:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 10 and 15 then 1 else 0 end) as [10:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 15 and 20 then 1 else 0 end) as [15:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 20 and 25 then 1 else 0 end) as [20:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 25 and 30 then 1 else 0 end) as [25:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 30 and 35 then 1 else 0 end) as [30:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 35 and 40 then 1 else 0 end) as [35:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 40 and 45 then 1 else 0 end) as [40:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) between 45 and 50 then 1 else 0 end) as [45:00]
    , SUM(case when DATEDIFF(MI, nexttime, endtime) >= 50 then 1 else 0 end) as [50:00]
from Visits
where nexttime between CONVERT(datetime, N'09:00:00', 108) and CONVERT(datetime, N'09:30:00', 108)

Output

╔══════════════╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╗
║06:30 - 07:00 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║07:00 - 07:30 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║07:30 - 08:00 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 1 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║08:00 - 08:30 ║   ║   ║   ║   ║   ║   ║   ║   ║   ║   ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║08:30 - 09:00 ║ 1 ║ 2 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 1 ║
╠══════════════╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣
║09:00 - 09:30 ║ 0 ║ 0 ║ 1 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
╚══════════════╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╝

Feel free to say whether I have correctly understood your question or not.


问:
AJAX script with json format data not working
My complete script is as follows

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(window).on('load',function(){
            $('#myModal').modal('show');
        });
    </script>
    <script>
        $( document ).ready(function () {
            $("#vote").click(function (e) {
                var poll_id = $('input[name=pollID]', '#myForm').val();
                var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
                //alert(poll_id + "AND" + poll_option_id);
                $.ajax({
                    type: "POST",
                    url: "http://localhost/poll/index.php/form/poll",
                    data: {poll_id: poll_id, poll_option_id: poll_option_id},
                    dataType: "json",
                    success: function(data) {
                        alert(data);
                    }, error: function() {
                        alert("ERROR");
                    }
                });
            });
        });
    </script>
</code>```

And I have the following inside poll function in form controller

```<code>public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}
</code>```

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

答:
I can see there are many javascript libraries included. Very sure some of them are conflicting.
Try this before $(document).ready():-

```<code>$.noConflict();
</code>```

After looking at your form controller code, I can see you are just returning a text. So ajax dataType should be HTML and not json. dataType parameter is to define the type of return value.
I can only see this one wrong point in your code. Your console response status is also fine, which means it is the dataType which is wrong.

dataType = The data type expected of the server response.

```<code>dataType:'html'
</code>```

Body:
My complete script is as follows

And I have the following inside poll function in form controller

public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

Body:
I can see there are many javascript libraries included. Very sure some of them are conflicting.
Try this before $(document).ready():-

$.noConflict();

After looking at your form controller code, I can see you are just returning a text. So ajax dataType should be HTML and not json. dataType parameter is to define the type of return value.
I can only see this one wrong point in your code. Your console response status is also fine, which means it is the dataType which is wrong.

dataType = The data type expected of the server response.

dataType:'html'


问:
Pause or stop the video when close icon is clicked
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

```

答:
Please change the

```<code>$('hideStr').click(function(){
    $("#playvideo").pause();       // Tag name used as a selector
});
</code>```

In the code the playvideo is mentioned as id not class.

Body:
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

Body:
Please change the

$('hideStr').click(function(){
    $("#playvideo").pause();       // Tag name used as a selector
});

In the code the playvideo is mentioned as id not class.


问:
iOS Charts remove decimal from yValues
How to remove decimals from y values in iOS Charts?
Im using the latest iOS Charts release with Swift3

答:
Could also use:</p>

```<code>let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)
data.setValueFormatter(formatter)
</code>```

Title: iOS Charts remove decimal from yValues

Body:
Could also use:

let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)
data.setValueFormatter(formatter)


问:
TabControl.SelectedIndex being changed, but SelectedIndexChanged even not firing
All,

I have a TabControl in an application that started behaving strangely.  Some background...

This program was converted from VB6 to VB .NET 2008, and used to refer to forms using their class names.  In other words, I might have a form class called frmFoo.  In the code for the program you might see:

```<code>frmFoo.Show()
</code>```

or

```<code>frmFoo.UserDefinedProperty = True
</code>```

During some recent changes, I created variables to represent instances of my forms much like these:

```<code>Public MyForm as frmFoo

MyForm = New frmFoo
MyForm.Show()
</code>```

In doing so, I also removed code from the form's Load event handler and put it in the form's constructor.

When the form loads, or when a document is loaded and should influence the TabControl's selected index, something like the following will not necessarily fire the SelectedIndexChanged event.

```<code>MyForm.tbsForm.SelectedIndex = ValueReadFromFile
</code>```

...or...

```<code>MyForm.tbsForm.Tabs(ValueReadFromFile).Select
</code>```

Sorry to be so wordy, but there's more.  If I open the form and look at the TabControl to verify that it's been set properly, everything works like it's supposed to.  The misbehaving TabControl is contained within another TabControl, so I have to click the parent TabControl to see it.  If I can see it, and run a test, the test always works.  If I can't see it, and run a test, the first test I run will not fire the event.  ...paging Dr. Heisenberg...

It's almost as if the control has to be initialized first by changing the value or making it visible onscreen...I'm totally lost on this one.  It's the most unusual behavior I've ever seen.  And everything worked perfectly before I began using variables to represent forms and placed the Load event code into the form constructors.

Can anyone help, or at least put me out of my misery?
SH

-------------------------------------------------------------- Edit #2

I just performed a test after having attempted to eliminate some of the variability in the behavior.  But I wanted to confirm the previously-stated behavior.

I opened the program and read a file.  This file contained a value that should have triggered the event handler.  Without making the control visible, I can change the SelectedIndex property of the tab control without the event firing.

I closed the program down again, and reopened it.  This time, selected the parent tab that allowed the child tab (the one whose event I'm concerned with) to become visible.  I then selected a different tab in the parent control, meaning that the child control was no longer visible.  When I opened the same file as before, it fired the event.

I'm tempted to implement a flag that confirms that the control has been repainted or whether the parent tab has been displayed.  I may have to fire the event in code if the flag isn't set.

I want to reiterate that everything worked when the program referred to the forms by their class names and much of the arrangement of controls on the forms was done in the load event.  Now the program creates variables and the arrangement of the controls is done in the form's constructor.  I'm sure this has something to do with the problem I'm having, but I can't understand how.  Any wisdom to share?

答:
```<code>MyForm.tbsForm.SelectedIndexChanged = ValueReadFromFile
</code>```

doesn't make a lot of sense.  Is tha trying to assign a handler to the SelectedIndexChanged event? or is ValueReadFromFile the name of the tab?

What you're saying is that you have two tab controls, say, A and B.  Tab control B is contained within a tab of A, and unless A has the tab page selected that contains the tab control B, the SelectedIndexChanged event of B will not fire if you change its tab programatically?

In which different ways have you tried to select a tab within the child tab control, and when is this code being executed?

Body:
All,

I have a TabControl in an application that started behaving strangely.  Some background...

This program was converted from VB6 to VB .NET 2008, and used to refer to forms using their class names.  In other words, I might have a form class called frmFoo.  In the code for the program you might see:

frmFoo.Show()

or

frmFoo.UserDefinedProperty = True

During some recent changes, I created variables to represent instances of my forms much like these:

Public MyForm as frmFoo

MyForm = New frmFoo
MyForm.Show()

In doing so, I also removed code from the form's Load event handler and put it in the form's constructor.

When the form loads, or when a document is loaded and should influence the TabControl's selected index, something like the following will not necessarily fire the SelectedIndexChanged event.

MyForm.tbsForm.SelectedIndex = ValueReadFromFile

...or...

MyForm.tbsForm.Tabs(ValueReadFromFile).Select

Sorry to be so wordy, but there's more.  If I open the form and look at the TabControl to verify that it's been set properly, everything works like it's supposed to.  The misbehaving TabControl is contained within another TabControl, so I have to click the parent TabControl to see it.  If I can see it, and run a test, the test always works.  If I can't see it, and run a test, the first test I run will not fire the event.  ...paging Dr. Heisenberg...

It's almost as if the control has to be initialized first by changing the value or making it visible onscreen...I'm totally lost on this one.  It's the most unusual behavior I've ever seen.  And everything worked perfectly before I began using variables to represent forms and placed the Load event code into the form constructors.

Can anyone help, or at least put me out of my misery?
SH

-------------------------------------------------------------- Edit #2

I just performed a test after having attempted to eliminate some of the variability in the behavior.  But I wanted to confirm the previously-stated behavior.

I opened the program and read a file.  This file contained a value that should have triggered the event handler.  Without making the control visible, I can change the SelectedIndex property of the tab control without the event firing.

I closed the program down again, and reopened it.  This time, selected the parent tab that allowed the child tab (the one whose event I'm concerned with) to become visible.  I then selected a different tab in the parent control, meaning that the child control was no longer visible.  When I opened the same file as before, it fired the event.

I'm tempted to implement a flag that confirms that the control has been repainted or whether the parent tab has been displayed.  I may have to fire the event in code if the flag isn't set.

I want to reiterate that everything worked when the program referred to the forms by their class names and much of the arrangement of controls on the forms was done in the load event.  Now the program creates variables and the arrangement of the controls is done in the form's constructor.  I'm sure this has something to do with the problem I'm having, but I can't understand how.  Any wisdom to share?

Body:
MyForm.tbsForm.SelectedIndexChanged = ValueReadFromFile

doesn't make a lot of sense.  Is tha trying to assign a handler to the SelectedIndexChanged event? or is ValueReadFromFile the name of the tab?

What you're saying is that you have two tab controls, say, A and B.  Tab control B is contained within a tab of A, and unless A has the tab page selected that contains the tab control B, the SelectedIndexChanged event of B will not fire if you change its tab programatically?

In which different ways have you tried to select a tab within the child tab control, and when is this code being executed?


问:
react-native init specify react version and react-native version
I basically want to init a react-native project with react@15.6.0 and react-native@0.45.0 because dependency problems. However react-native command only allows me to specify react-native version:

```<code>react-native init sample --version react-native@0.45.0
</code>```

This command not works:

```<code>react-native init diskful --version react-native@0.45.0 --version react@15.6.0
</code>```

This, too:

```<code>react-native init diskful --version react-native@0.45.0 react@15.6.0
</code>```

And this, too:

```<code>react-native init diskful --version react@15.6.0 react-native@0.45.0
</code>```

Install globally react@15.6.0 or react-native@0.45.0 does not affect.
Please, someone help me!

答:
Create a project :

```<code>react-native init MyNewApp --version 0.45.0
</code>```

If you want do change version then try with this:

```<code>npm install --save react-native@0.44.0
npm install --save react@16.0.0-alpha.6
</code>```

Body:
I basically want to init a react-native project with react@15.6.0 and react-native@0.45.0 because dependency problems. However react-native command only allows me to specify react-native version:

react-native init sample --version react-native@0.45.0

This command not works:

react-native init diskful --version react-native@0.45.0 --version react@15.6.0

This, too:

react-native init diskful --version react-native@0.45.0 react@15.6.0

And this, too:

react-native init diskful --version react@15.6.0 react-native@0.45.0

Install globally react@15.6.0 or react-native@0.45.0 does not affect.
Please, someone help me!

Body:
Create a project :

react-native init MyNewApp --version 0.45.0

If you want do change version then try with this:

npm install --save react-native@0.44.0
npm install --save react@16.0.0-alpha.6


问:
Image editing library crashes on devices running nougat
We're using a library to edit images. It works fine on devices running marshmallow and previous versions of Android but crashes on Android 7.0 with this error:

AndroidRuntime: FATAL EXCEPTION: Thread-56
Process: com.neon.android, PID: 21869
android.support.v8.renderscript.RSRuntimeException: Loading of ScriptC script failed.
at android.support.v8.renderscript.ScriptC.<init>(ScriptC.java:61)

However, the above error was addressed by setting these values to various properties in the build.gradle file and manifest:

```<code>compileSdkVersion 25
buildToolsVersion '25.0.2'
renderscriptTargetApi 23
android:targetSdkVersion="25"
</code>```

As a result of the above changes,the app works on 7.0 but crashes on all other versions of Android. How do i ensure that the library works on other versions as well?

If this helps in any way- the old values:

```<code>compileSdkVersion 23
buildToolsVersion "24.0.0"
renderscriptTargetApi 20
android:targetSdkVersion="22"
</code>```

答:
Problem was with the targetSdkVersion. Was targeting only 7.0 devices. Solved it by changing it to 22. Other values remain the same.

```<code>compileSdkVersion 25
buildToolsVersion '25.0.2'
renderscriptTargetApi 23
</code>```

Body:
We're using a library to edit images. It works fine on devices running marshmallow and previous versions of Android but crashes on Android 7.0 with this error:

AndroidRuntime: FATAL EXCEPTION: Thread-56
Process: com.neon.android, PID: 21869
android.support.v8.renderscript.RSRuntimeException: Loading of ScriptC script failed.
at android.support.v8.renderscript.ScriptC.<init>(ScriptC.java:61)

However, the above error was addressed by setting these values to various properties in the build.gradle file and manifest:

compileSdkVersion 25
buildToolsVersion '25.0.2'
renderscriptTargetApi 23
android:targetSdkVersion="25"

As a result of the above changes,the app works on 7.0 but crashes on all other versions of Android. How do i ensure that the library works on other versions as well?

If this helps in any way- the old values:

compileSdkVersion 23
buildToolsVersion "24.0.0"
renderscriptTargetApi 20
android:targetSdkVersion="22"

Body:
Problem was with the targetSdkVersion. Was targeting only 7.0 devices. Solved it by changing it to 22. Other values remain the same.

compileSdkVersion 25
buildToolsVersion '25.0.2'
renderscriptTargetApi 23


问:
PHP modulo quirk
I must not know enough about modulo with php. I am getting a strange result.

```<code>echo (-38 % 26); results in -12
</code>```

Which seems like the right answer to me. Google calculator is returning 14. Which is the right answer for the exercise I'm working on.

What's up with that?

答:
You need to use

```<code>echo ((-38 + 26) % 26);
</code>```

You could make a function which works with positive and negative $a as you intend:

```<code>function modulo($a, $b) { return ($a + $b) % $b; }
</code>```

Title: PHP modulo quirk

Body:
I must not know enough about modulo with php. I am getting a strange result.

echo (-38 % 26); results in -12

Which seems like the right answer to me. Google calculator is returning 14. Which is the right answer for the exercise I'm working on.

What's up with that?

Body:
You need to use

echo ((-38 + 26) % 26);

You could make a function which works with positive and negative $a as you intend:

function modulo($a, $b) { return ($a + $b) % $b; }


问:
How to set label height for auto adjust in Read More/Less with Swift 3?
I would like to create the paragraph with Read More/Read Less at the end.
 Here are my codes;

```<code>func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {

    let lbl = UILabel(frame: .zero)
    lbl.frame.size.width = width
    lbl.font = font
    lbl.numberOfLines = 0
    lbl.text = text
    lbl.sizeToFit()
    lbl.adjustsFontSizeToFitWidth = true
    return lbl.frame.size.height

}
</code>```

```<code> @IBAction func btnReadMore(_ sender: Any) {
    if isLabelAtMaxHeight {

        btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = false
        lblReviewHeight.constant = 29
        lblReview.font = UIFont (name: "Tharlon", size: 13)

    }
    else {

        btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = true
        lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font)
        lblReview.font = UIFont (name: "Tharlon", size: 13)
        lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead

    }

}
</code>```

I also set the label "Word wrap" in Attributes Inspector.

The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.

So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.

I don't want to use any other library.

Could anyone help me please?

答: Remove constraint lblReviewHeight, then just try to use numberOfLines control your text layout, if your want show all description set numberOfLines = 0, otherwise set numberOfLines to the line you want.

Body:
I would like to create the paragraph with Read More/Read Less at the end.
 Here are my codes;

func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {

    let lbl = UILabel(frame: .zero)
    lbl.frame.size.width = width
    lbl.font = font
    lbl.numberOfLines = 0
    lbl.text = text
    lbl.sizeToFit()
    lbl.adjustsFontSizeToFitWidth = true
    return lbl.frame.size.height

}

 @IBAction func btnReadMore(_ sender: Any) {
    if isLabelAtMaxHeight {

        btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = false
        lblReviewHeight.constant = 29
        lblReview.font = UIFont (name: "Tharlon", size: 13)

    }
    else {

        btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = true
        lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font)
        lblReview.font = UIFont (name: "Tharlon", size: 13)
        lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead

    }

}

I also set the label "Word wrap" in Attributes Inspector.

The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.

So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.

I don't want to use any other library.

Could anyone help me please?