答:
I, as the others are bit confused, but from my understanding of your problem you have basically working code.

You need to set select id to payment_option and put the message display div on the page. otherwise it cannot find what it needs to append the value to.

change it to this:
HTML

```<code><select name="option" id="payement_option">
    <option value="0">yes</option>
    <option value="1">no</option>
</select>

<div id="message_display"></div>
</code>```

JQUERY

```<code>$(function () {
    var message = new Array();
    //set message[0] = 'stuff' if you want something to display when yes is selected
    message[1] = '<input type="text" name="email" size="30" />';
    $("#payement_option").change(function () {
        //gets the message index
        var message_index = $("#payement_option").val();
        //emptys the value from message display
        $("#message_display").empty();

       //if option is not YES display message[val]
        if (message_index > 0) {
            $("#message_display").append(message[message_index]);
        }
    });
});
</code>```

and a live example: http://jsfiddle.net/mCqfq/

EDIT:

you mean like this? http://jsfiddle.net/dEwcK/

HTML:

```<code><select name="option" id="payement_option">
    <option value="0">yes</option>
    <option value="1">no</option>
</select>

<div id="message_display"><input type="text" name="email" size="30" id="hiddenInput" /></div>
</code>```

CSS:

```<code>#message_display {display: none;}
</code>```

JQUERY:

```<code>$(function () {
    $("#payement_option").change(function () {
        var message_index = $("#payement_option").val();

        if (message_index > 0) {
            $("#message_display").show();
        }
        else { $("#message_display").hide(); }

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

Title: Display hidden html code with jQuery

Body:
There is another solution to display a hidden input when a user choose an option from the select tag?
I want to put the HTML code outside the JS code.

jQuery code:

$(function() {

    var message = new Array(),
        $paymentOption = $("#payement_option"),
        $messageDisplay = $("#message_display");

    message[1] = '<input type="text" name="email" size="30" />';

    $paymentOption.change(function() {

        var messageIndex = $(this).val();

        $messageDisplay.empty();

        if (messageIndex > 0)
            $messageDisplay.append(message[messageIndex]);

    });

});

HTML code like this:

<select name="option"><option value="0">yes</option><option value="1">no</option</select>

the output:

EDIT:

I want something like:

    <input type="text" name="email" size="30" />

Body:
I, as the others are bit confused, but from my understanding of your problem you have basically working code.

You need to set select id to payment_option and put the message display div on the page. otherwise it cannot find what it needs to append the value to.

change it to this:
HTML

<select name="option" id="payement_option">
    <option value="0">yes</option>
    <option value="1">no</option>
</select>

<div id="message_display"></div>

JQUERY

$(function () {
    var message = new Array();
    //set message[0] = 'stuff' if you want something to display when yes is selected
    message[1] = '<input type="text" name="email" size="30" />';
    $("#payement_option").change(function () {
        //gets the message index
        var message_index = $("#payement_option").val();
        //emptys the value from message display
        $("#message_display").empty();

       //if option is not YES display message[val]
        if (message_index > 0) {
            $("#message_display").append(message[message_index]);
        }
    });
});

and a live example: http://jsfiddle.net/mCqfq/

EDIT:

you mean like this? http://jsfiddle.net/dEwcK/

HTML:

<select name="option" id="payement_option">
    <option value="0">yes</option>
    <option value="1">no</option>
</select>

<div id="message_display"><input type="text" name="email" size="30" id="hiddenInput" /></div>

CSS:

#message_display {display: none;}

JQUERY:

$(function () {
    $("#payement_option").change(function () {
        var message_index = $("#payement_option").val();

        if (message_index > 0) {
            $("#message_display").show();
        }
        else { $("#message_display").hide(); }

    });
});


来源: stackexchange

问:
Can not assign value to static variable inside class
I am trying to implement singleton pattern for a class. I have a static variable $classInstance and when assigning class object getting the error "Parse error: syntax error, unexpected '='".</p>

```<code>  /**
   * Hold instance of class.
   */
  private static $classInstance = null;

  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::classInstance === null) {
      self::classInstance = new self(); // Getting error on this line.
    }
    return self::classInstance;
  }
</code>```

答:
The error was because of missing "$" while accessing static property of class with self keyword.</p>

```<code>  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::$classInstance === null) {
      self::$classInstance = new self(); // Note the $ sign.
    }
    return self::$classInstance;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement singleton pattern for a class. I have a static variable $classInstance and when assigning class object getting the error "Parse error: syntax error, unexpected '='".

  /**
   * Hold instance of class.
   */
  private static $classInstance = null;

  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::classInstance === null) {
      self::classInstance = new self(); // Getting error on this line.
    }
    return self::classInstance;
  }

Body:
The error was because of missing "$" while accessing static property of class with self keyword.

  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::$classInstance === null) {
      self::$classInstance = new self(); // Note the $ sign.
    }
    return self::$classInstance;
  }


问:
How can I import a paralel package in python 3.6.9
I'm creating a project with the following folder structure.

A project with the 'src' package inside it. The 'models' package and the 'tests' package are inside 'src' and each has its own modules inside.

The problem: I'm trying import the package 'models' in a module inside the 'tests' package.

This is the folder structure:

```<code>-project
    -src
       -models
           -__init__.py
           -ArmModel.py
       -tests
           -test_arm_model.py
</code>```

The ArmModel.py defines a class:

```<code>class ArmModel:
    def __init__(self, definition='std def'):
        self.definition = definition
</code>```

And the test_arm_model.py (where I have the problem) needs to import ArmModel from models to test it:

```<code>import unittest
from src import models

class TestArmModel(unittest.TestCase):
    def test_arm_model(self):
        arm = models.ArmModel('arm')
        self.assertEqual(arm.definition, 'arm')

if __name__ == '__main__':
    unittest.main()
</code>```

I'm having trouble importing "Arm.py" from "models" inside the "tests" module.

Traceback (most recent call last):
    File "./src/tests/test_arm_model.py", line 2, in
      from src import models
  ModuleNotFoundError: No module named 'src'

Attempt 1:
I tried to use the following code and got the same error

```<code>from src import models
</code>```

I tried to get the class directly as following and got the same error

```<code>from src.models.ArmModel import ArmModel
</code>```

And I tried to manipulate the sys.path,

```<code>import sys
sys.path.append('/home/jamal/dev/tcc/src/')
from src.models.ArmModel import ArmModel
</code>```

And got the same error

```<code>from src.models.ArmModel import ArmModel
ModuleNotFoundError: No module named 'src'

</code>```

When I tried

```<code>sys.path.append('/home/jamal/dev/tcc/src/models/')
</code>```

or

```<code>sys.path.append('/home/jamal/dev/tcc/src/models/ArmModel')
</code>```

the autocomplete from PyCharm IDE couldn't find the package and I got the same error runnig the code.

I also tried to append '../' to the sys.path.
When I tried the code below, I got the ModuleNotFoundError: No module named 'src'

```<code>import sys
sys.path.append('../')
from src.models.ArmModel import ArmModel
</code>```

When I tried to change the import to

```<code>from models.ArmModel import ArmModel
</code>```

The IDE displayed an error with >Unresolved reference under models and ArmModel

答:
To solve this issue, I append the path to the project root file "TCC"

```<code>sys.path.append('home/jamal/Documents/dev/tcc')
from src.models.Arm import Arm
</code>```

Now I can access all the modules using "src."

Body:
I'm creating a project with the following folder structure.

A project with the 'src' package inside it. The 'models' package and the 'tests' package are inside 'src' and each has its own modules inside.

The problem: I'm trying import the package 'models' in a module inside the 'tests' package.

This is the folder structure:

-project
    -src
       -models
           -__init__.py
           -ArmModel.py
       -tests
           -test_arm_model.py

The ArmModel.py defines a class:

class ArmModel:
    def __init__(self, definition='std def'):
        self.definition = definition

And the test_arm_model.py (where I have the problem) needs to import ArmModel from models to test it:

import unittest
from src import models

class TestArmModel(unittest.TestCase):
    def test_arm_model(self):
        arm = models.ArmModel('arm')
        self.assertEqual(arm.definition, 'arm')

if __name__ == '__main__':
    unittest.main()

I'm having trouble importing "Arm.py" from "models" inside the "tests" module.

