问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答:
In response to 5, one common use is something like this (in C):

```<code>for (size_t pos = 0, end = strlen(something); pos < end; ++pos) {
    if isspace((unsigned)(something[pos])) {
        puts("contains whitespace");
        break;
    }
}
</code>```

instead of:

```<code>for (size_t pos = 0; pos < strlen(something); ++pos) { ... }
</code>```

strlen could be any operation that's expensive relative to the loop, such that it makes sense to hoist it. For strlen in particular maybe the optimizer could do it automatically, but in general if the compiler doesn't know what the call does, and you put it in the loop condition, it has to evaluate it every time around because it doesn't know whether it will change.

Of course, you could instead write this:

```<code>const size_t end = strlen(something);
for (size_t pos = 0; pos < end; ++pos) { ... }
</code>```

So there's certainly no strict need for the extra variable to be defined in the for statement, and arguably there's a tiny advantage to making end const (or final) anyway, which you lose by defining pos and end together. Some people prefer the "loop variables" (in this case including a "loop constant") to all be defined in the for statement, though, since they "belong" to it.

Plus, before someone points it out, in my C example you don't need indexing at all:

```<code>for (const char *ptr = something; *ptr; ++ptr) {
    if isspace((unsigned)*ptr) { ... }
}
</code>```

but we can pretend we have a task where we are going to iterate using a calculated end point...

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

Body:
In response to 5, one common use is something like this (in C):

for (size_t pos = 0, end = strlen(something); pos < end; ++pos) {
    if isspace((unsigned)(something[pos])) {
        puts("contains whitespace");
        break;
    }
}

instead of:

for (size_t pos = 0; pos < strlen(something); ++pos) { ... }

strlen could be any operation that's expensive relative to the loop, such that it makes sense to hoist it. For strlen in particular maybe the optimizer could do it automatically, but in general if the compiler doesn't know what the call does, and you put it in the loop condition, it has to evaluate it every time around because it doesn't know whether it will change.

Of course, you could instead write this:

const size_t end = strlen(something);
for (size_t pos = 0; pos < end; ++pos) { ... }

So there's certainly no strict need for the extra variable to be defined in the for statement, and arguably there's a tiny advantage to making end const (or final) anyway, which you lose by defining pos and end together. Some people prefer the "loop variables" (in this case including a "loop constant") to all be defined in the for statement, though, since they "belong" to it.

Plus, before someone points it out, in my C example you don't need indexing at all:

for (const char *ptr = something; *ptr; ++ptr) {
    if isspace((unsigned)*ptr) { ... }
}

but we can pretend we have a task where we are going to iterate using a calculated end point...


来源: stackexchange

问:
SwiftUI change navigation title color for current view only
I know I can globally change the navigation bar using init:

```<code>init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.red
    ]
}
</code>```

How would I do this for the current view only? I only want to set the navigation title color for the current view, not all views of the app.

答:
Not sure do you have this issue now.

I have searched for this issue and find a great article about this, you could wrap the settings of navigation bar style as a view modifier.

Check this Link.

```<code>struct NavigationBarModifier: ViewModifier {

    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {

    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }

}
</code>```

After that, apply like this:

```<code>.navigationBarColor(backgroundColor: .clear, titleColor: .white)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know I can globally change the navigation bar using init:

init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.red
    ]
}

How would I do this for the current view only? I only want to set the navigation title color for the current view, not all views of the app.

Body:
Not sure do you have this issue now.

I have searched for this issue and find a great article about this, you could wrap the settings of navigation bar style as a view modifier.

Check this Link.

struct NavigationBarModifier: ViewModifier {

    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {

    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }

}

After that, apply like this:

.navigationBarColor(backgroundColor: .clear, titleColor: .white)


问:
JPA/Hibernate - Embedding an Attribute
I am having a trouble mapping an embedded attribute of a class.  I have created some classes that are similar to what I am trying to do to illustrate.  Basically, I have an @Embeddable class hierarchy that uses Inheritance.  The top level class "Part Number" has only one attribute, and the extending classes add no attributes to the "Part Number" class, they only add some validation/logic.

Here is what I mean:

PART

```<code>@Entity
@Table(name="PART")
public class Part {
    private Integer id;
    private String name;
    private PartNumber partNumber;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="PART_NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Embedded
    public PartNumber getPartNumber() {
        return partNumber;
    }
    public void setPartNumber(PartNumber partNumber) {
        this.partNumber = partNumber;
    }

}
</code>```

PARTNUMBER

```<code>@Embeddable
public abstract class PartNumber {

    protected String partNumber;
    private String generalPartNumber;
    private String specificPartNumber;

    private PartNumber() {

    }

    public PartNumber(String partNumber) {
        this.partNumber = partNumber;

    }

    @Column(name = "PART_NUMBER")
    public String getPartNumber() {
        return partNumber;
    }

    public void setPartNumber(String partNumber) {
        this.partNumber = partNumber;
    }

    /**
     * @param partNumber
     * @return
     */
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /**
     * Returns the first half of the Part Number
     *
     * @return generalPartNumber
     */
    @Transient
    public String getGeneralPartNumber() {
        return generalPartNumber;

    }

