问:
Using multiple TinyMCE editors on a single page
Using multiple textareas results in TinyMCE only using the last configuration, rather than applying the correct config to each textarea.

I've tried several answers from Stack Overflow. None of them solved the problem. Many answers are from previous versions of TinyMCE, but do not specify what version the answers are for -- which makes obsolete answers seem relevant when they're not. Most troubling is that the official documentation from TinyMCE 4 is also apparently wrong.

This is the "official" way to specify more than one selector:

```<code>    tinymce.init({

      selector: "#textarea1",

    });

</code>```

```<code>    tinymce.init({

      selector: "#textarea2",

    });

</code>```

The actual outcome is that TinyMCE only uses the last configuration ("#textarea2").

Other solutions that you find on Stack Overflow and elsewhere do not solve the problem (using "exact" mode, specifying "textareas", etc.). The official documentation for tinyMCE v4 also uses the above method, though it is clearly wrong.

You can see this in the docs for yourself at the following link: https://www.tiny.cloud/docs/general-configuration-guide/multiple-editors/

Since using more than one editor on a page is basic functionality, I don't understand how there are so many possible "right" answers to the same question (note: this question is specifically about tinyMCE version 4), and apparently no definitive simple, correct answer. There's no reason for it to be a question to spend hours answering in several different possible ways without a clear solution. We're not exactly sending humans to Mars, here...

Thanks in advance for help on this issue.

答:
As with @Tyeth I don't see where the documentation is wrong.  Here is a very simple TinyMCE Fiddle with two divs with different IDs that get different TinyMCE editor configurations based on two init({}) calls.

http://fiddle.tinymce.com/aJgaab/1

Perhaps if you are seeing different behavior you can provide a TinyMCE Fiddle or CodePen or JS Fiddle that shows your actual code?  Without actual code it will be really hard for anyone to tell you why your code is not working when we have multiple examples of this working.

Body:
Using multiple textareas results in TinyMCE only using the last configuration, rather than applying the correct config to each textarea.

I've tried several answers from Stack Overflow. None of them solved the problem. Many answers are from previous versions of TinyMCE, but do not specify what version the answers are for -- which makes obsolete answers seem relevant when they're not. Most troubling is that the official documentation from TinyMCE 4 is also apparently wrong.

This is the "official" way to specify more than one selector:

    tinymce.init({

      selector: "#textarea1",

    });

    tinymce.init({

      selector: "#textarea2",

    });

The actual outcome is that TinyMCE only uses the last configuration ("#textarea2").

Other solutions that you find on Stack Overflow and elsewhere do not solve the problem (using "exact" mode, specifying "textareas", etc.). The official documentation for tinyMCE v4 also uses the above method, though it is clearly wrong.

You can see this in the docs for yourself at the following link: https://www.tiny.cloud/docs/general-configuration-guide/multiple-editors/

Since using more than one editor on a page is basic functionality, I don't understand how there are so many possible "right" answers to the same question (note: this question is specifically about tinyMCE version 4), and apparently no definitive simple, correct answer. There's no reason for it to be a question to spend hours answering in several different possible ways without a clear solution. We're not exactly sending humans to Mars, here...

Thanks in advance for help on this issue.


来源: stackexchange

问:
Check the content of *args in a Class __init__
I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

```<code>class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()
</code>```

答:
self.args is, like @quamrana mentions, always of type tuple, and therefore never equal to 'ti' or of type list. That is why your current code doesn't print anything.

I believe the following does what you describe:

```<code>class MyClass:
    def __init__(self, *args):
        self.firstarg = args[0]

    def test_meth(self):
        if self.firstarg == 'ti':
            print('ti')
        elif type(self.firstarg) == list:
            if len(self.firstarg) == 1:
                print('it is a list with 1 value')
            else:
                print('full list')

my_object = MyClass('ti')
my_object.test_meth()
my_object = MyClass(['ti'])
my_object.test_meth()
my_object = MyClass(['ti', 'ti'])
my_object.test_meth()
</code>```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()

Body:
self.args is, like @quamrana mentions, always of type tuple, and therefore never equal to 'ti' or of type list. That is why your current code doesn't print anything.

I believe the following does what you describe:

class MyClass:
    def __init__(self, *args):
        self.firstarg = args[0]

    def test_meth(self):
        if self.firstarg == 'ti':
            print('ti')
        elif type(self.firstarg) == list:
            if len(self.firstarg) == 1:
                print('it is a list with 1 value')
            else:
                print('full list')

my_object = MyClass('ti')
my_object.test_meth()
my_object = MyClass(['ti'])
my_object.test_meth()
my_object = MyClass(['ti', 'ti'])
my_object.test_meth()

Hope this helps!


问:
JSON Schema to GraphQL schema converters
Are there any adapters which are converting JSON Schema schemas (e.g from Swagger) to GraphQL schemas?
There is even an official article about wrapping around REST http://graphql.org/blog/rest-api-graphql-wrapper/, but usually REST already described and Swagger is the most popular format for it.
Wouldn't like to write it by my own if there is already existing implementation.</p>

答:
Meanwhile several tools have been implemented to convert a JSON Schema to GraphQL Schema:

json-schema-to-graphql-types

jsonschema2graphql

json-schema-to-graphql-types-decorated

ContentLicense: CC BY-SA 3.0


问:
MySQL: Updating data from one column to another using two matching columns
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

```<code>UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"
</code>```

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1

答:
You may try this

UPDATE firms
INNER JOIN investors ON firms.id = investors.firm AND investors.firm_role = "ceo"
SET firms.ceo = investors.name

Body:
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1


问:
override paperclip has_attached_file settings that were set in a gem
In my project i have a gem that uses paperclip for file attachments. an example model in the gem:

```<code>class Example do
...
    has_attached_file :image,
      styles: { mini: '32x32>', normal: '128x128>' },
      default_style: :mini,
      url: '/example/url/:id/:style/:basename.:extension',
      path: ':rails_root/public/example/url/:id/:style/:basename.:extension',
...
end
</code>```

I want to modify the image so instead of having mini and normal sizes, i can add another size. I also want to change the path. How do i go about this? i tried creating a decorator like:

```<code>Example.class_eval do
    has_attached_file :image,
      styles: { mini: '32x32>', normal: '128x128>', large: '1024x1024' },
      default_style: :mini,
      url: '/example/url/:id/:style/:basename.:extension',
      path: 'updated/example/url/:id/:style/:basename.:extension',
end
</code>```

this didn't do anything.

答:
Not sure if you've solved this by now, but for any future viewers of this question...

You can do this by modifying the attachment_definitions property of the class. For instance you could add an initializer with:

```<code>Example.attachment_definitions[:image][:styles][:normal] = "1000x500"
Example.attachment_definitions[:image][:path] = '...'
</code>```

Body:
In my project i have a gem that uses paperclip for file attachments. an example model in the gem:

class Example do
...
    has_attached_file :image,
      styles: { mini: '32x32>', normal: '128x128>' },
      default_style: :mini,
      url: '/example/url/:id/:style/:basename.:extension',
      path: ':rails_root/public/example/url/:id/:style/:basename.:extension',
...
end

I want to modify the image so instead of having mini and normal sizes, i can add another size. I also want to change the path. How do i go about this? i tried creating a decorator like:

Example.class_eval do
    has_attached_file :image,
      styles: { mini: '32x32>', normal: '128x128>', large: '1024x1024' },
      default_style: :mini,
      url: '/example/url/:id/:style/:basename.:extension',
      path: 'updated/example/url/:id/:style/:basename.:extension',
end

this didn't do anything.

Body:
Not sure if you've solved this by now, but for any future viewers of this question...

You can do this by modifying the attachment_definitions property of the class. For instance you could add an initializer with:

Example.attachment_definitions[:image][:styles][:normal] = "1000x500"
Example.attachment_definitions[:image][:path] = '...'


问:
Implementing two sample t-test in C
I am making a function that will calculate the test statistic from a two sample t-test and return it's value. However, I have been getting incorrect results. I previously was using scanf and got good answers, but it randomly stopped working. So I decided to switch to fgets which is suppose to be more reliable, however, the values it's returning are incorrect.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define VAL 10

double tstat(int x1,int x2,int s1,int s2,int n1,int n2);

int main()
{
    char mean1[VAL] = {0};
    char sd1[VAL] = {0};
    char n1[VAL] = {0};

    char mean2[VAL] = {0};
    char sd2[VAL] = {0};
    char n2[VAL] = {0};

    printf("Enter mean 1: \n");
    fgets(mean1, 10, stdin);
    printf("Enter sd 1: \n");
    fgets(sd1, 10, stdin);
    printf("Enter sample size 1: \n");
    fgets(n1, 10, stdin);

    printf("Enter mean 2: \n");
    fgets(mean2, 10, stdin);
    printf("Enter sd 2: \n");
    fgets(sd2, 10, stdin);
    printf("Enter n2: \n");
    fgets(n2, 10, stdin);

    printf("t value is: %lf", tstat(atoi(mean1),atoi(mean2),atoi(sd1),atoi(sd2),atoi(n1),atoi(n2)));
}