Traceback (most recent call last):
    File "./src/tests/test_arm_model.py", line 2, in
      from src import models
  ModuleNotFoundError: No module named 'src'

Attempt 1:
I tried to use the following code and got the same error

from src import models

I tried to get the class directly as following and got the same error

from src.models.ArmModel import ArmModel

And I tried to manipulate the sys.path,

import sys
sys.path.append('/home/jamal/dev/tcc/src/')
from src.models.ArmModel import ArmModel

And got the same error

from src.models.ArmModel import ArmModel
ModuleNotFoundError: No module named 'src'

When I tried

sys.path.append('/home/jamal/dev/tcc/src/models/')

or

sys.path.append('/home/jamal/dev/tcc/src/models/ArmModel')

the autocomplete from PyCharm IDE couldn't find the package and I got the same error runnig the code.

I also tried to append '../' to the sys.path.
When I tried the code below, I got the ModuleNotFoundError: No module named 'src'

import sys
sys.path.append('../')
from src.models.ArmModel import ArmModel

When I tried to change the import to

from models.ArmModel import ArmModel

The IDE displayed an error with >Unresolved reference under models and ArmModel

Body:
To solve this issue, I append the path to the project root file "TCC"

sys.path.append('home/jamal/Documents/dev/tcc')
from src.models.Arm import Arm

Now I can access all the modules using "src."


问:
How To fix Values of Second Y scale Using ggplot in R?
I'm trying to get a graph with 2 y scales using 2 different dataframes. The first dataframe bargraph_dets_temp looks like this

```<code>bargraph_dets_temp = structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
                                                                             "2", "3", "4"), class = "factor"), month = structure(c(8L, 8L,
                                                                                8L, 8L, 8L, 8L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2016, 2016, 2016, 2016, 2016, 2017), location = c("HFX001",
                                                                                "HFX002", "HFX003", "KETCH HARBOUR, NS", "NSTR001", "Gill Cove"
                                                                                ), num_unique_tags = c(5, 4, 2, 5, 5, 6), total_res_time_in_seconds = c(10666,
                                                                                14645, 6799, 0, 58959, 0), latitude = c(44.47846, 44.47222, 44.46643,
                                                                                44.48427, 44.48422, 44.48467), longitude = c(-63.53341, -63.52704,
                                                                                -63.51983, -63.53338, -63.53246, -63.53316), geometry = structure(list(
                                                                                structure(c(-63.53341, 44.47846), class = c("XY", "POINT",
                                                                                "sfg")), structure(c(-63.52704, 44.47222), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.51983, 44.46643), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53338, 44.48427), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53246, 44.48422), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53316, 44.48467), class = c("XY",
                                                                                "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = -63.53341,
                                                                                ymin = 44.46643, xmax = -63.51983, ymax = 44.48467), class = "bbox"), crs = structure(list(
                                                                                epsg = 4326L, proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L),
                      distances = c(27.3573801954343, 26.4992220821035, 25.6385699365414,
                                    27.8643036652756, 27.8152639871898, 27.8888441811952), ave_temp = c(6.417815,
                                                                                6.417815, 6.417815, 6.417815, 6.417815, 5.786351)), row.names = c(NA,
                                                                                -6L), groups = structure(list(month = structure(c(8L, 8L), .Label = c("Jan",
                                                                                "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
                                                                                "Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
                                                                                2017), .rows = list(1:5, 6L)), row.names = c(NA, -2L), class = c("tbl_df",
                                                                                "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"))
</code>```

from this dataframe I need the month, year, num_unique_tags, and Zone. My next dataframe mapoc_temp looks like this:

```<code>mapoc_temp = structure(list(month = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
2017, 2018, 2016, 2017, 2018), ave = c(6.52922242976571, 5.72051368352674,
5.78635119450037, 6.43544457584707, 5.81728212255571, 5.79052889374
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), groups = structure(list(month = structure(1:2, .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), .rows = list(
    1:3, 4:6)), row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))
</code>```

from this dataframe I need the ave_temp

To graph the values from both dataframes I am using this code

```<code>#putting 2 y scales on one graph

ggplot(bargraph_dets_temp,
       aes(x = month, y = num_unique_tags)) +
  geom_col(position = position_dodge(),
           aes(fill = as.factor(Zone))) +
  geom_line(inherit.aes = FALSE, data = mapoc_temp,
            aes(x = month, y = ave, group = 2),
            color = "forestgreen", size = 1.5) +
  scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~ . , name = "Average Temp (Celsius)")) +
  scale_fill_manual(name = "Zone",values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  xlab("Month") +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),

        axis.line = element_line(),

        axis.line.y.right = element_line(color = "forestgreen"),
        axis.ticks.y.right = element_line(color = "forestgreen"),
        axis.text.y.right = element_text(color = "forestgreen"),
        axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 30)),
        axis.title.y.left = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 40, r = 0, b = 0, l = 0)),

        strip.background =  element_rect(fill = NA, colour = NA),
        strip.text = element_text(size = 25),
        text = element_text(size = 24))
</code>```

This is the image I get

As you can see the temperature data goes straight across. But I want to show the temperature line increasing and decreasing, so I need the second y scale to be finer to show the change in temperature. Is there a way to fix the values of the second y scale so they go from 5-7 instead of 0-9?

答:
Having two different y-scales in one chart is typically discouraged -- and also not possible in ggplot by design -- see the explanation by the package author: https://stackoverflow.com/a/3101876/5726768.

There are workarounds, such as one described in this article: https://drawar.github.io/posts/dual-y-axis-ggplot2/

Alternatively, you can produce two different charts with aligned x-axes.

Body:
I'm trying to get a graph with 2 y scales using 2 different dataframes. The first dataframe bargraph_dets_temp looks like this

bargraph_dets_temp = structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
                                                                             "2", "3", "4"), class = "factor"), month = structure(c(8L, 8L,
                                                                                8L, 8L, 8L, 8L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2016, 2016, 2016, 2016, 2016, 2017), location = c("HFX001",
                                                                                "HFX002", "HFX003", "KETCH HARBOUR, NS", "NSTR001", "Gill Cove"
                                                                                ), num_unique_tags = c(5, 4, 2, 5, 5, 6), total_res_time_in_seconds = c(10666,
                                                                                14645, 6799, 0, 58959, 0), latitude = c(44.47846, 44.47222, 44.46643,
                                                                                44.48427, 44.48422, 44.48467), longitude = c(-63.53341, -63.52704,
                                                                                -63.51983, -63.53338, -63.53246, -63.53316), geometry = structure(list(
                                                                                structure(c(-63.53341, 44.47846), class = c("XY", "POINT",
                                                                                "sfg")), structure(c(-63.52704, 44.47222), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.51983, 44.46643), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53338, 44.48427), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53246, 44.48422), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53316, 44.48467), class = c("XY",
                                                                                "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = -63.53341,
                                                                                ymin = 44.46643, xmax = -63.51983, ymax = 44.48467), class = "bbox"), crs = structure(list(
                                                                                epsg = 4326L, proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L),
                      distances = c(27.3573801954343, 26.4992220821035, 25.6385699365414,
                                    27.8643036652756, 27.8152639871898, 27.8888441811952), ave_temp = c(6.417815,
                                                                                6.417815, 6.417815, 6.417815, 6.417815, 5.786351)), row.names = c(NA,
                                                                                -6L), groups = structure(list(month = structure(c(8L, 8L), .Label = c("Jan",
                                                                                "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
                                                                                "Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
                                                                                2017), .rows = list(1:5, 6L)), row.names = c(NA, -2L), class = c("tbl_df",
                                                                                "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"))

from this dataframe I need the month, year, num_unique_tags, and Zone. My next dataframe mapoc_temp looks like this:

mapoc_temp = structure(list(month = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
2017, 2018, 2016, 2017, 2018), ave = c(6.52922242976571, 5.72051368352674,
5.78635119450037, 6.43544457584707, 5.81728212255571, 5.79052889374
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), groups = structure(list(month = structure(1:2, .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), .rows = list(
    1:3, 4:6)), row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))

from this dataframe I need the ave_temp

To graph the values from both dataframes I am using this code

#putting 2 y scales on one graph

ggplot(bargraph_dets_temp,
       aes(x = month, y = num_unique_tags)) +
  geom_col(position = position_dodge(),
           aes(fill = as.factor(Zone))) +
  geom_line(inherit.aes = FALSE, data = mapoc_temp,
            aes(x = month, y = ave, group = 2),
            color = "forestgreen", size = 1.5) +
  scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~ . , name = "Average Temp (Celsius)")) +
  scale_fill_manual(name = "Zone",values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  xlab("Month") +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),

        axis.line = element_line(),

        axis.line.y.right = element_line(color = "forestgreen"),
        axis.ticks.y.right = element_line(color = "forestgreen"),
        axis.text.y.right = element_text(color = "forestgreen"),
        axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 30)),
        axis.title.y.left = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 40, r = 0, b = 0, l = 0)),

        strip.background =  element_rect(fill = NA, colour = NA),
        strip.text = element_text(size = 25),
        text = element_text(size = 24))