    /**
     * Returns the last half of the Part Number
     * which is specific to each Car Brand
     *
     * @return specificPartNumber
     */
    @Transient
    public String getSpecificPartNumber() {
        return specificPartNumber;

    }

}
</code>```

FORD PARTNUMBER

```<code>public class FordPartNumber extends PartNumber {

    /**
     * Ford Part Number is formatted as 1234-#1234
     *
     * @param partNumber
     */
    public FordPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }

}
</code>```

CHEVY PARTNUMBER

```<code>public class ChevyPartNumber extends PartNumber {

    /**
     * Chevy Part Number is formatted as 1234-$1234
     *
     * @param partNumber
     */
    public ChevyPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }
}
</code>```

Of course this does not work, because Hibernate ignores the Inheritance Hierarchy and doesn't like the fact that PartNumber is abstract.  Is there some way to do this using JPA or Hibernate Annotations?  I have tried using the @Inheritance JPA annotation.

I am not able to refactor the "PartNumber" part of the hierarchy because the original Developer wants to be able to extend PartNumber with N many XXXXPartNumber classes.

Does anyone know if anything like this will be a part of the JPA 2.0 or a new version of Hibernate?

答:
EclipseLink supports Inheritance in Embeddables via @Customizer
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Embeddable#Inheritance</p>

ContentLicense: CC BY-SA 2.5

Title: JPA/Hibernate - Embedding an Attribute

Body:
I am having a trouble mapping an embedded attribute of a class.  I have created some classes that are similar to what I am trying to do to illustrate.  Basically, I have an @Embeddable class hierarchy that uses Inheritance.  The top level class "Part Number" has only one attribute, and the extending classes add no attributes to the "Part Number" class, they only add some validation/logic.

Here is what I mean:

PART

@Entity
@Table(name="PART")
public class Part {
    private Integer id;
    private String name;
    private PartNumber partNumber;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="PART_NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Embedded
    public PartNumber getPartNumber() {
        return partNumber;
    }
    public void setPartNumber(PartNumber partNumber) {
        this.partNumber = partNumber;
    }

}

PARTNUMBER

@Embeddable
public abstract class PartNumber {

    protected String partNumber;
    private String generalPartNumber;
    private String specificPartNumber;

    private PartNumber() {

    }

    public PartNumber(String partNumber) {
        this.partNumber = partNumber;

    }

    @Column(name = "PART_NUMBER")
    public String getPartNumber() {
        return partNumber;
    }

    public void setPartNumber(String partNumber) {
        this.partNumber = partNumber;
    }

    /**
     * @param partNumber
     * @return
     */
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /**
     * Returns the first half of the Part Number
     *
     * @return generalPartNumber
     */
    @Transient
    public String getGeneralPartNumber() {
        return generalPartNumber;

    }

    /**
     * Returns the last half of the Part Number
     * which is specific to each Car Brand
     *
     * @return specificPartNumber
     */
    @Transient
    public String getSpecificPartNumber() {
        return specificPartNumber;

    }

}

FORD PARTNUMBER

public class FordPartNumber extends PartNumber {

    /**
     * Ford Part Number is formatted as 1234-#1234
     *
     * @param partNumber
     */
    public FordPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }

}

CHEVY PARTNUMBER

public class ChevyPartNumber extends PartNumber {

    /**
     * Chevy Part Number is formatted as 1234-$1234
     *
     * @param partNumber
     */
    public ChevyPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }
}

Of course this does not work, because Hibernate ignores the Inheritance Hierarchy and doesn't like the fact that PartNumber is abstract.  Is there some way to do this using JPA or Hibernate Annotations?  I have tried using the @Inheritance JPA annotation.

I am not able to refactor the "PartNumber" part of the hierarchy because the original Developer wants to be able to extend PartNumber with N many XXXXPartNumber classes.

Does anyone know if anything like this will be a part of the JPA 2.0 or a new version of Hibernate?


问:
How to convert string number into numeric number with given string, Java
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

```<code>public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}
</code>```

答:
This suggestion matches your approach with matching regex using Matcher and Pattern

Apply a regex to extract the digits, then replace each one with the matching index from the array using replace() method.

Online demo
 http://tpcg.io/qYIn6e6h

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    static String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    public static void main(String[] args) {

        String regex = "(\\d+)";
        String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(testString);

        while ( matcher.find() ) {
            testString = testString.replaceFirst(matcher.group(1), getDigitsText(matcher.group(1)) );
        }
        System.out.println( testString);
    }

 /**
 * Gets the text representation of the given number.
 * Example:  Input: 39 outputs: THREENINE
 */
    public static String getDigitsText( String digitText ){
        //split digits if more than one digit. split("") works since Java 8
        String[] digitStrings = digitText.split("");
        //get digit for string
        String text = "";
        for (String digitString : digitStrings){
            //parase string to int
            int digit = Integer.parseInt(digitString);
            //get matching text from
            text += singleDigits[digit];
        }

        return text;
    }
}
</code>```

Output:

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.

Approach

Used Matcher and Pattern to extract digits from String using regex (\d+)

Regex returns every number portion inside that String, it could be multiple digits.

This method getDigitsText() will take that String, split it into an array of Strings, each element represents one character that must be a digit.

Then iterate the array, getting the name of number from the singleDigits[] array

The method concats the name and returns the text representation of the given number.

The matcher loop inside main will simply replace the digits String with names String built in the method.

Result is printed after loop finishes.

Body:
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}

Body:
This suggestion matches your approach with matching regex using Matcher and Pattern

Apply a regex to extract the digits, then replace each one with the matching index from the array using replace() method.

Online demo
 http://tpcg.io/qYIn6e6h

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    static String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    public static void main(String[] args) {

        String regex = "(\\d+)";
        String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(testString);

        while ( matcher.find() ) {
            testString = testString.replaceFirst(matcher.group(1), getDigitsText(matcher.group(1)) );
        }
        System.out.println( testString);
    }

 /**
 * Gets the text representation of the given number.
 * Example:  Input: 39 outputs: THREENINE
 */
    public static String getDigitsText( String digitText ){
        //split digits if more than one digit. split("") works since Java 8
        String[] digitStrings = digitText.split("");
        //get digit for string
        String text = "";
        for (String digitString : digitStrings){
            //parase string to int
            int digit = Integer.parseInt(digitString);
            //get matching text from
            text += singleDigits[digit];
        }

        return text;
    }
}

Output:

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.

Approach

Used Matcher and Pattern to extract digits from String using regex (\d+)

Regex returns every number portion inside that String, it could be multiple digits.

This method getDigitsText() will take that String, split it into an array of Strings, each element represents one character that must be a digit.

Then iterate the array, getting the name of number from the singleDigits[] array

The method concats the name and returns the text representation of the given number.

The matcher loop inside main will simply replace the digits String with names String built in the method.

Result is printed after loop finishes.


问:
How to check if a list of dates contains today's date in Lua?
I want to write a code that automatically checks if today's date matches one of the dates in a given table. I'm not very familiar with Lua(still learning) but I do know how to use the time function howevers the platform I'm working on only support Lua 5.0 so it does not support the yday(%j) function which makes it more complicated.</p>

答:
You can try formatting your date using this code:

```<code>-- CURRENT DATE
local myyear = os.date("*t").year
local mymonth = os.date("*t").month; if mymonth < 10 then mymonth = "0"..mymonth end
local myday = os.date("*t").day; if myday < 10 then myday = "0"..myday end
local today = myyear..mymonth..myday
print(today)
</code>```

And then check if the date is in your table.
Hope this is not too complicated and can be of help?

PS: I am using gideros engine which uses lua.

Body:
You can try formatting your date using this code:

-- CURRENT DATE
local myyear = os.date("*t").year
local mymonth = os.date("*t").month; if mymonth < 10 then mymonth = "0"..mymonth end
local myday = os.date("*t").day; if myday < 10 then myday = "0"..myday end
local today = myyear..mymonth..myday
print(today)

And then check if the date is in your table.
Hope this is not too complicated and can be of help?

PS: I am using gideros engine which uses lua.


问:
Weird sql error, calling a something a column that isn't a column
I have an sql statement that looks like this:
SELECT name FROM companies WHERE name = government;

But then the error says this: Unknown column 'government' in 'where clause',

But anyway, why is this happening? I've been stuck on it for 30 minutes and simply putting SELECT name FROM companies will work (no error).

答:
You want to compare a column against a literal string - for this, you need to surround the string with single quotes, otherwise the database takes it as a column name. So:</p>

```<code>SELECT name FROM companies WHERE name = 'government';
</code>```

Body:
You want to compare a column against a literal string - for this, you need to surround the string with single quotes, otherwise the database takes it as a column name. So:

SELECT name FROM companies WHERE name = 'government';


问:
Post method to receive response in php
I have to write a php file that was supposed to receive data from a site form with post method . To test it i wrote these two files :

```<code><?php

    $url = 'temp.php';
    $data = array('username' => 'jsafsd@gmail.com', 'password' => 'lassrd');
    $query=http_build_query($data);
    $options = array(
        'header' => "Connection: close\r\n".
                            "Content-Length: ".strlen($query)."\r\n",
        'method'  => 'POST',
        'content' => $query,
    );

    $context  = stream_context_create(array ( 'http' => $options ));
    $result = file_get_contents($url,false,$context);
    var_dump($result);

?>
</code>```