double tstat(int x1,int x2,int s1,int s2,int n1,int n2)
{
    double t = 0;

    t = (x1 - x2)/(sqrt(pow(s1,2)/n1+pow(s2,2)/n2));

    return t;
}
</code>```

For example, setting mean1 = 1.3, sd1 = 0.5, n1 = 22; mean2 = 1.6,sd2 = 0.3, n2 = 24 should yield a value of -2.44, however, plugging this in returns -1 followed by #IND00. I presume my issue is that either I am misinterpreting how to properly use fgets, or something is going wonky with the datatypes, though I am a beginner in C, and I have not been able to spot any clear errors.

答:
Your variables are all of type int and you're using atoi to convert the strings to int.  However, the values you're entering aren't integers, they're floating point values, so only the integer part of each number is interpreted.  For example, atoi("1.3") results in 1.

You need to change your datatypes to double and use atof instead.

```<code>double tstat(double x1, double x2, double s1, double s2, double n1, double n2)
{
    double t = 0;

    t = (x1 - x2)/(sqrt(pow(s1,2)/n1+pow(s2,2)/n2));

    return t;
}

...

printf("t value is: %lf", tstat(atof(mean1),atof(mean2),atof(sd1),atof(sd2),atof(n1),atof(n2)));
</code>```

Title: Implementing two sample t-test in C

Body:
I am making a function that will calculate the test statistic from a two sample t-test and return it's value. However, I have been getting incorrect results. I previously was using scanf and got good answers, but it randomly stopped working. So I decided to switch to fgets which is suppose to be more reliable, however, the values it's returning are incorrect.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define VAL 10

double tstat(int x1,int x2,int s1,int s2,int n1,int n2);

int main()
{
    char mean1[VAL] = {0};
    char sd1[VAL] = {0};
    char n1[VAL] = {0};

    char mean2[VAL] = {0};
    char sd2[VAL] = {0};
    char n2[VAL] = {0};

    printf("Enter mean 1: \n");
    fgets(mean1, 10, stdin);
    printf("Enter sd 1: \n");
    fgets(sd1, 10, stdin);
    printf("Enter sample size 1: \n");
    fgets(n1, 10, stdin);

    printf("Enter mean 2: \n");
    fgets(mean2, 10, stdin);
    printf("Enter sd 2: \n");
    fgets(sd2, 10, stdin);
    printf("Enter n2: \n");
    fgets(n2, 10, stdin);

    printf("t value is: %lf", tstat(atoi(mean1),atoi(mean2),atoi(sd1),atoi(sd2),atoi(n1),atoi(n2)));
}

double tstat(int x1,int x2,int s1,int s2,int n1,int n2)
{
    double t = 0;

    t = (x1 - x2)/(sqrt(pow(s1,2)/n1+pow(s2,2)/n2));

    return t;
}

For example, setting mean1 = 1.3, sd1 = 0.5, n1 = 22; mean2 = 1.6,sd2 = 0.3, n2 = 24 should yield a value of -2.44, however, plugging this in returns -1 followed by #IND00. I presume my issue is that either I am misinterpreting how to properly use fgets, or something is going wonky with the datatypes, though I am a beginner in C, and I have not been able to spot any clear errors.

Body:
Your variables are all of type int and you're using atoi to convert the strings to int.  However, the values you're entering aren't integers, they're floating point values, so only the integer part of each number is interpreted.  For example, atoi("1.3") results in 1.

You need to change your datatypes to double and use atof instead.

double tstat(double x1, double x2, double s1, double s2, double n1, double n2)
{
    double t = 0;

    t = (x1 - x2)/(sqrt(pow(s1,2)/n1+pow(s2,2)/n2));

    return t;
}

...

printf("t value is: %lf", tstat(atof(mean1),atof(mean2),atof(sd1),atof(sd2),atof(n1),atof(n2)));


问:
Prevent DB query if relation was not loaded
I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

```<code>$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}
</code>```

, on the each $city->country call I have a query to DB

```<code>select * from `countries` where `countries`.`id` = ? limit 1
</code>```

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

I no need the $country variable. I need to get null if relation cities.country was not loaded in the main query.

答:
Why not doing the inverse then:

```<code>$cities = City::with('country')->get();

// this way you would loop only once:

foreach ($cities as $city) {
    dump($city->country);
}
</code>```

Using your approach then this :

```<code>foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($country);
        // here the $country variable
       // is the same as the $city->country one, so no need to query it again..
    }
}
</code>```

Body:
I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}

, on the each $city->country call I have a query to DB

select * from `countries` where `countries`.`id` = ? limit 1

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

I no need the $country variable. I need to get null if relation cities.country was not loaded in the main query.

Body:
Why not doing the inverse then:

$cities = City::with('country')->get();

// this way you would loop only once:

foreach ($cities as $city) {
    dump($city->country);
}

Using your approach then this :

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($country);
        // here the $country variable
       // is the same as the $city->country one, so no need to query it again..
    }
}


问:
output of 'iptables -L -nv' commands meaning
root@linux #iptables -L -nv

The output looks like this

```<code>Chain INPUT (policy ACCEPT 89658 packets, 116M bytes)
 pkts bytes target     prot opt in     out     source               destination
 122K   97M ACCEPT     all  --  *      *       192.168.43.104       0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 70753 packets, 70M bytes)
 pkts bytes target     prot opt in     out     source               destination
 141K   61M ACCEPT     all  --  *      *       0.0.0.0/0            192.168.43.104
</code>```

what relation between Chain INPUT (policy ACCEPT 89658 packets, 116M bytes)
and below that line.
and Chain OUTPUT (policy ACCEPT 70753 packets, 70M bytes)
and it's below the line.

I get confused what is 70753 packets vs 141K pkts and 70M vs 61M

答:
Chain INPUT means how much traffic you have received
Chain OUTPUT mean how much traffic your machine sent to the network.

Thus the request to the WEB page will create outgoing traffic(OUTPUT counters will be increased) and after WEB server reply you will receive incoming traffic(INPUT counter will be increased)

Body:
root@linux #iptables -L -nv

The output looks like this

Chain INPUT (policy ACCEPT 89658 packets, 116M bytes)
 pkts bytes target     prot opt in     out     source               destination
 122K   97M ACCEPT     all  --  *      *       192.168.43.104       0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 70753 packets, 70M bytes)
 pkts bytes target     prot opt in     out     source               destination
 141K   61M ACCEPT     all  --  *      *       0.0.0.0/0            192.168.43.104

what relation between Chain INPUT (policy ACCEPT 89658 packets, 116M bytes)
and below that line.
and Chain OUTPUT (policy ACCEPT 70753 packets, 70M bytes)
and it's below the line.

I get confused what is 70753 packets vs 141K pkts and 70M vs 61M


问:
To get the date difference between a datetime and nullable datetime
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

```<code>public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}
</code>```

Controller Action :

```<code>public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}
</code>```

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

答:
```<code>public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}

public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (int)(model.Date1 - (model.Date2 ?? today)).TotalDays;
    return View(model);
}
</code>```

Body:
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}

Controller Action :

public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?


问:
How to create dataframe of output
I run a query to a webserver with certain added criteria.
I specify a date range which alters the date in the url.
I then pull the data line for specified symbols and I get a list of short volume etc. for the specified stock and time frame.
However, I want to be able to get the output as a dataframe.
The dataframe is now still the stored dataframe from the last ran url, and not of the output.

I tried to use list_.append which I did not get to work.

```<code>import pandas as pd
from datetime import datetime
import urllib

symbols = ['AABA']

start_date = datetime(2019, 5, 10 )
end_date = datetime(2019, 5, 15 )

datelist = pd.date_range(start_date, periods=(end_date-start_date).days+1).tolist()