This is the image I get

As you can see the temperature data goes straight across. But I want to show the temperature line increasing and decreasing, so I need the second y scale to be finer to show the change in temperature. Is there a way to fix the values of the second y scale so they go from 5-7 instead of 0-9?


问:
What is the best way to compare strings to find matching words in Python?
I have two texts, text A and text B. Text B isn't an exact copy of text A, it has a lot of special characters which aren't in text A, but it is technically the same text. I need to compare the strings and map the counterparts in Text B to their counterparts in Text A.

The text isn't in English, and can't easily be translated to English, so the examples below are just to demonstrate a few of the problems.

Some words in text A are not in text B, but all words in text B should be in Text A:

```<code>text_a = "he experienced déjà vu"
text_b = ['he', 'experienced']
</code>```

Some words in text B use different characters to text A, but are the same words:

```<code>text_a = "she owns & runs the cafe florae"
text_b = ['she', 'owns', 'and', 'runs', 'the', 'cefé', 'floræ']
</code>```

Words in text B are generally in the right order, but not always:

```<code>text_a = "an uneasy alliance"
text_b = ['uneasy', 'alliance', 'an']
</code>```

Some words in text B are made up of smaller components, which are also included in text B, and these smaller components are unnecessary:

```<code>text_a = "we should withdraw our claim"
text_b = ['we', 'should', 'with', 'draw', 'withdraw', 'our', 'claim']
</code>```

Some words in text A are represented by two or more words in text B:

```<code>text_a = "they undercut their competitors"
text_b = ['they', 'under', 'cut', 'their', 'competitors']
</code>```

What I want to do is replace the words in text A with their counterparts from text B. To do this I need to write a function to match words between the two texts.

I've tried writing a function that compares strings using the edit distance method from the nltk library in conjunction with a handful of RegEx. This only does an OK job, so I looked at using sequence alignment techniques from libraries like biopython, but I can't get my head around these.

In particular, while using edit distance it's very difficult to match words like 'under' and 'cut' to 'undercut', while also avoiding errors in short strings. This is because in a sentence containing similar tokens, like 'to' and 'tu', these tokens have the same edit distance from something like 'tú', and would theoretically be equally valid candidates, though the obvious match here would be 'tu', not 'to'.

Is there any highly accurate way to match strings from text B in text A? I'd like to get an output like:

```<code>text_a = "the cafe florae undercut their competitors then withdrew their claim"
text_b = ['the', 'café', 'floræ', 'under', 'cut', 'their', 'competitors', 'then',
          'with', 'drew', 'withdrew', 'their', 'claim']

match_list = some_matchfunc(text_a, text_b)

print(match_list)

[['the', 'the'], ['cafe', 'café'], ['florae', 'floræ'], ['undercut', 'under'],
 ['undercut', 'cut'], ['their', 'their'], ['competitors', 'competitors'], ['then', 'then'],
 ['withdrew', 'withdrew'], ['their', 'their'], ['claim', 'claim']]
</code>```

Ideally, this would also include the index for the beginning and end of each matched word in text A, to avoid confusion, like with the word "their" which occurs twice below:

```<code>[['the', [0, 3] 'the'], ['cafe', [4, 8] 'café'], ['florae', [9, 15] 'floræ'],
 ['undercut', [16, 24], 'under'], ['undercut', [16, 24], 'cut'], ['their', [25, 30], 'their'],
 ['competitors', [31, 42], 'competitors'], ['then', [43, 47], 'then'], ['withdrew', [48, 56], 'withdrew'],
 ['their', [57, 62], 'their'], ['claim', [63, 68], 'claim']]
</code>```

As mentioned above, the text isn't in English, and translating it to compare words using NLP techniques isn't really feasible, so it does need to be based on string comparison. I think there must be some method or library already in existence which employs a more efficient sequence alignment algorithm than I can come up with using RegEx and edit distance, but I can't find one.

Does anybody know of a highly accurate method for comparing strings to achieve this outcome?

答:
The problem itself is very complex, and I would suggest a combination of dictionaries with suitable synonyms when suitable, and then falling back to a sequence alignment approach. The implementations in biopython are probably not really suitable for this case (BLAST, for instance, relies in a score matrix that does not make sense for real words, only to nucleotide or amino acid sequences). I suggest you have a look at SequenceMatcher, which could do the job. A very simple (albeit naive) solution is to do a pairwise alignment of all the candidates and pick the closest match. Depending on the complexity of the alignment, e.g. whether gaps/replacements are required (imagine "they're" -> "they are").

Bear in mind that in some cases many-to-many, one-to-many, and many-to-one substitutions will be required (you have some of these in your example already). This is not automatically solved by the sequence alignment, hence my suggestion to use a dictionary (a bidirectional one if can afford it). If the synonym corpus is very big, I would even consider a database for such tasks.

Also, some of your examples require word-level substitutions and some require letter-level substitutions. I suggest that you handle these separately. If you don't have to deal with typos, I would start with the bigger (word) scale, and then move on to the letter-level substitutions.

Body:
I have two texts, text A and text B. Text B isn't an exact copy of text A, it has a lot of special characters which aren't in text A, but it is technically the same text. I need to compare the strings and map the counterparts in Text B to their counterparts in Text A.

The text isn't in English, and can't easily be translated to English, so the examples below are just to demonstrate a few of the problems.

Some words in text A are not in text B, but all words in text B should be in Text A:

text_a = "he experienced déjà vu"
text_b = ['he', 'experienced']

Some words in text B use different characters to text A, but are the same words:

text_a = "she owns & runs the cafe florae"
text_b = ['she', 'owns', 'and', 'runs', 'the', 'cefé', 'floræ']

Words in text B are generally in the right order, but not always:

text_a = "an uneasy alliance"
text_b = ['uneasy', 'alliance', 'an']

Some words in text B are made up of smaller components, which are also included in text B, and these smaller components are unnecessary:

text_a = "we should withdraw our claim"
text_b = ['we', 'should', 'with', 'draw', 'withdraw', 'our', 'claim']

Some words in text A are represented by two or more words in text B:

text_a = "they undercut their competitors"
text_b = ['they', 'under', 'cut', 'their', 'competitors']

What I want to do is replace the words in text A with their counterparts from text B. To do this I need to write a function to match words between the two texts.

I've tried writing a function that compares strings using the edit distance method from the nltk library in conjunction with a handful of RegEx. This only does an OK job, so I looked at using sequence alignment techniques from libraries like biopython, but I can't get my head around these.

In particular, while using edit distance it's very difficult to match words like 'under' and 'cut' to 'undercut', while also avoiding errors in short strings. This is because in a sentence containing similar tokens, like 'to' and 'tu', these tokens have the same edit distance from something like 'tú', and would theoretically be equally valid candidates, though the obvious match here would be 'tu', not 'to'.

Is there any highly accurate way to match strings from text B in text A? I'd like to get an output like:

text_a = "the cafe florae undercut their competitors then withdrew their claim"
text_b = ['the', 'café', 'floræ', 'under', 'cut', 'their', 'competitors', 'then',
          'with', 'drew', 'withdrew', 'their', 'claim']

match_list = some_matchfunc(text_a, text_b)

print(match_list)

[['the', 'the'], ['cafe', 'café'], ['florae', 'floræ'], ['undercut', 'under'],
 ['undercut', 'cut'], ['their', 'their'], ['competitors', 'competitors'], ['then', 'then'],
 ['withdrew', 'withdrew'], ['their', 'their'], ['claim', 'claim']]