temp.php

```<code><?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else
    echo "bye";
    exit();
?>
</code>```

But when i run the first file, all i get is  string

```<code><?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else
    echo "bye";
    exit();
?>
</code>```

(length=95)

What is the problem with this ?

答: You'll need a compiler such as WampServer to render the PHP file.; web browsers usually only render it as a string.</p>

ContentLicense: CC BY-SA 3.0

Title: Post method to receive response in php

Body:
I have to write a php file that was supposed to receive data from a site form with post method . To test it i wrote these two files :

<?php

    $url = 'temp.php';
    $data = array('username' => 'jsafsd@gmail.com', 'password' => 'lassrd');
    $query=http_build_query($data);
    $options = array(
        'header' => "Connection: close\r\n".
                            "Content-Length: ".strlen($query)."\r\n",
        'method'  => 'POST',
        'content' => $query,
    );

    $context  = stream_context_create(array ( 'http' => $options ));
    $result = file_get_contents($url,false,$context);
    var_dump($result);

?>

temp.php

<?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else
    echo "bye";
    exit();
?>

But when i run the first file, all i get is  string

<?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else
    echo "bye";
    exit();
?>

(length=95)

What is the problem with this ?


答:
You need to put quotes ' around government

```<code>SELECT
    name
FROM companies
WHERE name = 'government';
</code>```

Title: Weird sql error, calling a something a column that isn't a column

Body:
I have an sql statement that looks like this:
SELECT name FROM companies WHERE name = government;

But then the error says this: Unknown column 'government' in 'where clause',

But anyway, why is this happening? I've been stuck on it for 30 minutes and simply putting SELECT name FROM companies will work (no error).

Body:
You need to put quotes ' around government

SELECT
    name
FROM companies
WHERE name = 'government';


问:
How to close jQuery accordion before opening next one?
After opening an accordion item and then clicking on a new accordion item, I want it to first close the open one and then open the new one.

Here's my current code:

```<code>jQuery('.acclink').click(function () {
    jQuery("#accordion").accordion("activate", -1); // this closes anything open
    jQuery(jQuery(this).attr('href')).click(); // this is supposed to open the new one but doesn't. It WILL work when the above function is commented out.
    return false;
});
</code>```

Here's my page: http://www.savedeth.com/objectivescenes/
What am I missing?

答:
Try this </p>

```<code>$(document).ready(function() { ("#accordion").accordion;});
</code>```

Body:
After opening an accordion item and then clicking on a new accordion item, I want it to first close the open one and then open the new one.

Here's my current code:

jQuery('.acclink').click(function () {
    jQuery("#accordion").accordion("activate", -1); // this closes anything open
    jQuery(jQuery(this).attr('href')).click(); // this is supposed to open the new one but doesn't. It WILL work when the above function is commented out.
    return false;
});

Here's my page: http://www.savedeth.com/objectivescenes/
What am I missing?

Body:
Try this

$(document).ready(function() { ("#accordion").accordion;});


问:
Javascript/Typescript - Remove elements of an array that exists in another array
I have two arrays:

```<code>const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];
</code>```

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

答:
There is a method call Array.filter():

```<code>    arr2 = arr2.filter( function( el ) {
                  return arr1.indexOf( el ) < 0;
                  });
</code>```

Sample way:

```<code>    arr2= arr2.filter( function( el ) {
      return !arr1.includes( el );
    } );
</code>```

Using arrow functions:

```<code>    arr2= arr2.filter( ( el ) => !arr1.includes( el ) );
</code>```

Body:
I have two arrays:

const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

Body:
There is a method call Array.filter():

    arr2 = arr2.filter( function( el ) {
                  return arr1.indexOf( el ) < 0;
                  });

Sample way:

    arr2= arr2.filter( function( el ) {
      return !arr1.includes( el );
    } );

Using arrow functions:

    arr2= arr2.filter( ( el ) => !arr1.includes( el ) );


问:
I can't loop through a directory which has images
I have tried to loop through a directory which has images inside. There are 45 images inside that directory but when I executed the file the program gave me only one image and then it stopped the loop immediately. I don't know what I did wrong with it and also I have tried both for loops, one within the comment and another one is outside the command.

my code

```<code>import cv2
import argparse
import os
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to not hong dataset")
ap.add_argument("-o", "--output", required=True, help="path to output directory")
args = vars(ap.parse_args())

haar_cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(haar_cascade)

print("\n[INFO] Working on image...")

"""
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    i = 0
    image = cv2.imread(imagePath)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
"""

for imagePath in os.listdir(args["dataset"]):
    i = 0
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
</code>```

答:
You keep setting i = 0 in your loop and thus keep overwriting the output file. instead do

```<code>for i, imagePath in enumerate(os.listdir(args["dataset"])):
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
</code>```

A general way to debug this kind of thing is to put a few prints in the code. For instance print("input", imagePath) at the top and print("output", p) near the bottom would have shown the problem.

Body:
I have tried to loop through a directory which has images inside. There are 45 images inside that directory but when I executed the file the program gave me only one image and then it stopped the loop immediately. I don't know what I did wrong with it and also I have tried both for loops, one within the comment and another one is outside the command.

my code

import cv2
import argparse
import os
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to not hong dataset")
ap.add_argument("-o", "--output", required=True, help="path to output directory")
args = vars(ap.parse_args())

haar_cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(haar_cascade)

print("\n[INFO] Working on image...")

"""
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    i = 0
    image = cv2.imread(imagePath)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
"""

for imagePath in os.listdir(args["dataset"]):
    i = 0
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1

Body:
You keep setting i = 0 in your loop and thus keep overwriting the output file. instead do

for i, imagePath in enumerate(os.listdir(args["dataset"])):
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)

A general way to debug this kind of thing is to put a few prints in the code. For instance print("input", imagePath) at the top and print("output", p) near the bottom would have shown the problem.


问:
how to pass json object to a java rest webservice using jax rs
I need help with the method signature on the updateGroup method.
Here is the json im passing - its an array of actions.

```<code>    [{"action":"add","key":"104"}]
</code>```

this is the method its being passed to

```<code>@PUT
@Path("/group/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public IRestResponse updateGroup(@PathParam("id") String GroupName,
                                 Object GroupActions){
    //Do Something...
}
</code>```

What type should GroupActions be above to recieve the json. ? HashMap, ArrayList, some combination?

答: Have you tried to use String type and than parse it?</p>

Body:
I need help with the method signature on the updateGroup method.
Here is the json im passing - its an array of actions.

    [{"action":"add","key":"104"}]

this is the method its being passed to

@PUT
@Path("/group/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public IRestResponse updateGroup(@PathParam("id") String GroupName,
                                 Object GroupActions){
    //Do Something...
}

What type should GroupActions be above to recieve the json. ? HashMap, ArrayList, some combination?


问:
Type 'string[]' is not assignable to type 'never[]'
In typescript, I got error of
Type 'string[]' is not assignable to type 'never[]'.