for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)].to_string(index=False, header=False)
            print(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue
</code>```

The result is now:

```<code>20190510  AABA  2300.0  0.0  14617.0  N
20190513  AABA  2816.0  0.0  39128.0  N
20190514  AABA  1761.0  0.0  26191.0  N
20190515  AABA  24092.0  0.0  62745.0  N
</code>```

I want the result to be in a dataframe so that I can directly export the result to csv

答:
Why do you convert dataframe to string when you want the output to be a dataframe? (For example, df[df['Symbol'].isin(symbols)].to_csv('ABBA.csv', index=False, header=False)) Anyways, to convert string back to dataframe you can use pandas.read_fwf:

```<code>from io import StringIO

df=pd.read_fwf(StringIO(stocks), header=None)
</code>```

OUTPUT:

```<code>          0     1        2    3        4  5
0  20190510  AABA   2300.0  0.0  14617.0  N
1  20190513  AABA   2816.0  0.0  39128.0  N
2  20190514  AABA   1761.0  0.0  26191.0  N
3  20190515  AABA  24092.0  0.0  62745.0  N
</code>```

Title: How to create dataframe of output

Body:
I run a query to a webserver with certain added criteria.
I specify a date range which alters the date in the url.
I then pull the data line for specified symbols and I get a list of short volume etc. for the specified stock and time frame.
However, I want to be able to get the output as a dataframe.
The dataframe is now still the stored dataframe from the last ran url, and not of the output.

I tried to use list_.append which I did not get to work.

import pandas as pd
from datetime import datetime
import urllib

symbols = ['AABA']

start_date = datetime(2019, 5, 10 )
end_date = datetime(2019, 5, 15 )

datelist = pd.date_range(start_date, periods=(end_date-start_date).days+1).tolist()

for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)].to_string(index=False, header=False)
            print(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue

The result is now:

20190510  AABA  2300.0  0.0  14617.0  N
20190513  AABA  2816.0  0.0  39128.0  N
20190514  AABA  1761.0  0.0  26191.0  N
20190515  AABA  24092.0  0.0  62745.0  N

I want the result to be in a dataframe so that I can directly export the result to csv

Body:
Why do you convert dataframe to string when you want the output to be a dataframe? (For example, df[df['Symbol'].isin(symbols)].to_csv('ABBA.csv', index=False, header=False)) Anyways, to convert string back to dataframe you can use pandas.read_fwf:

from io import StringIO

df=pd.read_fwf(StringIO(stocks), header=None)

OUTPUT:

          0     1        2    3        4  5
0  20190510  AABA   2300.0  0.0  14617.0  N
1  20190513  AABA   2816.0  0.0  39128.0  N
2  20190514  AABA   1761.0  0.0  26191.0  N
3  20190515  AABA  24092.0  0.0  62745.0  N


问:
regexp to match simple markdown
I'm trying to figure out the regexp to match all the occurences of *this kind of strings*. Two additional rules unfortunately made this thing more complicated than I thought:

tagged string should start with * followed by non-whitespace character (so * this one* should not be matched

tagged string should end with non-whitespace followed by * followed by whitespace (so *this one * and *this o*ne should not be matched

I started with simplest regexp \*\S([^\*]+)?\* which for my testing string:

*foo 1 * 2 bar* foo *b* azz *qu **ux*

matches places in square brackets:

[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]

and this is what I'd like to achieve:

[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]

so 2 problems appear:

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

how to match whitespace from rule 2. but not include it into result, which \*\S([^\*]+)?\*\s would do?

答:
I used full matches and not the groups and it matched your test string perfect:</p>

```<code>"(?<=\\s|^)\\*(?:\\S|\\S.*?\\S)\\*(?=\\s)"
</code>```

Title: regexp to match simple markdown

Body:
I used full matches and not the groups and it matched your test string perfect:

"(?<=\\s|^)\\*(?:\\S|\\S.*?\\S)\\*(?=\\s)"


问:
Trying to access dataTable variable outside ajax is giving undefined
I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.

I'm doing the same as in this example, only difference is the data is coming from an Ajax request.

Can you please help me understand why is that happening?

$(document).ready(function() {
  var campId;
  var t_OmnitureCode;

  // Campaign input autocomplete
  $("#campaign").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "promotion",
        type: "GET",
        data: {
          term: request.term,
          action: "searchCampaign"
        },
        dataType: "json",
        success: function(data) {
          if (!data.length) {
            var result = [{
              label: "no match found",
              value: "-1"
            }];
            response(result);
          } else {
            response($.map(data, function(item) {
              return {
                label: item.name,
                value: item.campaignId
              }
            }));
          }
        }
      });
    },
    select: function(event, ui) {
      event.preventDefault();
      campId = ui.item.value;
      if (campId != "-1") {
        this.value = ui.item.label;

        // This will apply datatables getting the content from an Ajax call
        t_OmnitureCode = applyDataTableOmnitureCode(campId);
      }
    },
    focus: function(event, ui) {
      event.preventDefault();
      this.value = ui.item.label;
    }
  });

  // Handling form submission
  $("#frm_promotion").on("submit", function(e) {
    var form = this;
    // Variable for datatable "t_OmnitureCode" is undefined below
    var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
```

<p><strong>EDIT:</strong>
Just realized that even while assigning the variable (<code>t_OmnitureCode = applyDataTableOmnitureCode(campId);</code>) it is undefined, not sure why.</p>

<p>Here is the applyDataTableOmnitureCode code:</p>

```function applyDataTableOmnitureCode(campId) {
    $("#tbl_omnitureCode").DataTable({
        destroy: true,
        scrollX: true,
        fixedColumns: {
            leftColumns: 1
        },
        "ajax": {
            "url": "promotion",
            "type": "GET",
            "data": {
                action: "searchOmnitureCodesByCampaignId",
                campaignId: campId
            },
            "dataSrc": ""
        },
        "columns": [
            { "data": "key" },
            { "data": "omnitureCode" },
            { "data": "urlAppName" },
            { "data": "language" },
            { "data": "channel" },
            { "data": "createDateTime", "defaultContent": "" },
            { "data": "updateDateTime", "defaultContent": "" }
        ],
        "columnDefs": [
            { "targets": 0, "checkboxes": { "selectRow": true } }
        ],
        "select": {
            "style": "multi"
        },
        "order": [[1, "asc"]],
        "fnInitComplete": function() {
            $("#omnitureCodeSection").show();
        }
    });
};
```

答:
You may need to grab your DataTables object into a variable before using that:

```<code>var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
</code>```

And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).

You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.

Body:
I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.

I'm doing the same as in this example, only difference is the data is coming from an Ajax request.

Can you please help me understand why is that happening?

$(document).ready(function() {
  var campId;
  var t_OmnitureCode;

  // Campaign input autocomplete
  $("#campaign").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "promotion",
        type: "GET",
        data: {
          term: request.term,
          action: "searchCampaign"
        },
        dataType: "json",
        success: function(data) {
          if (!data.length) {
            var result = [{
              label: "no match found",
              value: "-1"
            }];
            response(result);
          } else {
            response($.map(data, function(item) {
              return {
                label: item.name,
                value: item.campaignId
              }
            }));
          }
        }
      });
    },
    select: function(event, ui) {
      event.preventDefault();
      campId = ui.item.value;
      if (campId != "-1") {
        this.value = ui.item.label;

        // This will apply datatables getting the content from an Ajax call
        t_OmnitureCode = applyDataTableOmnitureCode(campId);
      }
    },
    focus: function(event, ui) {
      event.preventDefault();
      this.value = ui.item.label;
    }
  });

  // Handling form submission
  $("#frm_promotion").on("submit", function(e) {
    var form = this;
    // Variable for datatable "t_OmnitureCode" is undefined below
    var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();

EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.

Here is the applyDataTableOmnitureCode code:

function applyDataTableOmnitureCode(campId) {
    $("#tbl_omnitureCode").DataTable({
        destroy: true,
        scrollX: true,
        fixedColumns: {
            leftColumns: 1
        },
        "ajax": {
            "url": "promotion",
            "type": "GET",
            "data": {
                action: "searchOmnitureCodesByCampaignId",
                campaignId: campId
            },
            "dataSrc": ""
        },
        "columns": [
            { "data": "key" },
            { "data": "omnitureCode" },
            { "data": "urlAppName" },
            { "data": "language" },
            { "data": "channel" },
            { "data": "createDateTime", "defaultContent": "" },
            { "data": "updateDateTime", "defaultContent": "" }
        ],
        "columnDefs": [
            { "targets": 0, "checkboxes": { "selectRow": true } }
        ],
        "select": {
            "style": "multi"
        },
        "order": [[1, "asc"]],
        "fnInitComplete": function() {
            $("#omnitureCodeSection").show();
        }
    });
};

Body:
You may need to grab your DataTables object into a variable before using that:

var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();

And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).

You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.


问:
how to restrict indentation while using jq filters on json file
My input JSON file is:

```<code>{
    "name": "abc",
    "private": true,
    "version": "1.0.0",
    "description": "UI",
    "dependencies": {
        "xyz": "9.11",
        "abc": "5.0.0"
    }
}
</code>```

When I use jq .name=xyz, the output will be printed as:

```<code>{
  "name": "xyz",
  "private": true,
  "version": "1.0.0",
  "description": "UI",
  "dependencies": {
    "xyz": "9.11",
    "abc": "5.0.0"
  }
}
</code>```

Though my input file as proper indentation, after running the jq command the indentation is different.

How can I restrict the indentation?

Thanks in advance!

答: There is currently no way to instruct jq to preserve the indentation style per se, but the --indent N and --tab command-line options give limited control over the style of indentation.  Thus, in the particular case given, one could achieve the desired effect using --indent 4.

Body:
My input JSON file is:

{
    "name": "abc",
    "private": true,
    "version": "1.0.0",
    "description": "UI",
    "dependencies": {
        "xyz": "9.11",
        "abc": "5.0.0"
    }
}

When I use jq .name=xyz, the output will be printed as:

{
  "name": "xyz",
  "private": true,
  "version": "1.0.0",
  "description": "UI",
  "dependencies": {
    "xyz": "9.11",
    "abc": "5.0.0"
  }
}

Though my input file as proper indentation, after running the jq command the indentation is different.

How can I restrict the indentation?

Thanks in advance!


问:
How to prevent form submission until onsubmit function completes?
For my onsubmit function, I have a function that requests for user's location and adds their location to the input values of my form.
However, when the user clicks on the submit button and a pop-up appears and asks the user to allow the browser to know their location, my form always submits before the user could answer the pop-up. This leaves the function incompleted and the input values become undefined.

I have tried adding a "return true;" statement until my onsubmit function ends, but the form still gets submitted prior. I have also tried adding  "e.preventDefault();" before my function completes. None of the methods worked so far...

My form:

<form action="/login" onsubmit="getLocation()" method="POST">
    <button type="submit" class="btn btn-dark">Login</button>
    <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
    <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">
</form>
```

<p>The onsubmit function:  </p>

```function getLocation(e) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        return true;
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function onGeoSuccess(position) {
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;
}

function onGeoError(err) {
    alert("Error code " + err.code + ". " + err.message);
}
```

答:
First, you should ask permission on page load:

```<code><body onload="getLocation()">
</code>```

Second, you should use a flag (variable) to track the status of the Geo location success. And finally if there was no error the form is ready for submit.

```<code>var anErrorOccured = true;

function getLocation ()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition (onGeoSuccess);
    }
}