Ideally, this would also include the index for the beginning and end of each matched word in text A, to avoid confusion, like with the word "their" which occurs twice below:

[['the', [0, 3] 'the'], ['cafe', [4, 8] 'café'], ['florae', [9, 15] 'floræ'],
 ['undercut', [16, 24], 'under'], ['undercut', [16, 24], 'cut'], ['their', [25, 30], 'their'],
 ['competitors', [31, 42], 'competitors'], ['then', [43, 47], 'then'], ['withdrew', [48, 56], 'withdrew'],
 ['their', [57, 62], 'their'], ['claim', [63, 68], 'claim']]

As mentioned above, the text isn't in English, and translating it to compare words using NLP techniques isn't really feasible, so it does need to be based on string comparison. I think there must be some method or library already in existence which employs a more efficient sequence alignment algorithm than I can come up with using RegEx and edit distance, but I can't find one.

Does anybody know of a highly accurate method for comparing strings to achieve this outcome?


问:
Filter WPF DataGrid by multiple criterias
I would like to implement Excel like filter to datagrid by three columns.

Here is my code:

```<code>    using System.Data.Odbc;
    using System.Windows;
    using System.Data;

    namespace DB_inspector
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
                string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
                dbConnection.Open();
                OdbcDataAdapter dadapter = new OdbcDataAdapter();
                dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
                DataTable table = new DataTable("COMPANY");
                dadapter.Fill(table);
                DataGrid1.DataContext = table;
                DataGrid1.ItemsSource = table.DefaultView;
                dadapter.Update(table);
                dbConnection.Close();
            }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = NameSearch.Text;
                if (string.IsNullOrEmpty(filter))
                    dv.RowFilter = null;
                else
                    dv.RowFilter = string.Format("NAME Like '%{0}%'", filter);

        }

        private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = ActiveSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("ACTIVE Like '%{0}%'", filter);
        }

        private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = CustomerNumberSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
        }
    }
}
</code>```

XAML

```<code><Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DB_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"/>
        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1" TextChanged="TextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <TextBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="66" TextChanged="TextBox_TextChanged_1"/>
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82" TextChanged="CustomerNumberSearch_TextChanged"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>
</code>```

I would like to implement filters for column NRO and ACTIVE so that during load of data in column NRO will be numbers starting with 3 only and in column ACTIVE values with 1 only. In ACTIVE there are values 1 and 0 (1 active, 0 not active).

My current setup is filtering only by one criteria. How to make all three criteria function correct?

答:
You can modify your database query and let the database do the work more efficiently.

But if you still prefer to do it using C#, you can use LINQ to filter the DataTable:

MainWindow.xaml

```<code><Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <DataGrid ItemsSource={Binding Data} />
</Window>
</code>```

ViewModel.cs

```<code>public class ViewModel
{
  public DataTable Data { get; set; }

  public ViewModel()
  {
    this.Data = new DataTable();
  }

  // Button ICommand handler
  private void ExecuteGetDataCommand(object param)
  {
    DataTable dataTable = QueryDatabase();

    // Filter DataTable using LINQ
    this.Data = dataTable
      .AsEnumerable()
      .Where(row => row["NRO"].ToString().StartsWith("3")
        && row["ACTIVE"].ToString().StartsWith("1"))
      .CopyToDataTable();
  }

  private DataTable QueryDatabase()
  {
    OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
    string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
    dbConnection.Open();
    OdbcDataAdapter dadapter = new OdbcDataAdapter();
    dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
    DataTable table = new DataTable("COMPANY");
    dadapter.Fill(table);
    return table;
  }
}
</code>```

Update

This is the solution based on your posted code. I replaced the TextBox to filter the ACTIVE column with a CheckBox, to add some type safety (to prevent invalid input e.g., alphabetical). I also used data binding to connect the DataGrid to the DataTable. You should prefer to use data binding over code-behind and implement as much as possible in XAML:

MainWindow.xaml

```<code><Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Liinos_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>

        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"
                  ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MainWindow}}, Path=FilteredData}" />

        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>

        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1"
                 TextChanged="OnNameSearchTextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <CheckBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="66"
                  IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MainWindow}}, Path=IsActiveFilterValue}" />
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82"
                 TextChanged="OnCustomerNumberSearch_TextChanged"/>

        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
  public static readonly DependencyProperty FilteredDataProperty = DependencyProperty.Register(
    "FilteredData",
    typeof(DataTable),
    typeof(MainWindow));

  public DataTable FilteredData
  {
    get { return (DataTable)GetValue(FilteredDataProperty); }
    set { SetValue(FilteredDataProperty, value); }
  }

  public static readonly DependencyProperty IsActiveFilterValueProperty = DependencyProperty.Register(
    "IsActiveFilterValue",
    typeof(bool),
    typeof(MainWindow),
    new PropertyMetadata(false, OnIsActiveFilterValueChanged));

  public bool IsActiveFilterValue
  {
    get { return (bool)GetValue(IsActiveFilterValueProperty); }
    set { SetValue(IsActiveFilterValueProperty, value); }
  }

  private DataTable UnfilteredData { get; set; }
  private String NameFilterValue { get; set; }
  private int CustomerNumberFilterValue { get; set; }

  public MainWindow()
  {
    InitializeComponent();
  }

  private void Button_Click(object sender, RoutedEventArgs e)
  {
    string connectionString = "Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;";

    string queryString = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

    // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
    using (OdbcConnection dbConnection = new OdbcConnection(connectionString))
    {
      dbConnection.Open();
      OdbcDataAdapter dadapter = new OdbcDataAdapter();
      dadapter.SelectCommand = new OdbcCommand(queryString, dbConnection);

      this.UnfilteredData = new DataTable("COMPANY");
      dadapter.Fill(this.UnfilteredData);
      this.FilteredData = this.UnfilteredData;
    }
  }

  private void ApplyFilterOnDataTable()
  {
    // Filter DataTable using LINQ
    this.FilteredData = this.UnfilteredData
      .AsEnumerable()
      .Where(row =>
        string.IsNullOrWhiteSpace(this.NameFilterValue)
          ? true // Filter criteria is ignored, when input is empty or null
          : row["NAME"].StartsWith(this.NameFilterValue)
        && this.CustomerNumberFilterValue < 0
          ? true // Filter criteria is ignored, when value is < 0
          : row["NRO"].ToString().StartsWith(this.CustomerNumberFilterValue.ToString())
        && this.IsActiveFilterValue
          ? row["ACTIVE"].ToString().Equals("1")
          : true) // Filter criteris is ignored, when CheckBox is unchecked
      .CopyToDataTable();
  }

  private void OnNameSearchTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
  {
    this.NameFilterValue = NameSearch.Text;
    ApplyFilterOnDataTable();
  }

  private static void OnIsActiveFilterValueChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
  {
    var _this = d as MainWindow;
    _this.ApplyFilterOnDataTable();
  }

  private void OnCustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
  {
    // Check if input is numeric
    this.CustomerNumberFilterValue = Int32.TryParse(CustomerNumberSearch.Text, out int number)
      ? number
      : -1; // Parsing failed -> not a numeric value. -1 will disable this filter criteria
    ApplyFilterOnDataTable();
  }
}
</code>```

Body:
I would like to implement Excel like filter to datagrid by three columns.

Here is my code:

    using System.Data.Odbc;
    using System.Windows;
    using System.Data;

    namespace DB_inspector
    {
        ///
        /// Interaction logic for MainWindow.xaml
        ///
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
                string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
                dbConnection.Open();
                OdbcDataAdapter dadapter = new OdbcDataAdapter();
                dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
                DataTable table = new DataTable("COMPANY");
                dadapter.Fill(table);
                DataGrid1.DataContext = table;
                DataGrid1.ItemsSource = table.DefaultView;
                dadapter.Update(table);
                dbConnection.Close();
            }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = NameSearch.Text;
                if (string.IsNullOrEmpty(filter))
                    dv.RowFilter = null;
                else
                    dv.RowFilter = string.Format("NAME Like '%{0}%'", filter);

        }

        private void TextBox_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = ActiveSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("ACTIVE Like '%{0}%'", filter);
        }

        private void CustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DataView dv = DataGrid1.ItemsSource as DataView;

            string filter = CustomerNumberSearch.Text;
            if (string.IsNullOrEmpty(filter))
                dv.RowFilter = null;
            else
                dv.RowFilter = string.Format("NRO Like '%{0}%'", filter); //this should be "Begins with" not "Like"
        }
    }
}