I want to add 'abc' into the array, what's wrong with it?

```<code>export default function App() {
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState([]);

  const xx = () => setArr([...arr, text]);

  return <div className="App">{text}</div>;
}
</code>```

https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272

答:
useState is a generic function so use it to define the type of array.

like: const [arr, setArr] = React.useState<string[]>([]);

Body:
In typescript, I got error of
Type 'string[]' is not assignable to type 'never[]'.

I want to add 'abc' into the array, what's wrong with it?

export default function App() {
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState([]);

  const xx = () => setArr([...arr, text]);

  return
{text}
;
}

https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272


问:
How can data structures like Arrays in Java be of any type if they are objects themselves?
I might be getting a bit confused with OOP, just got into it, but if an array in java is an object, where it is calling the Array constructor from the Array class in java to make an instance of it, how is it possible for an Array in Java to be of primitive data type or any object type? Should not the type of the Array be Array type if that is what it is a class of? If I made a class called Car and then made an object called redCar of it, the type of the object is Car still. This does not just apply to Arrays but other data structures as well. Any easy explanations are welcome.</p>

答: An array in Java is a special type, just like String is.  It is not a primitive type, but you can instantiate it in a special way.  If you make an array of Cars, the type is Car[].  An array is what is called a "reference type" in Java.  This means that it does not store anything of its own in memory, it just references other variables in memory.  In the end, any array extends Object, just like any other object in Java.  Note that in Java, there is also a class called Array.  Arrays in Java are NOT instances of Array.  Array is simply a utility class which provides useful static methods for manipulating and accessing arrays.


答: Hmm... I would have used a loop to solve this issue. Keep in mind that the filter method will actually return a new array and not make any changes to the array you are actually targeting. You're probably going to have to loop through arr2 and check each element to see if it is too in arr1 using a conditional or the includes method. If an element in arr2 in fact has a copy in arr1 then use the splice method to get rid of that element. Remember to keep track of what index you are testing so that you can pass it to the splice methods. Note: using the includes method would allow you to not use a loop in a loop. However, off the top of my head im not sure if this strategy will get you better than O^2. Hope this helps. </p>

Title: Javascript/Typescript - Remove elements of an array that exists in another array


问:
How do I get my Django context variables into my JS file?
I'm trying to get data from a Django Backend to display on a map with Google Maps API, but I can't figure out how to pass the variables into the Javascript. Can someone please help me figure out what I'm doing wrong?

Django Method:

```<code>def home(request):
    //stuff that processes the method
    return render(request, 'map/index.html', {'lats': lats, "longs": longs, 'lat': lat, 'long': long, 'names': names, 'scores': scores})
</code>```

HTML Snippet:

```<code> <script> src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = ../../static/navbar.js></script>
    <!-- input tag-->

    <form method="post">
        {% csrf_token %}
        <input id="address" type="text" name="address">
        <input type="submit" style="display: none" />

    </form>

    <script>
        var names = {{ names }};
        var lats = {{ lats }};
        var longs = {{ longs }};
        var scores = {{ scores }};
        var lat = {{ lat }};
        var long = {{ long }};
    </script>

    <!-- this implements the map-->
    <div id="map"></div>
    <script src = ../../static/index.js> </script>
</code>```

Javascript Snippet(index.js):

```<code>let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [names[count], lats[count], longs[count], scores[count]];
}
let curlat = lat, curlong = long;
</code>```

答:
Simply save the variable to window in your template:

```<code><script>
    window.names = {{ names }};
    window.lats = {{ lats }};
    window.longs = {{ longs }};
    window.scores = {{ scores }};
    window.lat = {{ lat }};
    window.long = {{ long }};
</script>
</code>```

Now in your js file:

```<code>let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [window.names[count], window.lats[count], window.longs[count], window.scores[count]];
}
let curlat = lat, curlong = long;
</code>```

Body:
I'm trying to get data from a Django Backend to display on a map with Google Maps API, but I can't figure out how to pass the variables into the Javascript. Can someone please help me figure out what I'm doing wrong?

Django Method:

def home(request):
    //stuff that processes the method
    return render(request, 'map/index.html', {'lats': lats, "longs": longs, 'lat': lat, 'long': long, 'names': names, 'scores': scores})

HTML Snippet:

    <form method="post">
        {% csrf_token %}
        <input id="address" type="text" name="address">
        <input type="submit" style="display: none" />

    </form>

Javascript Snippet(index.js):

let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [names[count], lats[count], longs[count], scores[count]];
}
let curlat = lat, curlong = long;

Body:
Simply save the variable to window in your template:

<script>
    window.names = {{ names }};
    window.lats = {{ lats }};
    window.longs = {{ longs }};
    window.scores = {{ scores }};
    window.lat = {{ lat }};
    window.long = {{ long }};
</script>

Now in your js file:

let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [window.names[count], window.lats[count], window.longs[count], window.scores[count]];
}
let curlat = lat, curlong = long;


问:
Creating a palindrome checker with Python's loop and if statements
I am trying to follow the instructions to create a palindrome. I am given half a function, and I have to fill in the blanks. I am currently unable to get the loop to work correctly. I am also unsure how to add characters to the beginning or the end of string without using the + or a comma. I do not think that is what I am being asked to do.
Here are the instructions;

The is_palindrome function checks if a string is a palindrome... Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

```<code>def is_palindrome(input_string):
    # We'll create two strings, to compare them
    new_string = input_string.replace(" ", "")
    reverse_string = input_string.replace(" ", "")
    # Traverse through each letter of the input string
    for word in input_string: # Originally, I was only given the a FOR statement here, I wrote in the rest
        new_string+=word.replace(" ","").upper()
        # Add any non-blank letters to the
        # end of one string, and to the front
        # of the other string.

    if ___:
        new_string = ___
        reverse_string = ___
    # # Compare the strings
      if ___:
          return True
          return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
</code>```

I have removed the empty spaces and made everything the same case. I have assigned the characters to new_string, but it looks like I am supposed to use join to add the characters, but when I do the print statement does not print anything. I am unsure how to add the items in reverse order.
I am not even sure if I am on the correct track, because I am unsure what the IF statement is asking. I would think I should be able to use a loop to create the string and then compare the two strings.

Also, could someone please explain why new_string.join(word) does not print anything out? How am I using it incorrectly?

Thank you very much for any possible assistance.

答:
```<code>def is_palindrome(input_string):
    # We'll create two strings, to compare them
    new_string = ""
    reverse_string = ""
    # Traverse through each letter of the input string
    for char in input_string:
        # Add any non-blank letters to the
        # end of one string, and to the front
        # of the other string.
        if char !=" ":
            new_string +=char.lower()

            reverse_string =char.lower()+reverse_string

    # Compare the strings
    if new_string==reverse_string:
        return True
    return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
</code>```

Body:
I am trying to follow the instructions to create a palindrome. I am given half a function, and I have to fill in the blanks. I am currently unable to get the loop to work correctly. I am also unsure how to add characters to the beginning or the end of string without using the + or a comma. I do not think that is what I am being asked to do.
Here are the instructions;

The is_palindrome function checks if a string is a palindrome... Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