function onGeoSuccess(position)
{
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;

    anErrorOccured = false;
}

function submitData ()
{
    if (anErrorOccured)
    {
        return false;
    }
    else
    {
        return true;
    }
}
</code>```

Basically the anErrorOccured variable is set to true and only if the position is set successfully you will mark it as false.
And don't forgot to use 'return' when attaching some function to onsubmit event:

```<code><form action="/login" onsubmit="return submitData()" method="POST">
</code>```

You can also disable your submit button based on this flag, to be more user friendly.

Body:
For my onsubmit function, I have a function that requests for user's location and adds their location to the input values of my form.
However, when the user clicks on the submit button and a pop-up appears and asks the user to allow the browser to know their location, my form always submits before the user could answer the pop-up. This leaves the function incompleted and the input values become undefined.

I have tried adding a "return true;" statement until my onsubmit function ends, but the form still gets submitted prior. I have also tried adding  "e.preventDefault();" before my function completes. None of the methods worked so far...

My form:

<form action="/login" onsubmit="getLocation()" method="POST">
    <button type="submit" class="btn btn-dark">Login</button>
    <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
    <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">
</form>

The onsubmit function:

function getLocation(e) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        return true;
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function onGeoSuccess(position) {
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;
}

function onGeoError(err) {
    alert("Error code " + err.code + ". " + err.message);
}

Body:
First, you should ask permission on page load:

<body onload="getLocation()">

Second, you should use a flag (variable) to track the status of the Geo location success. And finally if there was no error the form is ready for submit.

var anErrorOccured = true;

function getLocation ()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition (onGeoSuccess);
    }
}

function onGeoSuccess(position)
{
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;

    anErrorOccured = false;
}

function submitData ()
{
    if (anErrorOccured)
    {
        return false;
    }
    else
    {
        return true;
    }
}

Basically the anErrorOccured variable is set to true and only if the position is set successfully you will mark it as false.
And don't forgot to use 'return' when attaching some function to onsubmit event:

<form action="/login" onsubmit="return submitData()" method="POST">

You can also disable your submit button based on this flag, to be more user friendly.


问:
Error in System.Net.HttpWebRequest.GetResponse() "ResponceSystem.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel"
Dotnet application is built with dotnet 4.5. On a few system, we are getting this error while connecting to the web server where few changes were made in SSL recently.

Web server TLS only 1.2
https://drive.google.com/open?id=1Z0S-MWugDZdQrIy3BnquooB0ZX7veIVT

Client side code.

```<code>WebRequest webRequest = WebRequest.Create(strUrl);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "Get";
if (strUrl.StartsWith("HTTPS", StringComparison.OrdinalIgnoreCase)) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
using (WebResponse webResponse = webRequest.GetResponse())
{
    if (webResponse == null) return blnResult;
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
       strSuccess = sr.ReadToEnd().Trim();
       blnResult = true;
    }
}
</code>```

As soon as I compile it with framework 4.6.2 it works.

Why it is working on few system with same 4.5 compiled EXE and on few system it needs to be compiled with 4.6.2?

WebClient class works fine with 4.5 version of dotnet framework. Only WebRequest is not working.

答:
Need to set security protocol first before initializing WebRequest object.</p>

```<code>if (strUrl.StartsWith("HTTPS", StringComparison.OrdinalIgnoreCase)) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

WebRequest webRequest = WebRequest.Create(strUrl);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "Get";

using (WebResponse webResponse = webRequest.GetResponse())
{
    if (webResponse == null) return blnResult;
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
       strSuccess = sr.ReadToEnd().Trim();
       blnResult = true;
    }
}
</code>```

Body:
Dotnet application is built with dotnet 4.5. On a few system, we are getting this error while connecting to the web server where few changes were made in SSL recently.

Web server TLS only 1.2
https://drive.google.com/open?id=1Z0S-MWugDZdQrIy3BnquooB0ZX7veIVT

Client side code.

WebRequest webRequest = WebRequest.Create(strUrl);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "Get";
if (strUrl.StartsWith("HTTPS", StringComparison.OrdinalIgnoreCase)) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
using (WebResponse webResponse = webRequest.GetResponse())
{
    if (webResponse == null) return blnResult;
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
       strSuccess = sr.ReadToEnd().Trim();
       blnResult = true;
    }
}

As soon as I compile it with framework 4.6.2 it works.

Why it is working on few system with same 4.5 compiled EXE and on few system it needs to be compiled with 4.6.2?

WebClient class works fine with 4.5 version of dotnet framework. Only WebRequest is not working.

Body:
Need to set security protocol first before initializing WebRequest object.

if (strUrl.StartsWith("HTTPS", StringComparison.OrdinalIgnoreCase)) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

WebRequest webRequest = WebRequest.Create(strUrl);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "Get";

using (WebResponse webResponse = webRequest.GetResponse())
{
    if (webResponse == null) return blnResult;
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
       strSuccess = sr.ReadToEnd().Trim();
       blnResult = true;
    }
}


问:
Loading a file from an API causing an error because of parsing to JSON
I am loading a xlsx file from an API. But loading causes an error because Angular trys to parse the body to JSON.

It is working if I give the request directly the response type like this:

this.http.get(this.url + "/getExcel",{responseType:'blob'});
```

<p>But in my backend I also need an authorization. And if I give the request a HttpHeaders object it isn't working:</p>

<pre class="lang-js prettyprint-override"><code>const headers = new HttpHeaders({
    responseType:'blob',
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{headers});
</code>```

I think the both above should do the same. Shouldn't it?

答:
You're combining the wrong things. You should do this: </p>

```<code>const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{
    headers,
    responseType: 'blob'
});
</code>```

Body:
I am loading a xlsx file from an API. But loading causes an error because Angular trys to parse the body to JSON.

It is working if I give the request directly the response type like this:

this.http.get(this.url + "/getExcel",{responseType:'blob'});

But in my backend I also need an authorization. And if I give the request a HttpHeaders object it isn't working:

const headers = new HttpHeaders({
    responseType:'blob',
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{headers});

I think the both above should do the same. Shouldn't it?

Body:
You're combining the wrong things. You should do this:

const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{
    headers,
    responseType: 'blob'
});


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答:
For the STL at least there are tools available that will output more human-friendly error messages. See http://www.bdsoft.com/tools/stlfilt.html

For non-STL templates you'll just have to learn what the errors mean. After you've seen them a dozen times it becomes easier to guess what the problem is. If you post them here maybe somebody can help you figure it out.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Segonds

OwnerDisplayName: Michel


问:
How to Selenium test Django project that retrieves data through APIs?
I have a Django Project. I want to make end-to-end tests for it using Selenium.
It interacts with Other components (usually run through docker-compose) API and functions properly.

The Django Project and 'Other Components' are different repositories (obviously there are multiple 'other components')

Testing of parts that don't involve API calls, have been tested.

答:
You can use a continuous integration like Jenkins to do your automated task like Selenium.

It's really easy to install localy and/or  to serve.

How to install Jenkins : here

have a great day!


问:
Why Am I Getting The Incorrect Levenshtein Distance?
I am attempting to implement the Levenshtein Distance algorithm in C# (for practice and because it'd be handy to have).  I used an implementation from the Wikipedia page but for some reason I'm getting the wrong distance on one set of words.  Here's the code (from LinqPad):

```<code>void Main()
{
   var ld = new LevenshteinDistance();
   int dist = ld.LevenshteinDistanceCalc("sitting","kitten");
   dist.Dump();
}

// Define other methods and classes here
public class LevenshteinDistance
{
   private int[,] distance;