XAML

<Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DB_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"/>
        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1" TextChanged="TextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <TextBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="66" TextChanged="TextBox_TextChanged_1"/>
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82" TextChanged="CustomerNumberSearch_TextChanged"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>

I would like to implement filters for column NRO and ACTIVE so that during load of data in column NRO will be numbers starting with 3 only and in column ACTIVE values with 1 only. In ACTIVE there are values 1 and 0 (1 active, 0 not active).

My current setup is filtering only by one criteria. How to make all three criteria function correct?

Body:
You can modify your database query and let the database do the work more efficiently.

But if you still prefer to do it using C#, you can use LINQ to filter the DataTable:

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <DataGrid ItemsSource={Binding Data} />
</Window>

ViewModel.cs

public class ViewModel
{
  public DataTable Data { get; set; }

  public ViewModel()
  {
    this.Data = new DataTable();
  }

  // Button ICommand handler
  private void ExecuteGetDataCommand(object param)
  {
    DataTable dataTable = QueryDatabase();

    // Filter DataTable using LINQ
    this.Data = dataTable
      .AsEnumerable()
      .Where(row => row["NRO"].ToString().StartsWith("3")
        && row["ACTIVE"].ToString().StartsWith("1"))
      .CopyToDataTable();
  }

  private DataTable QueryDatabase()
  {
    OdbcConnection dbConnection = new OdbcConnection("Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;");
    string strSql = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
    dbConnection.Open();
    OdbcDataAdapter dadapter = new OdbcDataAdapter();
    dadapter.SelectCommand = new OdbcCommand(strSql, dbConnection);
    DataTable table = new DataTable("COMPANY");
    dadapter.Fill(table);
    return table;
  }
}

Update

This is the solution based on your posted code. I replaced the TextBox to filter the ACTIVE column with a CheckBox, to add some type safety (to prevent invalid input e.g., alphabetical). I also used data binding to connect the DataGrid to the DataTable. You should prefer to use data binding over code-behind and implement as much as possible in XAML:

MainWindow.xaml

<Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Liinos_inspector"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="11*"/>
            <RowDefinition Height="553*"/>
        </Grid.RowDefinitions>

        <DataGrid x:Name="DataGrid1" Margin="0,51,0,0" Grid.Row="1"
                  ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MainWindow}}, Path=FilteredData}" />

        <Image Height="41" Margin="847,10,10,502" Width="141" Source="Logo_small.jpg" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Top"/>

        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="23" Margin="77,14,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="409" Grid.Row="1"
                 TextChanged="OnNameSearchTextBox_TextChanged"/>
        <Button Content="Refrsh" HorizontalAlignment="Left" Height="23" Margin="736,14,0,0" VerticalAlignment="Top" Width="72" Click="Button_Click" Grid.Row="1" Background="#FF51C951" BorderBrush="{x:Null}" Foreground="White"/>
        <CheckBox x:Name="ActiveSearch" HorizontalAlignment="Left" Height="23" Margin="502,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="66"
                  IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MainWindow}}, Path=IsActiveFilterValue}" />
        <TextBox x:Name="CustomerNumberSearch" HorizontalAlignment="Left" Height="23" Margin="580,14,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="82"
                 TextChanged="OnCustomerNumberSearch_TextChanged"/>

        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="10" Margin="0,1,0,0" VerticalAlignment="Top" Width="998" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="23" Margin="680,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="51" Click="Button_Click_1"/>

    </Grid>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
  public static readonly DependencyProperty FilteredDataProperty = DependencyProperty.Register(
    "FilteredData",
    typeof(DataTable),
    typeof(MainWindow));

  public DataTable FilteredData
  {
    get { return (DataTable)GetValue(FilteredDataProperty); }
    set { SetValue(FilteredDataProperty, value); }
  }

  public static readonly DependencyProperty IsActiveFilterValueProperty = DependencyProperty.Register(
    "IsActiveFilterValue",
    typeof(bool),
    typeof(MainWindow),
    new PropertyMetadata(false, OnIsActiveFilterValueChanged));

  public bool IsActiveFilterValue
  {
    get { return (bool)GetValue(IsActiveFilterValueProperty); }
    set { SetValue(IsActiveFilterValueProperty, value); }
  }

  private DataTable UnfilteredData { get; set; }
  private String NameFilterValue { get; set; }
  private int CustomerNumberFilterValue { get; set; }

  public MainWindow()
  {
    InitializeComponent();
  }

  private void Button_Click(object sender, RoutedEventArgs e)
  {
    string connectionString = "Driver={Pervasive ODBC Client Interface};ServerName=875;dbq=@DBFS;Uid=Username;Pwd=Password;";

    string queryString = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

    // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
    using (OdbcConnection dbConnection = new OdbcConnection(connectionString))
    {
      dbConnection.Open();
      OdbcDataAdapter dadapter = new OdbcDataAdapter();
      dadapter.SelectCommand = new OdbcCommand(queryString, dbConnection);

      this.UnfilteredData = new DataTable("COMPANY");
      dadapter.Fill(this.UnfilteredData);
      this.FilteredData = this.UnfilteredData;
    }
  }

  private void ApplyFilterOnDataTable()
  {
    // Filter DataTable using LINQ
    this.FilteredData = this.UnfilteredData
      .AsEnumerable()
      .Where(row =>
        string.IsNullOrWhiteSpace(this.NameFilterValue)
          ? true // Filter criteria is ignored, when input is empty or null
          : row["NAME"].StartsWith(this.NameFilterValue)
        && this.CustomerNumberFilterValue < 0
          ? true // Filter criteria is ignored, when value is < 0
          : row["NRO"].ToString().StartsWith(this.CustomerNumberFilterValue.ToString())
        && this.IsActiveFilterValue
          ? row["ACTIVE"].ToString().Equals("1")
          : true) // Filter criteris is ignored, when CheckBox is unchecked
      .CopyToDataTable();
  }

  private void OnNameSearchTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
  {
    this.NameFilterValue = NameSearch.Text;
    ApplyFilterOnDataTable();
  }

  private static void OnIsActiveFilterValueChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
  {
    var _this = d as MainWindow;
    _this.ApplyFilterOnDataTable();
  }

  private void OnCustomerNumberSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
  {
    // Check if input is numeric
    this.CustomerNumberFilterValue = Int32.TryParse(CustomerNumberSearch.Text, out int number)
      ? number
      : -1; // Parsing failed -> not a numeric value. -1 will disable this filter criteria
    ApplyFilterOnDataTable();
  }
}


问:
What is the minimum RISC-V instruction set that runs GNU/Linux?
I want to build my own minimal RISC-V processor for a FPGA. The processor will as simple as possible with only one pipeline.

I read the entire RISC-V ISA and there are many standard extensions. So what is the minimum RISC-V ISA that can run linux?

答:
As of 2020, the reasonable minimum is RV64GC, User/System mode ("U"/"S" extensions) and a page-based virtual memory system (Sv32, Sv39 or Sv48).

Note that the RISC-V Base specification (2019-06-08 ratified) expands the G (general-purpose) symbol to: IMAFD+Zicsr+Zifencei

The compressed instruction extension ("C") is also part of the base specification. The "U"/"S" extensions and virtual memory systems are part of the RISC-V Privileged Architecture specification.

Technically, RV64GC is the minimum for running a general purpose distribution such as Debian and Fedora - however, with a custom Linux you could get down to RV64IMA+Zi* or even RV32IMA+Zi* (with some patching).

ContentLicense: CC BY-SA 3.0


问:
How to remove duplicate combinations tuples from python list?
I have a list with tuples as below:

```<code>mylist = [(1, 2),(1, 3),(2, 1),(2, 3),(3, 1),(3, 2),(3, 3)]
</code>```

Expected (Unique combinations)

```<code>[(1, 2),(1, 3),(2, 3),(3, 3)]
</code>```

I tried below

```<code>mylist = list(set(map(tuple, mylist)))
</code>```

But didnt get the desired output. Any help here?

答:
You can try this.</p>

```<code>out=list(set(map(tuple,map(sorted,mylist))))
</code>```

Body:
I have a list with tuples as below:

mylist = [(1, 2),(1, 3),(2, 1),(2, 3),(3, 1),(3, 2),(3, 3)]