def is_palindrome(input_string):
    # We'll create two strings, to compare them
    new_string = input_string.replace(" ", "")
    reverse_string = input_string.replace(" ", "")
    # Traverse through each letter of the input string
    for word in input_string: # Originally, I was only given the a FOR statement here, I wrote in the rest
        new_string+=word.replace(" ","").upper()
        # Add any non-blank letters to the
        # end of one string, and to the front
        # of the other string.

    if ___:
        new_string = ___
        reverse_string = ___
    # # Compare the strings
      if ___:
          return True
          return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True

I have removed the empty spaces and made everything the same case. I have assigned the characters to new_string, but it looks like I am supposed to use join to add the characters, but when I do the print statement does not print anything. I am unsure how to add the items in reverse order.
I am not even sure if I am on the correct track, because I am unsure what the IF statement is asking. I would think I should be able to use a loop to create the string and then compare the two strings.

Also, could someone please explain why new_string.join(word) does not print anything out? How am I using it incorrectly?

Thank you very much for any possible assistance.


问:
Open the View over the other not as a subView?
I want to overlap view over the another view. I don't want to add it as a subView. The new view should be added with following rect size (280,400) on the super view of size (320,460).

Can any one suggest me the right way for doing this.

Thanks in advance

答: You could add both view as subviews of a superview. And the superviews view controller handles the show and hide of the subviews.</p>


问:
When I try to clear the workspace in R console, it always asks through a pop-up. How can I disable the pop-up?
When I try to clear the workspace in R console, it always pops up a dialog saying:

```<code>All objects in the workspace will be removed. Are you sure you want to proceed?
</code>```

Can I have a way to disable this popup?

答: There are some suggestions (here) depending on your platform. Looks like passing the "no-save" option when invoking R is your best bet: https://stackoverflow.com/a/4996252/8273813</p>

Body:
When I try to clear the workspace in R console, it always pops up a dialog saying:

All objects in the workspace will be removed. Are you sure you want to proceed?

Can I have a way to disable this popup?


问:
Setting up production postgres (createdb permissions)
I'm setting up postgres on DigitalOcean. I've set PG envs. The 9s are obviously redacted data. To facilitate the ssl connection, ~/.postgresql/root.crt exists.

# env | grep PG
PGPORT=99999
PGPASSWORD=9999999999999
PGSSLMODE=require
PGUSER=doadmin
PGDATABASE=auth_service_prod
PGHOST=private-db-postgresql-sfo9-99999-do-user-9999999-9.a.db.ondigitalocean.com
```

<p>When calling <code>createdb</code>, it fails:</p>

<pre class="lang-sh prettyprint-override"><code># createdb
createdb: could not connect to database template1: FATAL:  pg_hba.conf rejects connection for host "10.999.9.99", user "doadmin", database "template1", SSL on
</code>```

I can connect to psql, though. I don't know enough about configuring postgres to allow doadmin to create a db, but hopefully here is some useful info:

# psql
psql (11.7 (Debian 11.7-0+deb10u1), server 11.8)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

auth_service_prod=> \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 _dodb     | Superuser, Replication                                     | {}
 doadmin   | Create role, Create DB, Replication, Bypass RLS            | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

auth_service_prod=> \l
                                      List of databases
       Name        |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-------------------+----------+----------+-------------+-------------+-----------------------
 _dodb             | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 auth_service_prod | doadmin  | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 defaultdb         | doadmin  | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0         | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                   |          |          |             |             | postgres=CTc/postgres
 template1         | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                   |          |          |             |             | postgres=CTc/postgres
(5 rows)
```

答: DigitalOcean doesn't allow createdb from postgres, apparently. I removed the code creating databases, and created them "manually" from their GUI. The app is now only responsible for managing the schema, not the database(s).

Body:
I'm setting up postgres on DigitalOcean. I've set PG envs. The 9s are obviously redacted data. To facilitate the ssl connection, ~/.postgresql/root.crt exists.

# env | grep PG
PGPORT=99999
PGPASSWORD=9999999999999
PGSSLMODE=require
PGUSER=doadmin
PGDATABASE=auth_service_prod
PGHOST=private-db-postgresql-sfo9-99999-do-user-9999999-9.a.db.ondigitalocean.com

When calling createdb, it fails:

# createdb
createdb: could not connect to database template1: FATAL:  pg_hba.conf rejects connection for host "10.999.9.99", user "doadmin", database "template1", SSL on

I can connect to psql, though. I don't know enough about configuring postgres to allow doadmin to create a db, but hopefully here is some useful info:

# psql
psql (11.7 (Debian 11.7-0+deb10u1), server 11.8)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

auth_service_prod=> \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 _dodb     | Superuser, Replication                                     | {}
 doadmin   | Create role, Create DB, Replication, Bypass RLS            | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

auth_service_prod=> \l
                                      List of databases
       Name        |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-------------------+----------+----------+-------------+-------------+-----------------------
 _dodb             | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 auth_service_prod | doadmin  | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 defaultdb         | doadmin  | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0         | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                   |          |          |             |             | postgres=CTc/postgres
 template1         | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                   |          |          |             |             | postgres=CTc/postgres
(5 rows)


问:
Visual Studio Code split terminal on startup
Is there a way to have visual studio code launch the split terminal (Ctrl + \) on startup?

Or alternatively, is it possible to save my screen layout so I don't have to split the terminal manually?

答:
Some of this functionality was added since the question was asked.  Now you can put this into your tasks.json:

```<code> {
  "label": "SplitTerminalonStartip",
  "command": "${command:workbench.action.terminal.split}",
  "type": "shell",
  "problemMatcher": [],
  "runOptions": { "runOn": "folderOpen" }
},
</code>```

and the terminal will be split on startup.

Body:
Some of this functionality was added since the question was asked.  Now you can put this into your tasks.json:

 {
  "label": "SplitTerminalonStartip",
  "command": "${command:workbench.action.terminal.split}",
  "type": "shell",
  "problemMatcher": [],
  "runOptions": { "runOn": "folderOpen" }
},

and the terminal will be split on startup.


问:
Combine datafames in Python Pandas
I have two dataframes that I created in Pandas using python. And I want to combine them into one dataframe with the columns Name, PrivateIP and Memory.

hosts_df:

```<code>***Hosts Data Frame:
                      Name     PrivateIP
0               bastion001     10.238.2.166
1          logicmonitor001     10.238.2.52
2          logicmonitor002     45.21.2.1
***
</code>```

memory_df:

```<code>***Memory Data Frame:
     Memory
0   1843260
0   7706164
0   7904828
***
</code>```

Also I want to get rid of the column of zeros in the memory_df.

Here is my code.

code

```<code>    import os
    import pandas as pd
    filelist = os.listdir(text_path)
    # Read the servers into the DF
    hosts_list = os.path.join('..', '..', 'source_files', 'aws_hosts_list', 'aws_hosts_list.csv')
    text_path = "/home/tdun0002/stash/cloud_scripts/aws_scripts/output_files/memory_stats/text/"
    hosts_df = pd.read_csv(hosts_list, skipinitialspace=True)
    hosts_df.columns = ["Name", "PrivateIP"]
    # Create the memory dataframe
    column_names = ["Memory"]
    memory_df = pd.DataFrame(columns=column_names)
    print(f"Reading text files into the Memory DF")
    for filename in filelist:
        print(f"Adding filename: {filename}")
        filename = text_path + filename
        temp_df = pd.read_csv(filename, delim_whitespace=True, names=column_names)
        memory_df = memory_df.append(temp_df)

    memory_df.Memory = memory_df.Memory.astype("int32")