   public int LevenshteinDistanceCalc(string source, string target)
   {
      int sourceSize = source.Length, targetSize = target.Length;
      distance = new int[sourceSize, targetSize];
      for (int sIndex = 0; sIndex < sourceSize; sIndex++)
      {
         distance[sIndex, 0] = sIndex;
      }
      for (int tIndex = 0; tIndex < targetSize; tIndex++)
      {
         distance[0,tIndex] = tIndex;
      }
      //      for j from 1 to n:
      //      for i from 1 to m:
      //          if s[i] = t[j]:
      //            substitutionCost:= 0
      //          else:
      //            substitutionCost:= 1
      //          d[i, j] := minimum(d[i - 1, j] + 1,                   // deletion
      //                             d[i, j - 1] + 1,                   // insertion
      //                             d[i - 1, j - 1] + substitutionCost)  // substitution
      //
      //
      //      return d[m, n]

      for (int tIndex = 1; tIndex < targetSize; tIndex++)
      {
         for (int sIndex = 1; sIndex < sourceSize; sIndex++)
         {
            int substitutionCost = source[sIndex] == target[tIndex] ? 0 : 1;
            int deletion = distance[sIndex-1, tIndex]+1;
            int insertion = distance[sIndex,tIndex-1]+1;
            int substitution = distance[sIndex-1, tIndex-1] + substitutionCost;

            distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);

         }
      }
      return distance[sourceSize-1,targetSize-1];
   }

   private int leastOfThree(int a, int b, int c)
   {
      return Math.Min(a,(Math.Min(b,c)));
   }
}
</code>```

When I try "sitting" and "kitten" I get an LD of 2 (should be 3).  Yet when I try "Saturday" and "Sunday" I get an LD of 3 (which is correct).  I know something's wrong but I can't figure out what I'm missing.

答:
The example on wikipedia uses 1-based strings. In C# we use 0-based strings.

In their matrix the 0-row and 0-column does exist. So the size of their matrix is [source.Length + 1, source.Length + 1] In your code it doesn't exist.

```<code>public int LevenshteinDistanceCalc(string source, string target)
{
  int sourceSize = source.Length, targetSize = target.Length;
  distance = new int[sourceSize + 1, targetSize + 1];
  for (int sIndex = 1; sIndex <= sourceSize; sIndex++)
    distance[sIndex, 0] = sIndex;

  for (int tIndex = 1; tIndex <= targetSize; tIndex++)
    distance[0, tIndex] = tIndex;

  for (int tIndex = 1; tIndex <= targetSize; tIndex++)
  {
    for (int sIndex = 1; sIndex <= sourceSize; sIndex++)
    {
      int substitutionCost = source[sIndex-1] == target[tIndex-1] ? 0 : 1;
      int deletion = distance[sIndex - 1, tIndex] + 1;
      int insertion = distance[sIndex, tIndex - 1] + 1;
      int substitution = distance[sIndex - 1, tIndex - 1] + substitutionCost;

      distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);
    }
  }
  return distance[sourceSize, targetSize];
}
</code>```

Body:
I am attempting to implement the Levenshtein Distance algorithm in C# (for practice and because it'd be handy to have).  I used an implementation from the Wikipedia page but for some reason I'm getting the wrong distance on one set of words.  Here's the code (from LinqPad):

void Main()
{
   var ld = new LevenshteinDistance();
   int dist = ld.LevenshteinDistanceCalc("sitting","kitten");
   dist.Dump();
}

// Define other methods and classes here
public class LevenshteinDistance
{
   private int[,] distance;

   public int LevenshteinDistanceCalc(string source, string target)
   {
      int sourceSize = source.Length, targetSize = target.Length;
      distance = new int[sourceSize, targetSize];
      for (int sIndex = 0; sIndex < sourceSize; sIndex++)
      {
         distance[sIndex, 0] = sIndex;
      }
      for (int tIndex = 0; tIndex < targetSize; tIndex++)
      {
         distance[0,tIndex] = tIndex;
      }
      //      for j from 1 to n:
      //      for i from 1 to m:
      //          if s[i] = t[j]:
      //            substitutionCost:= 0
      //          else:
      //            substitutionCost:= 1
      //          d[i, j] := minimum(d[i - 1, j] + 1,                   // deletion
      //                             d[i, j - 1] + 1,                   // insertion
      //                             d[i - 1, j - 1] + substitutionCost)  // substitution
      //
      //
      //      return d[m, n]

      for (int tIndex = 1; tIndex < targetSize; tIndex++)
      {
         for (int sIndex = 1; sIndex < sourceSize; sIndex++)
         {
            int substitutionCost = source[sIndex] == target[tIndex] ? 0 : 1;
            int deletion = distance[sIndex-1, tIndex]+1;
            int insertion = distance[sIndex,tIndex-1]+1;
            int substitution = distance[sIndex-1, tIndex-1] + substitutionCost;

            distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);

         }
      }
      return distance[sourceSize-1,targetSize-1];
   }

   private int leastOfThree(int a, int b, int c)
   {
      return Math.Min(a,(Math.Min(b,c)));
   }
}

When I try "sitting" and "kitten" I get an LD of 2 (should be 3).  Yet when I try "Saturday" and "Sunday" I get an LD of 3 (which is correct).  I know something's wrong but I can't figure out what I'm missing.

Body:
The example on wikipedia uses 1-based strings. In C# we use 0-based strings.

In their matrix the 0-row and 0-column does exist. So the size of their matrix is [source.Length + 1, source.Length + 1] In your code it doesn't exist.

public int LevenshteinDistanceCalc(string source, string target)
{
  int sourceSize = source.Length, targetSize = target.Length;
  distance = new int[sourceSize + 1, targetSize + 1];
  for (int sIndex = 1; sIndex <= sourceSize; sIndex++)
    distance[sIndex, 0] = sIndex;

  for (int tIndex = 1; tIndex <= targetSize; tIndex++)
    distance[0, tIndex] = tIndex;

  for (int tIndex = 1; tIndex <= targetSize; tIndex++)
  {
    for (int sIndex = 1; sIndex <= sourceSize; sIndex++)
    {
      int substitutionCost = source[sIndex-1] == target[tIndex-1] ? 0 : 1;
      int deletion = distance[sIndex - 1, tIndex] + 1;
      int insertion = distance[sIndex, tIndex - 1] + 1;
      int substitution = distance[sIndex - 1, tIndex - 1] + substitutionCost;

      distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);
    }
  }
  return distance[sourceSize, targetSize];
}


答:
You can use the null coalescing operator (??) to make sure you are using a non-nullable value in the calculation like this.

```<code>model.Diff = (model.Date1 - (model.Date2 ?? today)).Days;
</code>```

This ensures that the calculation is done on two DateTimes instead of a DateTime and a DateTime?.  When one value in a calculation is nullable the result is going to be nullable.

Title: To get the date difference between a datetime and nullable datetime

Body:
You can use the null coalescing operator (??) to make sure you are using a non-nullable value in the calculation like this.

model.Diff = (model.Date1 - (model.Date2 ?? today)).Days;

This ensures that the calculation is done on two DateTimes instead of a DateTime and a DateTime?.  When one value in a calculation is nullable the result is going to be nullable.


问:
Is there a way to print a link to a javascript source file and line number in the devtools console with a console.print statement?
I have some console.log prints that are triggered in a specific javascript file. This file is aware of other files, and it make references to those filenames in the console.log prints. I was wondering if there was a way I could print some sort of link to that source file in the same console.log print out, with the hopeful behavior that clicking the link would open the source view of that file in dev tools?</p>

答:
Found out by trying out @miir's solution that you can:

1) Link to a file as long as you put the full path

```<code>console.log("http://localhost:8000/myapp/path/to/file.js")
console.log(document.currentScript.src); // if executed from within a script
</code>```

2) Link to a file + line + character manually

```<code>const line = "83";
const character = "2";
console.log(document.currentScript.src + ":" + line + ":" + character);
</code>```

3) Link to a file + line + character dynamically

```<code>const level = 1; // 1 is last stack trace, you can go up the calling functions
console.log(new Error().stack.split("\n")[level].match(/http[^\)]+/)[0]);
</code>```

Nothing that couldn't be figured out from the accepted answer, but maybe it can help newcomers.

Body:
Found out by trying out @miir's solution that you can:

1) Link to a file as long as you put the full path

console.log("http://localhost:8000/myapp/path/to/file.js")
console.log(document.currentScript.src); // if executed from within a script

2) Link to a file + line + character manually

const line = "83";
const character = "2";
console.log(document.currentScript.src + ":" + line + ":" + character);

3) Link to a file + line + character dynamically

const level = 1; // 1 is last stack trace, you can go up the calling functions
console.log(new Error().stack.split("\n")[level].match(/http[^\)]+/)[0]);

Nothing that couldn't be figured out from the accepted answer, but maybe it can help newcomers.


问:
WordPress Notice "Undefined Index"
I am getting following notice in WordPress

Notice: Undefined index: _wpnonce in /var/www/vhosts/abc.biz/php/func.php on line 338

Any solution?
Thanks for help

答:
I found the solution, have to use isset() to check _wpnonce value, before comparing it.

```<code>if ( isset($_POST['_wpnonce']) && $_POST['_wpnonce'] = '123456789' ) {}
</code>```

Thanks.

Title: WordPress Notice "Undefined Index"

Body:
I found the solution, have to use isset() to check _wpnonce value, before comparing it.

if ( isset($_POST['_wpnonce']) && $_POST['_wpnonce'] = '123456789' ) {}

Thanks.


问:
Different layouts in portrait and landscape mode
Let's assume I have this layout design on an iPad Portrait.

But I would like to have it this way when the iPad is in landscape:

Is it possible to do that with auto layout?
Or with a small amount of code?

答:
The only way I have easily achieved this, so it works on iPads and iPhones is by doing it programmatically. This is done with Swift 5.0 in Xcode 10.2.

In your ViewController, define the two views you want to change depending on orientation:

```<code>@IBOutlet weak var raceInfoView: UIStackView!
@IBOutlet weak var raceListView: UITableView!
</code>```

Then define the constraints which will always stay the same in your storyboard and define the ones which will change in your ViewController.

```<code>private var portraitRaceInfoViewTrailing: NSLayoutConstraint!
private var portraitRaceInfoViewBottom: NSLayoutConstraint!
private var portraitRaceListViewLeading: NSLayoutConstraint!
private var landscapeRaceInfoViewTrailing: NSLayoutConstraint!
private var landscapeRaceInfoViewBottom: NSLayoutConstraint!
private var landscapeRaceListViewTop: NSLayoutConstraint!
</code>```

Next, initialise the constraints, I put it in viewDidLoad but it can probably be put somewhere else.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    portraitRaceInfoViewTrailing = NSLayoutConstraint(
        item: racesView as Any, attribute: NSLayoutConstraint.Attribute.trailing,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    portraitRaceInfoViewBottom = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    portraitRaceListViewLeading = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.leading,
        multiplier: 1, constant: 0)

    landscapeRaceInfoViewTrailing = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    landscapeRaceInfoViewBottom = NSLayoutConstraint(
        item: raceInfoView as Any, attribute: NSLayoutConstraint.Attribute.bottom,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    landscapeRaceListViewTop = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.top,
        multiplier: 1, constant: 0)

    applyOrientationConstraints()
}
</code>```