Expected (Unique combinations)

[(1, 2),(1, 3),(2, 3),(3, 3)]

I tried below

mylist = list(set(map(tuple, mylist)))

But didnt get the desired output. Any help here?

Body:
You can try this.

out=list(set(map(tuple,map(sorted,mylist))))


问:
How can I read text from files and display them as list using widget/s in Flutter?
may I ask a way how to make this work.

I have a text file named questions.txt.

This file contains the following questions:

How old are you?

Where do you live?

What is your age?

I want to load these questions from the file, and render them as a list in Flutter.

questionnaires.dart

import 'package:flutter/material.dart';
class Questionnaires extends StatefulWidget {
    @override
    _QuestionnairesState createState() => _QuestionnairesState();
}

class _QuestionnairesState extends State<Questionnaires> {
    String q1 = "";
    String q2 = "";
    String q3 = "";
    @override
    Widget build(BuildContext context) {
        return SafeArea(
            child: Scaffold(
            resizeToAvoidBottomInset: false,
                body: Center(
                    child: Column(
                        children: <Widget>[
                            Text(q1),
                            Text(q2),
                            Text(q3)
                        ],
                    ),
                ),
            ),
        );
    }
}
```

答:
You can start with the most basic way of retrieving the questions from a .txt file using rootBundle.loadString, then display it using a ListView widget.

main.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Questions',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyAppScreen(),
    );
  }
}

class MyAppScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppScreenState();
  }
}

class MyAppScreenState extends State<MyAppScreen> {
  List<String> _questions = [];

  Future<List<String>> _loadQuestions() async {
    List<String> questions = [];
    await rootBundle.loadString('path/to/questions.txt').then((q) {
      for (String i in LineSplitter().convert(q)) {
        questions.add(i);
      }
    });
    return questions;
  }

  @override
  void initState() {
    _setup();
    super.initState();
  }

  _setup() async {
    // Retrieve the questions (Processed in the background)
    List<String> questions = await _loadQuestions();

    // Notify the UI and display the questions
    setState(() {
      _questions = questions;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter Questions")),
      body: Center(
        child: Container(
          child: ListView.builder(
            itemCount: _questions.length,
            itemBuilder: (context, index) {
              return Text(_questions[index]);
            },
          ),
        ),
      ),
    );
  }
}
```

<p>And here are the sample list of questions.</p>

<p><strong>questions.txt</strong></p>

```"How old are you?"
"Where do you live?"
"What is your age?"
```

In the example code above, you are parsing the text file line by line, please see LineSplitter. This is good for small and sample projects while you're testing out Flutter. But you should be able to update this implementation by following the official docs of Flutter, on how you can read from and write on files.

Furthermore, if you want to go big with your Flutter project, you should look into ways on how you can host your questions online, eg. served via REST APIs, then retrieve it using the http plugin for Flutter.

More on:

https://flutter.dev/docs/cookbook/networking/fetch-data

https://flutter.dev/docs/cookbook/persistence/reading-writing-files

https://pub.dev/packages/path_provider

Output:

Body:
You can start with the most basic way of retrieving the questions from a .txt file using rootBundle.loadString, then display it using a ListView widget.

main.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Questions',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyAppScreen(),
    );
  }
}

class MyAppScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppScreenState();
  }
}

class MyAppScreenState extends State<MyAppScreen> {
  List<String> _questions = [];

  Future<List<String>> _loadQuestions() async {
    List<String> questions = [];
    await rootBundle.loadString('path/to/questions.txt').then((q) {
      for (String i in LineSplitter().convert(q)) {
        questions.add(i);
      }
    });
    return questions;
  }

  @override
  void initState() {
    _setup();
    super.initState();
  }

  _setup() async {
    // Retrieve the questions (Processed in the background)
    List<String> questions = await _loadQuestions();

    // Notify the UI and display the questions
    setState(() {
      _questions = questions;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter Questions")),
      body: Center(
        child: Container(
          child: ListView.builder(
            itemCount: _questions.length,
            itemBuilder: (context, index) {
              return Text(_questions[index]);
            },
          ),
        ),
      ),
    );
  }
}

And here are the sample list of questions.

questions.txt

"How old are you?"
"Where do you live?"
"What is your age?"

In the example code above, you are parsing the text file line by line, please see LineSplitter. This is good for small and sample projects while you're testing out Flutter. But you should be able to update this implementation by following the official docs of Flutter, on how you can read from and write on files.

Furthermore, if you want to go big with your Flutter project, you should look into ways on how you can host your questions online, eg. served via REST APIs, then retrieve it using the http plugin for Flutter.

More on:

https://flutter.dev/docs/cookbook/networking/fetch-data

https://flutter.dev/docs/cookbook/persistence/reading-writing-files

https://pub.dev/packages/path_provider

Output:


问:
Memory Leak from NSXMLParser
im running cocos2d with levelSVG, a SVG Parsing system from Sapus Media.

I'm using the parse system, which works as predicted, but im having a few problems with memory leaks associated with the NSXMLParser.

The Memory Leaks give a consistent drop in fps over a timespan of 5 minutes and render the application useless at 12fps at the end of this timeframe.

I have removed all my particlesystems and other potentially leaky objects and the leak still exists..

Running the Memory Leak Tool:

3 Leaking Objects Detected:

GeneralBlock-512

GeneralBlock-512

NSConcreteMapTable

They link to:

*

```<code>NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

        [parser setDelegate:self];
        [parser setShouldProcessNamespaces:NO];
        [parser setShouldReportNamespacePrefixes:NO];
        [parser setShouldResolveExternalEntities:NO];
        [parser parse];

        NSError *parseError = [parser parserError];
        if(parseError) {
            SVGLOG(@"Error parsing SVG file: %@", parseError);
        }

        [parser release];
</code>```

As you can see, the object is released after the parsing has been completed.

Driving me bonkers, does anyone know whats happening?

答:
Okay, after a bit of research I found a bug in the NSXMLParser when using the URL method as described above.

```<code>NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]
</code>```

By changing this to:

```<code>NSData *xml = [NSData dataWithContentsOfURL:url];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xml];
</code>```

This fixed the memory leak issue but still didnt account for the consistent drop of fps over the timeframe.
I then found that my allocations of memory for a particular class, CCFollow was consistently increasing overtime on the memory-leak tool.

I then checked the code and I was running an infinite CCAction - CCFollow, within a repeating tick update method. This was the source of the memory drain.
Removing it from the tick update method and moving it to an initialisation method fixed this problem.

Title: Memory Leak from NSXMLParser

Body:
im running cocos2d with levelSVG, a SVG Parsing system from Sapus Media.

I'm using the parse system, which works as predicted, but im having a few problems with memory leaks associated with the NSXMLParser.

The Memory Leaks give a consistent drop in fps over a timespan of 5 minutes and render the application useless at 12fps at the end of this timeframe.

I have removed all my particlesystems and other potentially leaky objects and the leak still exists..

Running the Memory Leak Tool:

3 Leaking Objects Detected:

GeneralBlock-512

GeneralBlock-512

NSConcreteMapTable

They link to:

*

NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

        [parser setDelegate:self];
        [parser setShouldProcessNamespaces:NO];
        [parser setShouldReportNamespacePrefixes:NO];
        [parser setShouldResolveExternalEntities:NO];
        [parser parse];

        NSError *parseError = [parser parserError];
        if(parseError) {
            SVGLOG(@"Error parsing SVG file: %@", parseError);
        }

        [parser release];

As you can see, the object is released after the parsing has been completed.

Driving me bonkers, does anyone know whats happening?

Body:
Okay, after a bit of research I found a bug in the NSXMLParser when using the URL method as described above.

NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]

By changing this to:

NSData *xml = [NSData dataWithContentsOfURL:url];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xml];

This fixed the memory leak issue but still didnt account for the consistent drop of fps over the timeframe.
I then found that my allocations of memory for a particular class, CCFollow was consistently increasing overtime on the memory-leak tool.

I then checked the code and I was running an infinite CCAction - CCFollow, within a repeating tick update method. This was the source of the memory drain.
Removing it from the tick update method and moving it to an initialisation method fixed this problem.