</code>```

How can I combine these datfames into one with the columns: Name, PrivateIP, Memory?

答:
Try this.

Reset index of memory_df dataframe.

Concatenate the two dataframes: hosts_df and memory_df.

pd.concat([hosts_df, memory_df.reset_index(drop=True)], axis=1)
```

<h2>Code: Example</h2>

<pre class="lang-py prettyprint-override"><code># Dummy Data
hosts_df = pd.DataFrame({'Name': ['bastion001', 'logicmonitor001', 'logicmonitor002'],
                      'PrivateIP': ["10.238.2.166", "10.238.2.52", "45.21.2.1"]})
memory_df = pd.DataFrame({'Memory': [1843260, 7706164, 7904828]}).reindex(index=[0,0,0])

# Concat dataframes
df = pd.concat([hosts_df, memory_df.reset_index(drop=True)], axis=1)
print(df)
</code>```

Output:

              Name     PrivateIP   Memory
0       bastion001  10.238.2.166  1843260
1  logicmonitor001   10.238.2.52  1843260
2  logicmonitor002     45.21.2.1  1843260
```

Title: Combine datafames in Python Pandas

Body:
I have two dataframes that I created in Pandas using python. And I want to combine them into one dataframe with the columns Name, PrivateIP and Memory.

hosts_df:

***Hosts Data Frame:
                      Name     PrivateIP
0               bastion001     10.238.2.166
1          logicmonitor001     10.238.2.52
2          logicmonitor002     45.21.2.1
***

memory_df:

***Memory Data Frame:
     Memory
0   1843260
0   7706164
0   7904828
***

Also I want to get rid of the column of zeros in the memory_df.

Here is my code.

code

    import os
    import pandas as pd
    filelist = os.listdir(text_path)
    # Read the servers into the DF
    hosts_list = os.path.join('..', '..', 'source_files', 'aws_hosts_list', 'aws_hosts_list.csv')
    text_path = "/home/tdun0002/stash/cloud_scripts/aws_scripts/output_files/memory_stats/text/"
    hosts_df = pd.read_csv(hosts_list, skipinitialspace=True)
    hosts_df.columns = ["Name", "PrivateIP"]
    # Create the memory dataframe
    column_names = ["Memory"]
    memory_df = pd.DataFrame(columns=column_names)
    print(f"Reading text files into the Memory DF")
    for filename in filelist:
        print(f"Adding filename: {filename}")
        filename = text_path + filename
        temp_df = pd.read_csv(filename, delim_whitespace=True, names=column_names)
        memory_df = memory_df.append(temp_df)

    memory_df.Memory = memory_df.Memory.astype("int32")

How can I combine these datfames into one with the columns: Name, PrivateIP, Memory?

Body:
Try this.

Reset index of memory_df dataframe.

Concatenate the two dataframes: hosts_df and memory_df.

pd.concat([hosts_df, memory_df.reset_index(drop=True)], axis=1)

Code: Example

# Dummy Data
hosts_df = pd.DataFrame({'Name': ['bastion001', 'logicmonitor001', 'logicmonitor002'],
                      'PrivateIP': ["10.238.2.166", "10.238.2.52", "45.21.2.1"]})
memory_df = pd.DataFrame({'Memory': [1843260, 7706164, 7904828]}).reindex(index=[0,0,0])

# Concat dataframes
df = pd.concat([hosts_df, memory_df.reset_index(drop=True)], axis=1)
print(df)

Output:

              Name     PrivateIP   Memory
0       bastion001  10.238.2.166  1843260
1  logicmonitor001   10.238.2.52  1843260
2  logicmonitor002     45.21.2.1  1843260


问:
SwiftUI update navigation bar title color
How to change the navigation bar title color in SwiftUI

NavigationView {
    List {
        ForEach(0..<15) { item in
            HStack {
                Text("Apple")
                    .font(.headline)
                    .fontWeight(.medium)
                    .color(.orange)
                    .lineLimit(1)
                    .multilineTextAlignment(.center)
                    .padding(.leading)
                    .frame(width: 125, height: nil)

                Text("Apple Infinite Loop. Address: One Infinite Loop Cupertino, CA 95014 (408) 606-5775 ")
                    .font(.subheadline)
                    .fontWeight(.regular)
                    .multilineTextAlignment(.leading)
                    .lineLimit(nil)
            }
        }
    }
    .navigationBarTitle(Text("TEST")).navigationBarHidden(false).foregroundColor(.orange)
}
```

I have tried with .foregroundColor(.orange) but it is not working

also tried             .navigationBarTitle(Text("TEST").color(.orange))

答:
I have searched for this issue and find a great article about this, you could wrap the settings of navigation bar style as a view modifier.

Check this Link.

Notes: I believe you need to update some code in this example, add titleColor parameter.

```<code>struct NavigationBarModifier: ViewModifier {

    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {

    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }

}
</code>```

After that, apply like this:

```<code>.navigationBarColor(backgroundColor: .clear, titleColor: .white)
</code>```

I hope it will work.

Body:
How to change the navigation bar title color in SwiftUI

NavigationView {
    List {
        ForEach(0..<15) { item in
            HStack {
                Text("Apple")
                    .font(.headline)
                    .fontWeight(.medium)
                    .color(.orange)
                    .lineLimit(1)
                    .multilineTextAlignment(.center)
                    .padding(.leading)
                    .frame(width: 125, height: nil)

                Text("Apple Infinite Loop. Address: One Infinite Loop Cupertino, CA 95014 (408) 606-5775 ")
                    .font(.subheadline)
                    .fontWeight(.regular)
                    .multilineTextAlignment(.leading)
                    .lineLimit(nil)
            }
        }
    }
    .navigationBarTitle(Text("TEST")).navigationBarHidden(false).foregroundColor(.orange)
}

I have tried with .foregroundColor(.orange) but it is not working

also tried             .navigationBarTitle(Text("TEST").color(.orange))

Body:
I have searched for this issue and find a great article about this, you could wrap the settings of navigation bar style as a view modifier.

Check this Link.

Notes: I believe you need to update some code in this example, add titleColor parameter.

struct NavigationBarModifier: ViewModifier {

    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {

    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }

}

After that, apply like this:

.navigationBarColor(backgroundColor: .clear, titleColor: .white)

I hope it will work.


问:
Touchablehighlight not clickable if position absolute
I have a Touchablehighlight that I need to position absolute, but it becomes unclickable after I do it.

What could cause this? It functions like it should if I dont have the position set to absolute.

答:
This props help to disable ScrollView to catch all touches and let child handles

```<code> keyboardShouldPersistTaps='always'
</code>```

'always', the keyboard will not dismiss automatically, and the scroll view will not catch taps, but children of the scroll view can catch taps.

'handled', the keyboard will not dismiss automatically when the tap was handled by children of the scroll view (or captured by an ancestor).

https://reactnative.dev/docs/scrollview#keyboardshouldpersisttaps

Body:
This props help to disable ScrollView to catch all touches and let child handles

 keyboardShouldPersistTaps='always'

'always', the keyboard will not dismiss automatically, and the scroll view will not catch taps, but children of the scroll view can catch taps.

'handled', the keyboard will not dismiss automatically when the tap was handled by children of the scroll view (or captured by an ancestor).

https://reactnative.dev/docs/scrollview#keyboardshouldpersisttaps


问:
Octave: Save a table inside a table
I am trying to save an array inside a table and i get this error: nonconformant arguments (op1 is 1x1, op2 is 1x4)

I have a function running which produces an array of 1 row and 4 columns. For example:

W =   0.32574   0.21354   0.10639   0.35433

What I am trying to do is save all the results that are being generated from the loops. What I am doing is this (for N=4):

```<code>for m=1:15
  W(m)=weights(N) # N=the number of columns it is going to generate