Declaring constraints programmatically looks a bit scary, but its actually quite easy. You can create the constraint in your storyboard and view all the values and copy the right ones to the right place in the code.

And finally in viewDidLoad apply the constraints with applyOrientationConstraints().

```<code>func applyOrientationConstraints() {
    let orient = UIApplication.shared.statusBarOrientation
    switch orient {
    case .portrait:
        NSLayoutConstraint.activate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.deactivate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    default:
        NSLayoutConstraint.deactivate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.activate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    }
}
</code>```

And lastly override viewWillTransition to apply the constraints when the orientation changes.

```<code>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        self.applyOrientationConstraints()
    }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        print("rotation completed")
    })
    super.viewWillTransition(to: size, with: coordinator)
}
</code>```

Body:
The only way I have easily achieved this, so it works on iPads and iPhones is by doing it programmatically. This is done with Swift 5.0 in Xcode 10.2.

In your ViewController, define the two views you want to change depending on orientation:

@IBOutlet weak var raceInfoView: UIStackView!
@IBOutlet weak var raceListView: UITableView!

Then define the constraints which will always stay the same in your storyboard and define the ones which will change in your ViewController.

private var portraitRaceInfoViewTrailing: NSLayoutConstraint!
private var portraitRaceInfoViewBottom: NSLayoutConstraint!
private var portraitRaceListViewLeading: NSLayoutConstraint!
private var landscapeRaceInfoViewTrailing: NSLayoutConstraint!
private var landscapeRaceInfoViewBottom: NSLayoutConstraint!
private var landscapeRaceListViewTop: NSLayoutConstraint!

Next, initialise the constraints, I put it in viewDidLoad but it can probably be put somewhere else.

override func viewDidLoad() {
    super.viewDidLoad()

    portraitRaceInfoViewTrailing = NSLayoutConstraint(
        item: racesView as Any, attribute: NSLayoutConstraint.Attribute.trailing,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    portraitRaceInfoViewBottom = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    portraitRaceListViewLeading = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.leading,
        multiplier: 1, constant: 0)

    landscapeRaceInfoViewTrailing = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    landscapeRaceInfoViewBottom = NSLayoutConstraint(
        item: raceInfoView as Any, attribute: NSLayoutConstraint.Attribute.bottom,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    landscapeRaceListViewTop = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.top,
        multiplier: 1, constant: 0)

    applyOrientationConstraints()
}

Declaring constraints programmatically looks a bit scary, but its actually quite easy. You can create the constraint in your storyboard and view all the values and copy the right ones to the right place in the code.

And finally in viewDidLoad apply the constraints with applyOrientationConstraints().

func applyOrientationConstraints() {
    let orient = UIApplication.shared.statusBarOrientation
    switch orient {
    case .portrait:
        NSLayoutConstraint.activate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.deactivate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    default:
        NSLayoutConstraint.deactivate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.activate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    }
}

And lastly override viewWillTransition to apply the constraints when the orientation changes.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        self.applyOrientationConstraints()
    }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        print("rotation completed")
    })
    super.viewWillTransition(to: size, with: coordinator)
}


问:
Developed simple winform app that uses gecko, won't run on another computer
I developed a simple windows form app that displays a webpage inside a Gecko webrowser. It works fine on my computer(win10, visual st.2017), I also tried it on another computer running win10 and it also runs fine, but when I tried running it on the client's computer it just won't launch, as if nothing happens, the cursor changes to a circle(thinking) and then nothing.

I installed .net 4.6 no change, disabled antivirus no change, installed firefox no change. Tried another winforms app that simply opens an empty window and it works fine, and another console application works fine, it's just this app that uses Gecko webbrowser that doesn't work.

I tried simply copying my bin\debug folder and running the app, and I also tried installing the app from the setup.exe after making a release version also won't run, it gives error that plugin-hang-ui.deploy.exe not found, I have plugin-hang-ui.exe in Firefox folder under bin\Release.

My code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using Gecko;

namespace ScreenPlayer1
{
public partial class Form1 : Form
{
    static string serial = "thefirst1";//This is unique per user.
    private const int SW_HIDE = 0;
    private const int SW_SHOW = 1;
    [DllImport("user32.dll")]
    private static extern int FindWindow(string className, string windowText);
    [DllImport("user32.dll")]
    private static extern int ShowWindow(int hwnd, int command);
    int hWnd = FindWindow("Shell_TrayWnd", "");
    string UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0";
    public Form1()
    {
        InitializeComponent();
        Xpcom.Initialize("Firefox");
        GeckoPreferences.User["full-screen-api.enabled"] = true;
        GeckoPreferences.Default["full-screen-api.enabled"] = true;
        GeckoPreferences.User["general.useragent.override"] = UserAgent;
        GeckoPreferences.Default["general.useragent.override"] = UserAgent;
        WindowState = FormWindowState.Maximized;
        TopMost = true;

    }