问:
A badge in GitHub template repository that will refer to clones' build status, not the template repo's build status
I'm new to GitHub's template repositories. We've created a template repo for our course's code labs. Let's say it's on GitHub under myorg/labX. The students are using GitHub Classroom, which clones the template repo for each student under myorg/labX-studentlogin. We've got actions to run some tests against their code using GitHub's own CI, and I want to include badges in the repo's README.md to see the test results at a glance. So I know that

```<code>![](https://github.com/myorg/labX/workflows/task1/badge.svg)
</code>```

will include the badge, but this is the status of the template repo, not student repos. Is there a way to automate this so that when the students get their clone, it will contain a README with the URL that refers to the status of their own repo?

答:
I agree it would be a great feature to have.

It looks like at this point, GitHub Template Repositories do not support variable substitution, which is what would make it possible.

I see it is discussed briefly here:

Variable substitution for GitHub Template Repository Usage

Perhaps you should join the discussion and/or cast your Kudo.

Body:
I'm new to GitHub's template repositories. We've created a template repo for our course's code labs. Let's say it's on GitHub under myorg/labX. The students are using GitHub Classroom, which clones the template repo for each student under myorg/labX-studentlogin. We've got actions to run some tests against their code using GitHub's own CI, and I want to include badges in the repo's README.md to see the test results at a glance. So I know that

![](https://github.com/myorg/labX/workflows/task1/badge.svg)

will include the badge, but this is the status of the template repo, not student repos. Is there a way to automate this so that when the students get their clone, it will contain a README with the URL that refers to the status of their own repo?


问:
How to understand that the types a and forall r. (a -> r) -> r are isomorphic
In the book Thinking with Types, 6.4 Continuation Monad tells that the types a and forall r. (a -> r) -> r are isomorphic, which can be witnessed by the following functions:

cont :: a -> (forall r. (a -> r) -> r)
cont x = \f -> f x

unCont :: (forall r. (a -> r) -> r) -> a
unCont f = f id
```

In this book, it tells that any two types that have the same cardinality will always be isomorphic to one another. So I try to figure out the cardinality of the types a and forall r. (a -> r) -> r.

Suppose the cardinality of the type a is |a|. Then for the type forall r. (a -> r) -> r, how to figure out its cardinality equals |a|? The function type a -> b has cardinality |b|^|a|, i.e., |b| to the power of |a|, so forall r. (a -> r) -> r has cardinality of |r|^(|r|^|a|). How can it be equal to |a|?

I'm confused. Thanks for any tips!

答:
The cardinality argument doesn't really work with polymorphic types (see @chi's answer).

But isomorphism itself can be intuitively explained like this:

The type forall r. (a -> r) -> r means "if you give me a function that converts a to r, I can give you back an r. Oh, and I can do this for any possible r whatsoever"

The only way to fulfill such promise is by secretly having an a in my hand.

Since I promise to do this for any possible r, it means I can't know anything about r itself, including how to construct a value of it. And the only thing I have available is the function a -> r that you give me. And the only way to call such function is by giving it an a.

This means that if I'm making such promise, I must already secretly have an a behind my back.

For a more formal explanation, recall that "isomorphic" in plain terms means "can be unambiguously converted back and forth without losses". This is what the cardinality argument is getting at: if you have the same number of things, you can always arrange a pairing between them.

And in your question you already show the two conversions: cont converts one way, unCont converts the other. And you can trivially show that cont . unCont = unCont . cont = id. Therefore the types are isomorphic.

While showing the existence of the two conversions is more formal, I find it's not always satisfactory for getting an intuition for how the two types are really "kinda the same thing", hence the intuitive explanation I gave above.

Body:
In the book Thinking with Types, 6.4 Continuation Monad tells that the types a and forall r. (a -> r) -> r are isomorphic, which can be witnessed by the following functions:

cont :: a -> (forall r. (a -> r) -> r)
cont x = \f -> f x

unCont :: (forall r. (a -> r) -> r) -> a
unCont f = f id

In this book, it tells that any two types that have the same cardinality will always be isomorphic to one another. So I try to figure out the cardinality of the types a and forall r. (a -> r) -> r.

Suppose the cardinality of the type a is |a|. Then for the type forall r. (a -> r) -> r, how to figure out its cardinality equals |a|? The function type a -> b has cardinality |b|^|a|, i.e., |b| to the power of |a|, so forall r. (a -> r) -> r has cardinality of |r|^(|r|^|a|). How can it be equal to |a|?

I'm confused. Thanks for any tips!


问:
Postgres syntax in node-postgres for function call
Here is how I call postgres from my node.js app using express

```<code>const db_pg = require("./db-pg");
app.get('/pg/', (req,res,next) => {
    db_pg.query(req).then((body) => {
        res.send(body);
    }).catch((err) => {
        next(err);
    })
});
</code>```

And within my db-pg/index.js file (not including the detail of the pool setup):

```<code>module.exports = {
    query: (req) => {
        return pool.query(req);
    }
};
</code>```

I am getting the following error from postgreSQL :

```<code>syntax error at or near ","
</code>```

The query I am trying to execute is :

```<code>req = {
    text: "SELECT * from my_func(?,?,?)",
    values: ["the_name", 20190303, 20190620]
}
</code>```

What is wrong in my syntax ?

答:
Just turning Chris White's comment into an answer:

node-postgres recommends to use parameterized-queries for passing parameters.

Here is the correct syntax for the SQL (all the rest looks fine):

```<code>"SELECT * FROM my_func($1, $2, $3)"
</code>```

Body:
Here is how I call postgres from my node.js app using express

const db_pg = require("./db-pg");
app.get('/pg/', (req,res,next) => {
    db_pg.query(req).then((body) => {
        res.send(body);
    }).catch((err) => {
        next(err);
    })
});

And within my db-pg/index.js file (not including the detail of the pool setup):

module.exports = {
    query: (req) => {
        return pool.query(req);
    }
};

I am getting the following error from postgreSQL :

syntax error at or near ","

The query I am trying to execute is :

req = {
    text: "SELECT * from my_func(?,?,?)",
    values: ["the_name", 20190303, 20190620]
}

What is wrong in my syntax ?

Body:
Just turning Chris White's comment into an answer:

node-postgres recommends to use parameterized-queries for passing parameters.

Here is the correct syntax for the SQL (all the rest looks fine):

"SELECT * FROM my_func($1, $2, $3)"


问:
Django JSONField dumping/loading
I'm using JSONField in some of my Django models and would like to migrate this data from Oracle to Postgres.

So far I haven't had any luck keeping this JSON data intact when using Django's dumpdata and loaddata commands, the data is transformed into string representations of the JSON. I've yet to find a good solution to this... Ideas?

答:
EDIT: If you end up using the package json - only then is the following solution applicable.

If you are using Python 2.6 and above you can use:

```<code>import json
</code>```

otherwise, you can use the simplejson that is bundled with django.utils (for Python < 2.6).

```<code>from django.utils import simplejson as json
</code>```

That way you can continue to use the same package name, and take your code to Google App Engine as it supports Python 2.5.2 at the moment.

Title: Django JSONField dumping/loading

Body:
EDIT: If you end up using the package json - only then is the following solution applicable.

If you are using Python 2.6 and above you can use:

import json

otherwise, you can use the simplejson that is bundled with django.utils (for Python < 2.6).

from django.utils import simplejson as json

That way you can continue to use the same package name, and take your code to Google App Engine as it supports Python 2.5.2 at the moment.


答:
Cardinality can not really be defined in the presence of polymorphic types. It is understood nowadays that polymorphic types "are not sets" as one might initially think. A famous pioneering argument by Reynolds was provided in his paper "Polymorphism is not set theoretic", proving that we can't simply interpret types with sets in the "trivial" way and obtain a meaningful notion.

Indeed, in sets 2^K and K are distinct cardinals, the first one being larger. Similarly, 2^(2^K) is larger than K. Yet, F X = 2^(2^X) (resembling F a = (a -> Bool) -> Bool) forms a (covariant) functor, for which we can find a fixed point

```<code>newtype T = T ((T -> Bool) -> Bool)
</code>```

obtaining T being isomorphic to 2^(2^T), which makes no sense in sets, precisely because they can't have the same cardinality.

(The type T above can be obtained even without recursive types, in the presence of polymorphism, through an encoding as forall a. (F a -> a) -> a.)

Anyway, to solve this impasse we need to interpret a -> Bool as something else than the set of functions 2^a. A possible solution is to use Scott-continuous functions, as done by Scott. A related solution is using stable functions (see Girard's "Proofs and types" book), which (if I recall correctly) makes the interpretations of T and T -> Bool to have the same cardinality (unless both are finite).

So, cardinality is not the right tool to use to check type isomorphism in the presence of polymorphic types. We really need to see if it is possible to craft the isomorphism function and its inverse, as the ones you posted in your question.

Title: How to understand that the types a and forall r. (a -> r) -> r are isomorphic

Body:
Cardinality can not really be defined in the presence of polymorphic types. It is understood nowadays that polymorphic types "are not sets" as one might initially think. A famous pioneering argument by Reynolds was provided in his paper "Polymorphism is not set theoretic", proving that we can't simply interpret types with sets in the "trivial" way and obtain a meaningful notion.

Indeed, in sets 2^K and K are distinct cardinals, the first one being larger. Similarly, 2^(2^K) is larger than K. Yet, F X = 2^(2^X) (resembling F a = (a -> Bool) -> Bool) forms a (covariant) functor, for which we can find a fixed point

newtype T = T ((T -> Bool) -> Bool)

obtaining T being isomorphic to 2^(2^T), which makes no sense in sets, precisely because they can't have the same cardinality.

(The type T above can be obtained even without recursive types, in the presence of polymorphism, through an encoding as forall a. (F a -> a) -> a.)

Anyway, to solve this impasse we need to interpret a -> Bool as something else than the set of functions 2^a. A possible solution is to use Scott-continuous functions, as done by Scott. A related solution is using stable functions (see Girard's "Proofs and types" book), which (if I recall correctly) makes the interpretations of T and T -> Bool to have the same cardinality (unless both are finite).

So, cardinality is not the right tool to use to check type isomorphism in the presence of polymorphic types. We really need to see if it is possible to craft the isomorphism function and its inverse, as the ones you posted in your question.


问:
Should I put input elements inside a label element?
Is there a best practice concerning the nesting of label and input HTML elements?

classic way:

My Text
<input type="text" id="myinput" />
```

<p>or</p>

<pre class="lang-html prettyprint-override"><code><label for="myinput">My Text
   <input type="text" id="myinput" />
</label>
</code>```

答:
One thing you need to consider is the interaction of checkbox and radio inputs with javascript.

Using below structure:

```<code><label>
  <input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
  <span>Label text</span>
</label>
</code>```

When user clicks on "Label text" controlCheckbox() function will be fired once.

But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.

Then you may have some bugs in your checkboxState.

I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.

Body:
Is there a best practice concerning the nesting of label and input HTML elements?

classic way:

My Text
<input type="text" id="myinput" />

or

My Text
   <input type="text" id="myinput" />

Body:
One thing you need to consider is the interaction of checkbox and radio inputs with javascript.

Using below structure:

<label>
  <input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
  <span>Label text</span>
</label>

When user clicks on "Label text" controlCheckbox() function will be fired once.

But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.

Then you may have some bugs in your checkboxState.

I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.


问:
EF Code First - 1-to-1 Optional Relationship
I want to map an optional 1-to-1 relationship in an existing database with EF Code First.

Simple schema:

```<code>User
 Username
 ContactID

Contact
 ID
 Name
</code>```

Obviously ContactID joins to Contact.ID. The ContactID field is nullable so the relationship is optional - 0 or 1, never many.

So how do I specify this relationship in EF Code First, with this existing schema?

Here's what I've tried so far:

```<code>public class User
{
    [Key]
    public string Username { get; set; }
    public int? ContactID { get; set; }

    [ForeignKey("ContactID")]
    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact)
    .WithOptionalDependent(c => c.User);
</code>```

I get the following Exception:

```<code>  System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role
 'User_Contact_Source' in relationship 'User_Contact'. Because the Dependent
Role properties are not the key properties, the upper bound of the multiplicity
of the Dependent Role must be *.
</code>```

答:
One solution would be;

```<code>public class User
{
    [Key]
    public string Username { get; set; }

    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

        modelBuilder.Entity<User>()
            .HasOptional<Contact>(u => u.Contact)
            .WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));