endfor
</code>```

My function looks like this: (e.g criteria=4)

```<code>function W=weights(criteria)

W=zeros(1,criteria); #fill the table with zeros
x=rand(1,criteria); #Random numbers are generated, range=[0,1]
sumx=sum(x); #Sum of all random numbers
factorsumx=1/sumx; #calculate the factor
W=x.*factorsumx; #Random numbers are multiplied with 1/sumx
finalsum=sum(W); #FinalSum is to confirm that the sum of weights is always equal to 1

endfunction
</code>```

答:
as op2 is 1x4 you need op1 of same size

```<code>N=4;
w=zeros(15,N);

for m=1:15
  W(m,1:N)=weights(N) # N=the number of columns it is going to generate
endfor
</code>```

Title: Octave: Save a table inside a table

Body:
I am trying to save an array inside a table and i get this error: nonconformant arguments (op1 is 1x1, op2 is 1x4)

I have a function running which produces an array of 1 row and 4 columns. For example:

W =   0.32574   0.21354   0.10639   0.35433

What I am trying to do is save all the results that are being generated from the loops. What I am doing is this (for N=4):

for m=1:15
  W(m)=weights(N) # N=the number of columns it is going to generate
endfor

My function looks like this: (e.g criteria=4)

function W=weights(criteria)

W=zeros(1,criteria); #fill the table with zeros
x=rand(1,criteria); #Random numbers are generated, range=[0,1]
sumx=sum(x); #Sum of all random numbers
factorsumx=1/sumx; #calculate the factor
W=x.*factorsumx; #Random numbers are multiplied with 1/sumx
finalsum=sum(W); #FinalSum is to confirm that the sum of weights is always equal to 1

endfunction

Body:
as op2 is 1x4 you need op1 of same size

N=4;
w=zeros(15,N);

for m=1:15
  W(m,1:N)=weights(N) # N=the number of columns it is going to generate
endfor


问:
url module in node.js
I'm trying to fetch the query information from the url, using:

url.parse(req.url, true)

I catch that in the console to see the information and it gives me back this:

Any ideas on what is happening?

Thank you.

答: I just used the value ignoring the [Object null prototype] message and it worked as it should.</p>

Title: url module in node.js


问:
videojs with live stream ts
I am trying to get a live stream from an IPTV service into a webpage for a magicmirror project. I am trying to get a single new channel to embed into the page.

I found that the ts file is using this URL, it loads fine in VLC: http://host.net:826/live/hello/413.ts

I created an m3u8 that looks like this:

```<code>#EXTM3U

#EXTINF:-1

http://host.net:826/live/hello/413.ts
</code>```

When I use this code, the file never loads the stream from the provider.

```<code><video-js id="my_video_1" class="center" controls autoplay preload="auto" width="950" height="600">
  <source src="playlist.m3u8" type="application/x-mpegURL">
</video-js>
  </div>
<script>
  var player = videojs('my_video_1', {
    html5: {
      hls: {
        overrideNative: true
      }
    }
  });
</script>
</code>```

I have run the stream through ffmpeg so that it dumps the files locally and then creates a local m3u8 file. If I then point the above code to that m3u8 file, it loads and runs fine - but I am not live, it's starting to copy the stream local from whenever I start it. So if I refresh the page, the stream begins from the beginning of the locally saved files again.

答:
I know its been 6 months since this questions was asked, I recently worked on the similar issues and figured I'll share my solution.

You can do this with hls.js without creating m3u8 index.

Learn more about hls.js at: https://github.com/video-dev/hls.js/

Start by renaming .ts stream URL to .m3u8, there is no need to create m3u8 index http://host.net:826/live/hello/413.ts - >  http://host.net:826/live/hello/413.m3u8

HTML:

```<code><script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