    /// <summary>
    /// //hash stuff
    /// </summary>
    static string ComputeSha256Hash(string rawData, string salt)
    {
        // Create a SHA256
        using (SHA256 sha256Hash = SHA256.Create())
        {
            string salted = "6++6" + rawData + salt;
            // ComputeHash - returns byte array
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(salted));

            // Convert byte array to a string
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
    /// <summary>
    /// end hash stuff
    /// </summary>
    ///

    private void Form1_Load(object sender, EventArgs e)
    {
        Random r = new Random(), s = new Random(), t = new Random();
        string salt = "s" + r.Next(1, 100) + s.Next(1, 100) + t.Next(1, 100);
        string get_serial = ComputeSha256Hash(serial, salt);
        string mode = "client";

        if (!File.Exists("mode.txt"))
        {
            string message = "Set as server?", caption = "Mode not set, choose yes for server no for client!";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;

            // Displays the MessageBox.

            result = MessageBox.Show(message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                mode = "server";
                System.IO.File.WriteAllText(@"mode.txt", mode);
            }
            else
            {
                mode = "client";
                System.IO.File.WriteAllText(@"mode.txt", mode);
            }
        }
        else
        {
            mode = System.IO.File.ReadAllText(@"mode.txt");
        }

        if (mode == "client")
        {
            int hh = ShowWindow(hWnd, SW_SHOW);
            FormBorderStyle = FormBorderStyle.None;
        }
        try
        {
            geckoWebBrowser2.Navigate("http://www.example.com/scr/prl.php?usr="
                               + get_serial + "&sts=" + salt + "&mode=" + mode);
            geckoWebBrowser2.Width = geckoWebBrowser2.Parent.Width;
            geckoWebBrowser2.Height = geckoWebBrowser2.Parent.Height;
        }
        catch (Exception sysEx)
        {
            System.Diagnostics.EventLog.WriteEntry("Bad web browsing!", sysEx.ToString());
        }
    }

    private void Form1_Closing(object sender, FormClosingEventArgs e)
    {
        int hwnd = ShowWindow(hWnd, SW_SHOW);
    }

    private void geckoWebBrowser2_Click(object sender, EventArgs e)
    {

    }
}
</code>```

}

Help would be appreciated, thanks.

答:
Installed Visual Studio 2019 with .NET and added GeckoFX from NuGet packages. After that my app worked like charm!

This is not the answer I expected, but since there was no other answer it should do.

Body:
I developed a simple windows form app that displays a webpage inside a Gecko webrowser. It works fine on my computer(win10, visual st.2017), I also tried it on another computer running win10 and it also runs fine, but when I tried running it on the client's computer it just won't launch, as if nothing happens, the cursor changes to a circle(thinking) and then nothing.

I installed .net 4.6 no change, disabled antivirus no change, installed firefox no change. Tried another winforms app that simply opens an empty window and it works fine, and another console application works fine, it's just this app that uses Gecko webbrowser that doesn't work.

I tried simply copying my bin\debug folder and running the app, and I also tried installing the app from the setup.exe after making a release version also won't run, it gives error that plugin-hang-ui.deploy.exe not found, I have plugin-hang-ui.exe in Firefox folder under bin\Release.

My code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using Gecko;

namespace ScreenPlayer1
{
public partial class Form1 : Form
{
    static string serial = "thefirst1";//This is unique per user.
    private const int SW_HIDE = 0;
    private const int SW_SHOW = 1;
    [DllImport("user32.dll")]
    private static extern int FindWindow(string className, string windowText);
    [DllImport("user32.dll")]
    private static extern int ShowWindow(int hwnd, int command);
    int hWnd = FindWindow("Shell_TrayWnd", "");
    string UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0";
    public Form1()
    {
        InitializeComponent();
        Xpcom.Initialize("Firefox");
        GeckoPreferences.User["full-screen-api.enabled"] = true;
        GeckoPreferences.Default["full-screen-api.enabled"] = true;
        GeckoPreferences.User["general.useragent.override"] = UserAgent;
        GeckoPreferences.Default["general.useragent.override"] = UserAgent;
        WindowState = FormWindowState.Maximized;
        TopMost = true;

    }

    ///
    /// //hash stuff
    ///
    static string ComputeSha256Hash(string rawData, string salt)
    {
        // Create a SHA256
        using (SHA256 sha256Hash = SHA256.Create())
        {
            string salted = "6++6" + rawData + salt;
            // ComputeHash - returns byte array
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(salted));

            // Convert byte array to a string
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
    ///
    /// end hash stuff
    ///
    ///

    private void Form1_Load(object sender, EventArgs e)
    {
        Random r = new Random(), s = new Random(), t = new Random();
        string salt = "s" + r.Next(1, 100) + s.Next(1, 100) + t.Next(1, 100);
        string get_serial = ComputeSha256Hash(serial, salt);
        string mode = "client";

        if (!File.Exists("mode.txt"))
        {
            string message = "Set as server?", caption = "Mode not set, choose yes for server no for client!";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;

            // Displays the MessageBox.

            result = MessageBox.Show(message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                mode = "server";
                System.IO.File.WriteAllText(@"mode.txt", mode);
            }
            else
            {
                mode = "client";
                System.IO.File.WriteAllText(@"mode.txt", mode);
            }
        }
        else
        {
            mode = System.IO.File.ReadAllText(@"mode.txt");
        }

        if (mode == "client")
        {
            int hh = ShowWindow(hWnd, SW_SHOW);
            FormBorderStyle = FormBorderStyle.None;
        }
        try
        {
            geckoWebBrowser2.Navigate("http://www.example.com/scr/prl.php?usr="
                               + get_serial + "&sts=" + salt + "&mode=" + mode);
            geckoWebBrowser2.Width = geckoWebBrowser2.Parent.Width;
            geckoWebBrowser2.Height = geckoWebBrowser2.Parent.Height;
        }
        catch (Exception sysEx)
        {
            System.Diagnostics.EventLog.WriteEntry("Bad web browsing!", sysEx.ToString());
        }
    }

    private void Form1_Closing(object sender, FormClosingEventArgs e)
    {
        int hwnd = ShowWindow(hWnd, SW_SHOW);
    }

    private void geckoWebBrowser2_Click(object sender, EventArgs e)
    {

    }
}

}

Help would be appreciated, thanks.


答:
Your matrix isn't big enough.

In the pseudo-code, s and t have lengths m and n respectively (char s[1..m], char t[1..n]). The matrix however has dimentions [0..m, 0..n] - i.e. one more than the length of the strings in each direction. You can see this in the tables below the pseudo-code.

So the matrix for "sitting" and "kitten" is 7x8, but your matrix is only 6x7.

You're also indexing into the strings incorrectly, because the strings in the pseudo-code are 1-indexed, but C#'s strings are 0-indexed.

After fixing these, you get this code, which works with "sitting" and "kitten":

```<code>public static class LevenshteinDistance
{
    public static int LevenshteinDistanceCalc(string source, string target)
    {
        int sourceSize = source.Length + 1, targetSize = target.Length + 1;
        int[,] distance = new int[sourceSize, targetSize];
        for (int sIndex = 0; sIndex < sourceSize; sIndex++)
        {
            distance[sIndex, 0] = sIndex;
        }
        for (int tIndex = 0; tIndex < targetSize; tIndex++)
        {
            distance[0, tIndex] = tIndex;
        }
        //      for j from 1 to n:
        //      for i from 1 to m:
        //          if s[i] = t[j]:
        //            substitutionCost:= 0
        //          else:
        //            substitutionCost:= 1
        //          d[i, j] := minimum(d[i - 1, j] + 1,                   // deletion
        //                             d[i, j - 1] + 1,                   // insertion
        //                             d[i - 1, j - 1] + substitutionCost)  // substitution
        //
        //
        //      return d[m, n]

        for (int tIndex = 1; tIndex < targetSize; tIndex++)
        {
            for (int sIndex = 1; sIndex < sourceSize; sIndex++)
            {
                int substitutionCost = source[sIndex - 1] == target[tIndex - 1] ? 0 : 1;
                int deletion = distance[sIndex - 1, tIndex] + 1;
                int insertion = distance[sIndex, tIndex - 1] + 1;
                int substitution = distance[sIndex - 1, tIndex - 1] + substitutionCost;

                distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);
            }
        }
        return distance[sourceSize - 1, targetSize - 1];
    }