</code>```

You set only your navigational objects in your POCOs and instead you use fluent API to map your key to the correct column.

Body:
I want to map an optional 1-to-1 relationship in an existing database with EF Code First.

Simple schema:

User
 Username
 ContactID

Contact
 ID
 Name

Obviously ContactID joins to Contact.ID. The ContactID field is nullable so the relationship is optional - 0 or 1, never many.

So how do I specify this relationship in EF Code First, with this existing schema?

Here's what I've tried so far:

public class User
{
    [Key]
    public string Username { get; set; }
    public int? ContactID { get; set; }

    [ForeignKey("ContactID")]
    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact)
    .WithOptionalDependent(c => c.User);

I get the following Exception:

  System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role
 'User_Contact_Source' in relationship 'User_Contact'. Because the Dependent
Role properties are not the key properties, the upper bound of the multiplicity
of the Dependent Role must be *.

Body:
One solution would be;

public class User
{
    [Key]
    public string Username { get; set; }

    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

        modelBuilder.Entity<User>()
            .HasOptional<Contact>(u => u.Contact)
            .WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));

You set only your navigational objects in your POCOs and instead you use fluent API to map your key to the correct column.


问:
How to get difference between two lists in dart?
I am creating an app right now and I want to get the difference between two lists such:

List x = ['one' , 'two' , 'three' , 'four'];

List y = ['one' , 'two',];

------

Output: ['three' , 'four']
```

答:
This might be easier if you can use Set.difference instead.

If you're stuck with using lists this is a slightly shorter solution.

```<code>    var l = [1, 2, 3, 4];
    var r = [3, 4];
    l.removeWhere((e) => r.contains(e));
    print(l);
</code>```

Body:
This might be easier if you can use Set.difference instead.

If you're stuck with using lists this is a slightly shorter solution.

    var l = [1, 2, 3, 4];
    var r = [3, 4];
    l.removeWhere((e) => r.contains(e));
    print(l);


答:
Thats because a Tuple (1, 2) is different from a Tuple (2, 1)

```<code>print((1, 2) == (1, 2))
print((1, 2) == (2, 1))

True
False
</code>```

You can see it in:

```<code>my_set = set()

my_set.add((1, 2))
my_set.add((1, 2))
my_set.add((2, 1))

print(my_set)

{(1, 2), (2, 1)}
</code>```

So, in your case, you can sort your tuples, so both (1, 2) and (2, 1) will be the same, and the set will get your job done

```<code>mylist = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]

mylist = [sorted(item) for item in mylist]

mylist = list(set(map(tuple, mylist)))

print(mylist)

[(1, 2), (1, 3), (2, 3), (3, 3)]
</code>```

Title: How to remove duplicate combinations tuples from python list?

Body:
Thats because a Tuple (1, 2) is different from a Tuple (2, 1)

print((1, 2) == (1, 2))
print((1, 2) == (2, 1))

True
False

You can see it in:

my_set = set()

my_set.add((1, 2))
my_set.add((1, 2))
my_set.add((2, 1))

print(my_set)

{(1, 2), (2, 1)}

So, in your case, you can sort your tuples, so both (1, 2) and (2, 1) will be the same, and the set will get your job done

mylist = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]

mylist = [sorted(item) for item in mylist]

mylist = list(set(map(tuple, mylist)))

print(mylist)

[(1, 2), (1, 3), (2, 3), (3, 3)]


问:
How to merge result from multiple tables in efficient way Laravel
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

```<code>public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }
</code>```

I am looking for an efficient way to do the query and merge result in one collection.

答:
You may use collapse() method</p>

```<code>$collection = collect([$ml_8_machine, $ml_16_machine, $ml_32_machine, $ml_64_machine, $ml_96_machine, $ml_128_machine]);

$machines = $collection->collapse();

//dump($machines);

return view('vendor.machines', compact('machines'));
</code>```

Body:
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }

I am looking for an efficient way to do the query and merge result in one collection.

Body:
You may use collapse() method

$collection = collect([$ml_8_machine, $ml_16_machine, $ml_32_machine, $ml_64_machine, $ml_96_machine, $ml_128_machine]);

$machines = $collection->collapse();

//dump($machines);

return view('vendor.machines', compact('machines'));