<button type="button" onclick="PlayVideo();">Play</button>
<video id="video" controls autoplay crossorigin="anonymous" />
</code>```

Javascript:

```<code>function PlayVideo() {
    var video = document.getElementById('video');
    var videoSrc = "http://host.net:826/live/hello/413.m3u8";
    if (Hls.isSupported()) {
        // The following hlsjsConfig is required for live-stream
        var hlsjsConfig = {
            "maxBufferSize": 0,
            "maxBufferLength": 30,
            "liveSyncDuration": 30,
            "liveMaxLatencyDuration": Infinity
        }
        var hls = new Hls(hlsjsConfig);
        hls.loadSource(videoSrc);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
            video.play();
        });
    }
    else if (elementId.canPlayType('application/vnd.apple.mpegurl')) {
        elementId.src = videoSrc;
        elementId.addEventListener('loadedmetadata', function () {
            elementId.play();
        });
    }
}
</code>```

You can further optimize the buffer to what you need it to be by changing values of the hlsjsConfig. See hls.js API details here: https://github.com/dailymotion/hls.js/blob/master/docs/API.md#second-step-instantiate-hls-object-and-bind-it-to-video-element

Title: videojs with live stream ts

Body:
I am trying to get a live stream from an IPTV service into a webpage for a magicmirror project. I am trying to get a single new channel to embed into the page.

I found that the ts file is using this URL, it loads fine in VLC: http://host.net:826/live/hello/413.ts

I created an m3u8 that looks like this:

#EXTM3U

#EXTINF:-1

http://host.net:826/live/hello/413.ts

When I use this code, the file never loads the stream from the provider.

<video-js id="my_video_1" class="center" controls autoplay preload="auto" width="950" height="600">
  <source src="playlist.m3u8" type="application/x-mpegURL">
</video-js>

I have run the stream through ffmpeg so that it dumps the files locally and then creates a local m3u8 file. If I then point the above code to that m3u8 file, it loads and runs fine - but I am not live, it's starting to copy the stream local from whenever I start it. So if I refresh the page, the stream begins from the beginning of the locally saved files again.

Body:
I know its been 6 months since this questions was asked, I recently worked on the similar issues and figured I'll share my solution.

You can do this with hls.js without creating m3u8 index.

Learn more about hls.js at: https://github.com/video-dev/hls.js/

Start by renaming .ts stream URL to .m3u8, there is no need to create m3u8 index http://host.net:826/live/hello/413.ts - >  http://host.net:826/live/hello/413.m3u8

HTML:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

<button type="button" onclick="PlayVideo();">Play</button>
<video id="video" controls autoplay crossorigin="anonymous" />

Javascript:

function PlayVideo() {
    var video = document.getElementById('video');
    var videoSrc = "http://host.net:826/live/hello/413.m3u8";
    if (Hls.isSupported()) {
        // The following hlsjsConfig is required for live-stream
        var hlsjsConfig = {
            "maxBufferSize": 0,
            "maxBufferLength": 30,
            "liveSyncDuration": 30,
            "liveMaxLatencyDuration": Infinity
        }
        var hls = new Hls(hlsjsConfig);
        hls.loadSource(videoSrc);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
            video.play();
        });
    }
    else if (elementId.canPlayType('application/vnd.apple.mpegurl')) {
        elementId.src = videoSrc;
        elementId.addEventListener('loadedmetadata', function () {
            elementId.play();
        });
    }
}

You can further optimize the buffer to what you need it to be by changing values of the hlsjsConfig. See hls.js API details here: https://github.com/dailymotion/hls.js/blob/master/docs/API.md#second-step-instantiate-hls-object-and-bind-it-to-video-element


问:
How to remove end space when firefox double click selected text
Firefox double click selected text with next space. How to remove end space on screen with javascript.
Thank you so much.</p>

答:
Thanks to @James Bellaby

It worked for me using Chrome 83, this is the code for removing leading and trailing spaces from the selected range.

```<code>function fix_selection(range) {
    var selection = window.getSelection();
    var selected = range.toString();
    range = selection.getRangeAt(0);
    let start = selection.anchorOffset;
    let end = selection.focusOffset;
    if (!selection.isCollapsed) {
        if (/\s+$/.test(selected)) { // Removes leading spaces
            if (start > end) {
                range.setEnd(selection.focusNode, --start);
            } else {
                range.setEnd(selection.anchorNode, --end);
            }
        }
        if (/^\s+/.test(selected)) { // Removes trailing spaces
            if (start > end) {
                range.setStart(selection.anchorNode, ++end);
            } else {
                range.setStart(selection.focusNode, ++start);
            }
        }
    }
    return range
}
</code>```

Body:
Thanks to @James Bellaby

It worked for me using Chrome 83, this is the code for removing leading and trailing spaces from the selected range.

function fix_selection(range) {
    var selection = window.getSelection();
    var selected = range.toString();
    range = selection.getRangeAt(0);
    let start = selection.anchorOffset;
    let end = selection.focusOffset;
    if (!selection.isCollapsed) {
        if (/\s+$/.test(selected)) { // Removes leading spaces
            if (start > end) {
                range.setEnd(selection.focusNode, --start);
            } else {
                range.setEnd(selection.anchorNode, --end);
            }
        }
        if (/^\s+/.test(selected)) { // Removes trailing spaces
            if (start > end) {
                range.setStart(selection.anchorNode, ++end);
            } else {
                range.setStart(selection.focusNode, ++start);
            }
        }
    }
    return range
}


问:
How can I match the input entered by the user to the lists in dictionary
```<code>print('-----------smart health prediction using data mining------------------- ')
mydict = {
    'malaria': ['fever', 'headache', 'sweats', 'chills', 'vomiting'],
    'anxiety': ['restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'],
    'asthma': ['wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'],
    'hepatitis C': ['shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'],
    'diabetes': ['feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'],
    'migraine': ['increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache']
}
print(mydict)
j = input("How many symptoms")
x = int(j)
list1 = []
for i in range(x):
    list1.append(input())
print (list1)
# From here I want the list to match the maximum symptoms with the lists in the dictionary
if list1 == mydict['malaria']
    print('true')
else:
    print('false')
mydict['malaria'], mydict['anxiety']
</code>```

答:
I have a couple of suggestions that should help here.

First, I would make the symptoms into a set, rather than a list. Why? Sets are unordered, and made to be easy to compare and manipulate. You don't care what order the symptoms were listed, you just want to see how many match. As you'll see below, this is easier with sets.

Next is that you are relying on symptoms being typed in EXACTLY as you have them in your dataset. If you can't guarantee that, you probably want to do some fuzzy matching. If this is the case, look up Levenshtein distance and implement something that gets a measure of similarity between the input symptoms and the sets of symptoms, and chooses the closest.

My code for solving this with exact matches (I noticed a few spelling mistakes, I just left them as-is):

```<code>mydict = {
    'malaria': {'fever', 'headache', 'sweats', 'chills', 'vomiting'},
    'anxiety': {'restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'},
    'asthma': {'wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'},
    'hepatitis C': {'shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'},
    'diabetes': {'feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'},
    'migraine': {'increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache'}
}
print(mydict)
j = input("How many symptoms")
x = int(j)
input_set = set()
for i in range(x):
    input_set.add(input())
print (input_set)
# Lets match the maximum # of symptoms with the sets in the dictionary
max_matches = 0
max_key = None
for disorder, symptoms_set in mydict.items():
    num_matches = len(input_set & symptoms_set) # find the length of the intersection!
    if num_matches > max_matches:
        max_matches = num_matches
        max_key = disorder
print(f'Disorder: {max_key} was best match, with {max_matches} matches!')
</code>```

This should provide easier (unordered) matching, and should display whatever disorder matched the greatest number of input symptoms. It does not handle ties, but that's details you can work out if desired.

Hope this helps, Happy Coding!

Body:
I have a couple of suggestions that should help here.

First, I would make the symptoms into a set, rather than a list. Why? Sets are unordered, and made to be easy to compare and manipulate. You don't care what order the symptoms were listed, you just want to see how many match. As you'll see below, this is easier with sets.

Next is that you are relying on symptoms being typed in EXACTLY as you have them in your dataset. If you can't guarantee that, you probably want to do some fuzzy matching. If this is the case, look up Levenshtein distance and implement something that gets a measure of similarity between the input symptoms and the sets of symptoms, and chooses the closest.

My code for solving this with exact matches (I noticed a few spelling mistakes, I just left them as-is):

mydict = {
    'malaria': {'fever', 'headache', 'sweats', 'chills', 'vomiting'},
    'anxiety': {'restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'},
    'asthma': {'wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'},
    'hepatitis C': {'shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'},
    'diabetes': {'feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'},
    'migraine': {'increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache'}
}
print(mydict)
j = input("How many symptoms")
x = int(j)
input_set = set()
for i in range(x):
    input_set.add(input())
print (input_set)
# Lets match the maximum # of symptoms with the sets in the dictionary
max_matches = 0
max_key = None
for disorder, symptoms_set in mydict.items():
    num_matches = len(input_set & symptoms_set) # find the length of the intersection!
    if num_matches > max_matches:
        max_matches = num_matches
        max_key = disorder
print(f'Disorder: {max_key} was best match, with {max_matches} matches!')

This should provide easier (unordered) matching, and should display whatever disorder matched the greatest number of input symptoms. It does not handle ties, but that's details you can work out if desired.

Hope this helps, Happy Coding!