    private static int leastOfThree(int a, int b, int c)
    {
        return Math.Min(a, (Math.Min(b, c)));
    }
}
</code>```

(I also took the liberty of making distance a local variable since there's no need for it to be a field (it only makes your class non-threadsafe), and also making it static to avoid the unnecessary instantiation).

To debug this, I put a breakpoint on return distance[sourceSize - 1, targetSize - 1] and compared distance to the table on Wikipedia. It was very obvious that it was too small.

Title: Why Am I Getting The Incorrect Levenshtein Distance?

Body:
Your matrix isn't big enough.

In the pseudo-code, s and t have lengths m and n respectively (char s[1..m], char t[1..n]). The matrix however has dimentions [0..m, 0..n] - i.e. one more than the length of the strings in each direction. You can see this in the tables below the pseudo-code.

So the matrix for "sitting" and "kitten" is 7x8, but your matrix is only 6x7.

You're also indexing into the strings incorrectly, because the strings in the pseudo-code are 1-indexed, but C#'s strings are 0-indexed.

After fixing these, you get this code, which works with "sitting" and "kitten":

public static class LevenshteinDistance
{
    public static int LevenshteinDistanceCalc(string source, string target)
    {
        int sourceSize = source.Length + 1, targetSize = target.Length + 1;
        int[,] distance = new int[sourceSize, targetSize];
        for (int sIndex = 0; sIndex < sourceSize; sIndex++)
        {
            distance[sIndex, 0] = sIndex;
        }
        for (int tIndex = 0; tIndex < targetSize; tIndex++)
        {
            distance[0, tIndex] = tIndex;
        }
        //      for j from 1 to n:
        //      for i from 1 to m:
        //          if s[i] = t[j]:
        //            substitutionCost:= 0
        //          else:
        //            substitutionCost:= 1
        //          d[i, j] := minimum(d[i - 1, j] + 1,                   // deletion
        //                             d[i, j - 1] + 1,                   // insertion
        //                             d[i - 1, j - 1] + substitutionCost)  // substitution
        //
        //
        //      return d[m, n]

        for (int tIndex = 1; tIndex < targetSize; tIndex++)
        {
            for (int sIndex = 1; sIndex < sourceSize; sIndex++)
            {
                int substitutionCost = source[sIndex - 1] == target[tIndex - 1] ? 0 : 1;
                int deletion = distance[sIndex - 1, tIndex] + 1;
                int insertion = distance[sIndex, tIndex - 1] + 1;
                int substitution = distance[sIndex - 1, tIndex - 1] + substitutionCost;

                distance[sIndex, tIndex] = leastOfThree(deletion, insertion, substitution);
            }
        }
        return distance[sourceSize - 1, targetSize - 1];
    }

    private static int leastOfThree(int a, int b, int c)
    {
        return Math.Min(a, (Math.Min(b, c)));
    }
}

(I also took the liberty of making distance a local variable since there's no need for it to be a field (it only makes your class non-threadsafe), and also making it static to avoid the unnecessary instantiation).

To debug this, I put a breakpoint on return distance[sourceSize - 1, targetSize - 1] and compared distance to the table on Wikipedia. It was very obvious that it was too small.


问:
PhpStorm: Replace string literal with class constant
I've been trying to find out how to replace a string of an FQCN with an import statement (and vice-versa). I can't work out if this feature doesn't exist or if I just can't find it.

For example, the ALT + ENTER context menu in PHPUnit when creating a mock:

PhpStorm knows which class this is - or is this a plugin doing this?

The opposite:

The PHP Annotations plugin adds a nice option in the context menu - but only for Doctrine:

Is there a keyboard shortcut to achieve the same result as above but with any class string literal?

答: Php Inspections (EA Extended) plugin has an inspection and quick fix for that: ::class can be used.


问:
Is there a way to format date to only show month and year in plsql?
I have trouble to output only month and year like this
December 2018 when I made a function to pass a parameter for the date.

I made a simple function with a parameter to return date only shows month and year with below test code. I used the month instead of mon as described from above, but there is a gap in between e.g. December     2019.

```<code>function get_month(p_month DATE DEFAULT sysdate)
return VARCHAR2
is

v_month varchar2(50);

begin

select to_char(trunc(p_month), 'Month yyyy') into v_month from dual;

return v_month;
commit;

end;
</code>```

Ideally, I would expect the output of the month in full name like to_char(sysdate,'Month DDth, YYYY') but without the day in the middle.

答:
the Month option in the format string seems to be generating the output with extra whitespaces, you can trim them to get the required result.

Try this:

```<code>select trim(to_char(sysdate,'Month'))||' '||to_char(sysdate,'yyyy')
from dual;
</code>```

Body:
I have trouble to output only month and year like this
December 2018 when I made a function to pass a parameter for the date.

I made a simple function with a parameter to return date only shows month and year with below test code. I used the month instead of mon as described from above, but there is a gap in between e.g. December     2019.

function get_month(p_month DATE DEFAULT sysdate)
return VARCHAR2
is

v_month varchar2(50);

begin

select to_char(trunc(p_month), 'Month yyyy') into v_month from dual;

return v_month;
commit;

end;

Ideally, I would expect the output of the month in full name like to_char(sysdate,'Month DDth, YYYY') but without the day in the middle.

Body:
the Month option in the format string seems to be generating the output with extra whitespaces, you can trim them to get the required result.

Try this:

select trim(to_char(sysdate,'Month'))||' '||to_char(sysdate,'yyyy')
from dual;


问:
Getting day of the week from timestamp using JavaScript
How do I get the day of the week from a timestamp in JavaScript?
I'd like to get this from a timestamp I specify, not the current date.

Thanks

答:
Try out the following:</p>

```<code>var currentTime = new Date();
var day = currentTime.getDate();
</code>```

Body:
Try out the following:

var currentTime = new Date();
var day = currentTime.getDate();


问:
Fastest way to perform complex search on pandas dataframe
I am trying to figure out the fastest way to perform search and sort on a pandas dataframe. Below are before and after dataframes of what I am trying to accomplish.

Before:

```<code>flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       DEF       123     456     8000    8000
   DEF       XYZ       456     893     9999    9999
   AAA       BBB       473     917     5555    5555
   BBB       CCC       917     341     5555    5555
</code>```

After search/sort:

```<code>flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       XYZ       123     893     8000    9999
   AAA       CCC       473     341     5555    5555
</code>```

In this example I am essentially trying to filter out 'flights' that exist in between end destinations. This should be done by using some sort of drop duplicates method but what leaves me confused is how to handle all of the columns. Would a binary search be the best way to accomplish this? Hints appreciated, trying hard to figure this out.

possible edge case:

What if the data is switched up and our end connections are in the same column?

```<code>flight1  flight2      1Num    2Num     1Code   2Code
   ABC       DEF       123     456     8000    8000
   XYZ       DEF       893     456     9999    9999
</code>```

After search/sort:

```<code>flight1  flight2      1Num    2Num     1Code   2Code
   ABC       XYZ       123     893     8000    9999
</code>```

This case logically shouldn't happen. After all how can you go DEF-ABC and DEF-XYZ? You can't, but the 'endpoints' would still be ABC-XYZ

答:
Here's a NumPy solution, which might be convenient in the case performance is relevant:

```<code>def remove_middle_dest(df):
    x = df.to_numpy()
    # obtain a flat numpy array from both columns
    b = x[:,0:2].ravel()
    _, ix, inv = np.unique(b, return_index=True, return_inverse=True)
    # Index of duplicate values in b
    ixs_drop = np.setdiff1d(np.arange(len(b)), ix)
    # Indices to be used to replace the content in the columns
    replace_at = (inv[:,None] == inv[ixs_drop]).argmax(0)
    # Col index of where duplicate value is, 0 or 1
    col = (ixs_drop % 2) ^ 1
    # 2d array to index and replace values in the df
    # index to obtain values with which to replace
    keep_cols = np.broadcast_to([3,5],(len(col),2))
    ixs = np.concatenate([col[:,None], keep_cols], 1)
    # translate indices to row indices
    rows_drop, rows_replace = (ixs_drop // 2), (replace_at // 2)
    c = np.empty((len(col), 5), dtype=x.dtype)
    c[:,::2] = x[rows_drop[:,None], ixs]
    c[:,1::2] = x[rows_replace[:,None], [2,4]]
    # update dataframe and drop rows
    df.iloc[rows_replace, 1:] = c
    return df.drop(rows_drop)
</code>```

Which fo the proposed dataframe yields the expected output:

```<code>print(df)
    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        DEF    123      456    8000      8000
1      DEF        XYZ    456      893    9999      9999
2      AAA        BBB    473      917    5555      5555
3      BBB        CCC    917      341    5555      5555

remove_middle_dest(df)

    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        XYZ    123      893    8000      9999
2      AAA        CCC    473      341    5555      5555
</code>```

This approach does not assume any particular order in terms of the rows where the duplicate is, and the same applies to the columns (to cover the edge case described in the question). If we use for instance the following dataframe:

```<code>    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        DEF    123      456    8000      8000
1      XYZ        DEF    893      456    9999      9999
2      AAA        BBB    473      917    5555      5555
3      BBB        CCC    917      341    5555      5555

remove_middle_dest(df)

     flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        XYZ    123      456    8000      9999
2      AAA        CCC    473      341    5555      5555
</code>```

Body:
I am trying to figure out the fastest way to perform search and sort on a pandas dataframe. Below are before and after dataframes of what I am trying to accomplish.

Before:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       DEF       123     456     8000    8000
   DEF       XYZ       456     893     9999    9999
   AAA       BBB       473     917     5555    5555
   BBB       CCC       917     341     5555    5555

After search/sort:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       XYZ       123     893     8000    9999
   AAA       CCC       473     341     5555    5555

In this example I am essentially trying to filter out 'flights' that exist in between end destinations. This should be done by using some sort of drop duplicates method but what leaves me confused is how to handle all of the columns. Would a binary search be the best way to accomplish this? Hints appreciated, trying hard to figure this out.

possible edge case:

What if the data is switched up and our end connections are in the same column?

flight1  flight2      1Num    2Num     1Code   2Code
   ABC       DEF       123     456     8000    8000
   XYZ       DEF       893     456     9999    9999

After search/sort:

flight1  flight2      1Num    2Num     1Code   2Code
   ABC       XYZ       123     893     8000    9999

This case logically shouldn't happen. After all how can you go DEF-ABC and DEF-XYZ? You can't, but the 'endpoints' would still be ABC-XYZ

Body:
Here's a NumPy solution, which might be convenient in the case performance is relevant:

def remove_middle_dest(df):
    x = df.to_numpy()
    # obtain a flat numpy array from both columns
    b = x[:,0:2].ravel()
    _, ix, inv = np.unique(b, return_index=True, return_inverse=True)
    # Index of duplicate values in b
    ixs_drop = np.setdiff1d(np.arange(len(b)), ix)
    # Indices to be used to replace the content in the columns
    replace_at = (inv[:,None] == inv[ixs_drop]).argmax(0)
    # Col index of where duplicate value is, 0 or 1
    col = (ixs_drop % 2) ^ 1
    # 2d array to index and replace values in the df
    # index to obtain values with which to replace
    keep_cols = np.broadcast_to([3,5],(len(col),2))
    ixs = np.concatenate([col[:,None], keep_cols], 1)
    # translate indices to row indices
    rows_drop, rows_replace = (ixs_drop // 2), (replace_at // 2)
    c = np.empty((len(col), 5), dtype=x.dtype)
    c[:,::2] = x[rows_drop[:,None], ixs]
    c[:,1::2] = x[rows_replace[:,None], [2,4]]
    # update dataframe and drop rows
    df.iloc[rows_replace, 1:] = c
    return df.drop(rows_drop)

Which fo the proposed dataframe yields the expected output:

print(df)
    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        DEF    123      456    8000      8000
1      DEF        XYZ    456      893    9999      9999
2      AAA        BBB    473      917    5555      5555
3      BBB        CCC    917      341    5555      5555

remove_middle_dest(df)

    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        XYZ    123      893    8000      9999
2      AAA        CCC    473      341    5555      5555

This approach does not assume any particular order in terms of the rows where the duplicate is, and the same applies to the columns (to cover the edge case described in the question). If we use for instance the following dataframe:

    flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        DEF    123      456    8000      8000
1      XYZ        DEF    893      456    9999      9999
2      AAA        BBB    473      917    5555      5555
3      BBB        CCC    917      341    5555      5555

remove_middle_dest(df)

     flightTo flightFrom  toNum  fromNum  toCode  fromCode
0      ABC        XYZ    123      456    8000      9999
2      AAA        CCC    473      341    5555      5555


问:
How to compare two arabic string in oracle?
I have two strings:

```<code>a = 'على';
b = 'علي';
</code>```

or

```<code>a = 'محمد';
b ='محــــــــــمد';
</code>```

or

```<code>a= 'بُنْ'
b='بن'

</code>```

```<code>a= 'يسرا'
b='يسرى'

</code>```

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

答:
```<code>SELECT * FROM DUAL
WHERE a = b;
</code>```

A row will be returned if they are equal, no rows if not equal.

Body:
I have two strings:

a = 'على';
b = 'علي';

or

a = 'محمد';
b ='محــــــــــمد';

or

a= 'بُنْ'
b='بن'

a= 'يسرا'
b='يسرى'

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

Body:
SELECT * FROM DUAL
WHERE a = b;

A row will be returned if they are equal, no rows if not equal.