问:
SwiftUI: onCommit triggered when is when I click away rather than press Return
I am working with onCommit for a text view in SwiftUI (the app is for MacOS).

```<code>struct TextBlockView: View {
     @State private var content = ""
    var id = UUID()

       var body: some View {

        let block = MacEditorTextView(text: $content, onEditingChanged: {
            print("editing changed")
        }, onCommit: {
            Keystroke.keystroke.enterPressed = true
            print("add new textblock here")
            //trigger function to create next block
           }).multilineTextAlignment(.leading)
               .frame(minWidth: 300,
                      maxWidth: .infinity,
                      minHeight: 40,
                      maxHeight: .infinity)
                .focusable()

        let tag = Rectangle()
                    .fill(Color.init(red: 1.00, green: 0.95, blue: 0.80, opacity: 1))
                    .frame(width: 10, height: 10)

        return HStack {
            tag
            block
        }
       }
}
</code>```

The desired action occurs when the user clicks away from the text block (a new textblock is added). However, I would like this action to occur when the user hits return. It worked this way for about 30 minutes when I first wrote the code for onCommit, before it decided a commit was a click rather than press of the return key.

I have tried to use the "onCommand" instead of onCommit, but this did not work, and I am unsure if I used the appropriate selector. I have also tried to capture when the enter key is pressed at the level of the NSWindow. However, I decided this was not desired, as I do not wish for this action to take place whenever the enter key is pressed.

Any help in relating onCommit to a specific key (return) would be very appreciated.

I am new to StackOverflow, so let me know if more information is needed.

答:
You can implement something like this. When you click on the blue box, it sends a single to say you have. Put the box behind your text box.

Cut'n'Pasted this quickly, a lot more code than you really need, you can do some pruning to this answer too.

```<code>import SwiftUI
import Combine

let saidNDone = PassthroughSubject<Void, Never>()

struct ContentView: View {
var body: some View {
    Example1()
}
}

struct Example1: View {
@State var viewState: CGSize = .zero
@State var dragState: CGSize = .zero
@State var touched = false

var body: some View {
    let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: CoordinateSpace.global)
        .onChanged { (value) in
            self.dragState = value.translation
    }.onEnded { (value) in
        self.viewState.width += value.translation.width
        self.viewState.height += value.translation.height
        self.dragState = .zero
        saidNDone.send()
    }
    return VStack {
        Rectangle().foregroundColor(.blue).frame(width: 100, height: 100)
        .offset(x: dragState.width + viewState.width,
                y: dragState.height + viewState.height)
        .gesture(dragGesture)
        Text("Hello World ")
          .onReceive(saidNDone) { ( _ ) in
            self.touched = true
          }
        .foregroundColor(self.touched ? Color.red: Color.black)
    }
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
}
}
</code>```

Body:
I am working with onCommit for a text view in SwiftUI (the app is for MacOS).

struct TextBlockView: View {
     @State private var content = ""
    var id = UUID()

       var body: some View {

        let block = MacEditorTextView(text: $content, onEditingChanged: {
            print("editing changed")
        }, onCommit: {
            Keystroke.keystroke.enterPressed = true
            print("add new textblock here")
            //trigger function to create next block
           }).multilineTextAlignment(.leading)
               .frame(minWidth: 300,
                      maxWidth: .infinity,
                      minHeight: 40,
                      maxHeight: .infinity)
                .focusable()

        let tag = Rectangle()
                    .fill(Color.init(red: 1.00, green: 0.95, blue: 0.80, opacity: 1))
                    .frame(width: 10, height: 10)

        return HStack {
            tag
            block
        }
       }
}

The desired action occurs when the user clicks away from the text block (a new textblock is added). However, I would like this action to occur when the user hits return. It worked this way for about 30 minutes when I first wrote the code for onCommit, before it decided a commit was a click rather than press of the return key.

I have tried to use the "onCommand" instead of onCommit, but this did not work, and I am unsure if I used the appropriate selector. I have also tried to capture when the enter key is pressed at the level of the NSWindow. However, I decided this was not desired, as I do not wish for this action to take place whenever the enter key is pressed.

Any help in relating onCommit to a specific key (return) would be very appreciated.

I am new to StackOverflow, so let me know if more information is needed.

Body:
You can implement something like this. When you click on the blue box, it sends a single to say you have. Put the box behind your text box.

Cut'n'Pasted this quickly, a lot more code than you really need, you can do some pruning to this answer too.

import SwiftUI
import Combine

let saidNDone = PassthroughSubject<Void, Never>()

struct ContentView: View {
var body: some View {
    Example1()
}
}

struct Example1: View {
@State var viewState: CGSize = .zero
@State var dragState: CGSize = .zero
@State var touched = false

var body: some View {
    let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: CoordinateSpace.global)
        .onChanged { (value) in
            self.dragState = value.translation
    }.onEnded { (value) in
        self.viewState.width += value.translation.width
        self.viewState.height += value.translation.height
        self.dragState = .zero
        saidNDone.send()
    }
    return VStack {
        Rectangle().foregroundColor(.blue).frame(width: 100, height: 100)
        .offset(x: dragState.width + viewState.width,
                y: dragState.height + viewState.height)
        .gesture(dragGesture)
        Text("Hello World ")
          .onReceive(saidNDone) { ( _ ) in
            self.touched = true
          }
        .foregroundColor(self.touched ? Color.red: Color.black)
    }
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
}
}


来源: stackexchange

问:
How to write QuerySet syntax let field contains items in a list?
I know in Django I can use __icontains to query database use LIKE.

```<code>name = "joe"

Q(name__icontains=name)
</code>```

but if I have a list:

```<code>name_list = ["joe", "klare"]
</code>```

How can I write the QuerySet syntax let the name contains "joe" or "klare"?

答:
Create a generic function for such operations, if you regularly make such queries with different properties

```<code>def generate_property_in_list_query(property_name, list_items):
    query = None
    for item in list_items:
        filter_query = Q(**{"{}__icontains".format(property_name): item})
        query = filter_query if not query else query | filter_query
    return query
</code>```

Now you can create the query for name like

```<code>generate_property_in_list_query("name", ["joe", "klare"])
</code>```

And the model filter opertaion will be

```<code>Model.objects.filter(generate_property_in_list_query("name", ["joe", "klare"]))
</code>```

And if we want to search for some other properties, simply change the property name

ContentLicense: CC BY-SA 4.0

Body:
I know in Django I can use __icontains to query database use LIKE.

name = "joe"

Q(name__icontains=name)

but if I have a list:

name_list = ["joe", "klare"]

How can I write the QuerySet syntax let the name contains "joe" or "klare"?

Body:
Create a generic function for such operations, if you regularly make such queries with different properties

def generate_property_in_list_query(property_name, list_items):
    query = None
    for item in list_items:
        filter_query = Q(**{"{}__icontains".format(property_name): item})
        query = filter_query if not query else query | filter_query
    return query

Now you can create the query for name like

generate_property_in_list_query("name", ["joe", "klare"])

And the model filter opertaion will be

Model.objects.filter(generate_property_in_list_query("name", ["joe", "klare"]))

And if we want to search for some other properties, simply change the property name


问:
Java: HttpResponse headers never have "Content-Encoding" but do have "Vary: Accept-Encoding"
I'm using the following example: http://www.devdaily.com/java/jwarehouse/commons-httpclient-4.0.3/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java.shtml

While adding "Accept-Encoding: gzip" to the headers is expected to tell the server you can receive gxip encoding back, it doesn't appear to be working that way. Instead, the servers only respond with "Vary: Accept-Encoding". After a long time of Googling, I couldn't even really find out what "Vary: Accept-Encoding" means. Why aren't the servers responding with "Content-Encoding: gzip" as they should be? Am I missing something?

EDIT: For instance, when checking www.yahoo.com on this website (http://www.gidnetwork.com/tools/gzip-test.php), it pulls in the right header (the content-encoding one). However, when I pull in that website through the Java code, the content-encoding header doesn't show up. Why is that?

Here is the code I'm using to print the headers in Java:

```<code>        Header[] h = response.getAllHeaders();
        for (int x = 0; x < h.length; x++)
            System.out.println(h[x]);
</code>```

答:
Your server is probably not configured to return gzip'ped content.

EDIT: against http://apache.org/, the code works as described. The paste is at http://pastebin.com/Ajj4XBb1

ContentLicense: CC BY-SA 3.0

Body:
I'm using the following example: http://www.devdaily.com/java/jwarehouse/commons-httpclient-4.0.3/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java.shtml

While adding "Accept-Encoding: gzip" to the headers is expected to tell the server you can receive gxip encoding back, it doesn't appear to be working that way. Instead, the servers only respond with "Vary: Accept-Encoding". After a long time of Googling, I couldn't even really find out what "Vary: Accept-Encoding" means. Why aren't the servers responding with "Content-Encoding: gzip" as they should be? Am I missing something?

EDIT: For instance, when checking www.yahoo.com on this website (http://www.gidnetwork.com/tools/gzip-test.php), it pulls in the right header (the content-encoding one). However, when I pull in that website through the Java code, the content-encoding header doesn't show up. Why is that?

Here is the code I'm using to print the headers in Java:

        Header[] h = response.getAllHeaders();
        for (int x = 0; x < h.length; x++)
            System.out.println(h[x]);


问:
Unable to find HTML table with Python using BeautifulSoup
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"
</code>```

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:

答:
As Swapnil mentioned, you get that data from the api request. Now why he didn't go further and actually offer the solution to get the table fully, I'm not sure.

But that api returns the data in json format. So it's a matter of reading in the json, then use pandas to turn into a table:

```<code>import requests
import pandas as pd

url = 'https://iextrading.com/api/mobile/refdata'

jsonData = requests.get(url).json()

df = pd.DataFrame(jsonData)
</code>```

Output:

```<code>print (df)
                            Issuer Symbol        date isEnabled lit
0         AGILENT TECHNOLOGIES INC      A  2020-05-28         1   1
1                       ALCOA CORP     AA  2020-05-28         1   1
2     PERTH MINT PHYSICAL GOLD ETF   AAAU  2020-05-28         1   1
3      ATA CREATIVITY GLOBAL - ADR   AACG  2020-05-28         1   1
4      ADVISORSHARES DORSEY WRIGHT   AADR  2020-05-28         1   1
5      AMERICAN AIRLINES GROUP INC    AAL  2020-05-28         1   1
6      ALTISOURCE ASSET MANAGEMENT   AAMC  2020-05-28         1   1
7           ATLANTIC AMERICAN CORP   AAME  2020-05-28         1   1
8                      AARON'S INC    AAN  2020-05-28         1   1
9      APPLIED OPTOELECTRONICS INC   AAOI  2020-05-28         1   1
10                        AAON INC   AAON  2020-05-28         1   1
11          ADVANCE AUTO PARTS INC    AAP  2020-05-28         1   1
12                       APPLE INC   AAPL  2020-05-28         1   1
13       AMERICAN ASSETS TRUST INC    AAT  2020-05-28         1   1
14        ALMADEN MINERALS LTD - B    AAU  2020-05-28         1   1
15    ATLAS AIR WORLDWIDE HOLDINGS   AAWW  2020-05-28         1   1
16    ISHARES MSCI ALL COUNTRY ASI   AAXJ  2020-05-28         1   1
17             AXON ENTERPRISE INC   AAXN  2020-05-28         1   1
18    ALLIANCEBERNSTEIN HOLDING LP     AB  2020-05-28         1   1
19                ABB LTD-SPON ADR    ABB  2020-05-28         1   1
20                      ABBVIE INC   ABBV  2020-05-28         1   1
21          AMERISOURCEBERGEN CORP    ABC  2020-05-28         1   1
22                  AMERIS BANCORP   ABCB  2020-05-28         1   1
23         ABEONA THERAPEUTICS INC   ABEO  2020-05-28         1   1
24      ABSOLUTE CORE STRATEGY ETF   ABEQ  2020-05-28         1   1
25                    AMBEV SA-ADR   ABEV  2020-05-28         1   1
26         ASBURY AUTOMOTIVE GROUP    ABG  2020-05-28         1   1
27              ARCA BIOPHARMA INC   ABIO  2020-05-28         1   1
28              ABM INDUSTRIES INC    ABM  2020-05-28         1   1
29                     ABIOMED INC   ABMD  2020-05-28         1   1
                           ...    ...         ...       ...  ..
8806  ZK INTERNATIONAL GROUP CO LT   ZKIN  2020-05-28         1   1
8807               ZAI LAB LTD-ADR   ZLAB  2020-05-28         1   1
8808   ZOOM VIDEO COMMUNICATIONS-A     ZM  2020-05-28         1   1
8809  DIREXION ZACKS MLP HIGH INCO   ZMLP  2020-05-28         1   1
8810            ZION OIL & GAS INC     ZN  2020-05-28         1   1
8811              ZYNGA INC - CL A   ZNGA  2020-05-28         1   1
8812  CHINA SOUTHERN AIR-SPONS ADR    ZNH  2020-05-28         1   1
8813  ZENTALIS PHARMACEUTICALS INC   ZNTL  2020-05-28         1   1
8814                                ZNWAA  2020-05-28         1   1
8815  ZOMEDICA PHARMACEUTICALS COR    ZOM  2020-05-28         1   1
8816  PIMCO 25+ YR ZERO CPN US TIF   ZROZ  2020-05-28         1   1
8817                   ZSCALER INC     ZS  2020-05-28         1   1
8818            ZOSANO PHARMA CORP   ZSAN  2020-05-28         1   1
8819   PROSHARES ULTRASHORT SILVER    ZSL  2020-05-28         1   1
8820                                ZTEST  2020-05-28         1   1
8821    ZTO EXPRESS CAYMAN INC-ADR    ZTO  2020-05-28         1   1
8822  VIRTUS TOTAL RETURN FUND INC    ZTR  2020-05-28         1   1
8823                    ZOETIS INC    ZTS  2020-05-28         1   1
8824                    ZUMIEZ INC   ZUMZ  2020-05-28         1   1
8825           ZUORA INC - CLASS A    ZUO  2020-05-28         1   1
8826                     ZOVIO INC    ZVO  2020-05-28         1   1
8827                                  ZVV  2020-05-28         1   1
8828                                 ZVVV  2020-05-28         1   1
8829                                ZVZZT  2020-05-28         1   1
8830                                ZWZZT  2020-05-28         1   1
8831                                ZXIET  2020-05-28         1   1
8832                                ZXZZT  2020-05-28         1   1
8833                 ZYMEWORKS INC   ZYME  2020-05-28         1   1
8834   ZYNERBA PHARMACEUTICALS INC   ZYNE  2020-05-28         1   1
8835                     ZYNEX INC   ZYXI  2020-05-28         1   1

[8836 rows x 5 columns]
</code>```

Body:
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:

Body:
As Swapnil mentioned, you get that data from the api request. Now why he didn't go further and actually offer the solution to get the table fully, I'm not sure.

But that api returns the data in json format. So it's a matter of reading in the json, then use pandas to turn into a table:

import requests
import pandas as pd

url = 'https://iextrading.com/api/mobile/refdata'

jsonData = requests.get(url).json()

df = pd.DataFrame(jsonData)

Output:

print (df)
                            Issuer Symbol        date isEnabled lit
0         AGILENT TECHNOLOGIES INC      A  2020-05-28         1   1
1                       ALCOA CORP     AA  2020-05-28         1   1
2     PERTH MINT PHYSICAL GOLD ETF   AAAU  2020-05-28         1   1
3      ATA CREATIVITY GLOBAL - ADR   AACG  2020-05-28         1   1
4      ADVISORSHARES DORSEY WRIGHT   AADR  2020-05-28         1   1
5      AMERICAN AIRLINES GROUP INC    AAL  2020-05-28         1   1
6      ALTISOURCE ASSET MANAGEMENT   AAMC  2020-05-28         1   1
7           ATLANTIC AMERICAN CORP   AAME  2020-05-28         1   1
8                      AARON'S INC    AAN  2020-05-28         1   1
9      APPLIED OPTOELECTRONICS INC   AAOI  2020-05-28         1   1
10                        AAON INC   AAON  2020-05-28         1   1
11          ADVANCE AUTO PARTS INC    AAP  2020-05-28         1   1
12                       APPLE INC   AAPL  2020-05-28         1   1
13       AMERICAN ASSETS TRUST INC    AAT  2020-05-28         1   1
14        ALMADEN MINERALS LTD - B    AAU  2020-05-28         1   1
15    ATLAS AIR WORLDWIDE HOLDINGS   AAWW  2020-05-28         1   1
16    ISHARES MSCI ALL COUNTRY ASI   AAXJ  2020-05-28         1   1
17             AXON ENTERPRISE INC   AAXN  2020-05-28         1   1
18    ALLIANCEBERNSTEIN HOLDING LP     AB  2020-05-28         1   1
19                ABB LTD-SPON ADR    ABB  2020-05-28         1   1
20                      ABBVIE INC   ABBV  2020-05-28         1   1
21          AMERISOURCEBERGEN CORP    ABC  2020-05-28         1   1
22                  AMERIS BANCORP   ABCB  2020-05-28         1   1
23         ABEONA THERAPEUTICS INC   ABEO  2020-05-28         1   1
24      ABSOLUTE CORE STRATEGY ETF   ABEQ  2020-05-28         1   1
25                    AMBEV SA-ADR   ABEV  2020-05-28         1   1
26         ASBURY AUTOMOTIVE GROUP    ABG  2020-05-28         1   1
27              ARCA BIOPHARMA INC   ABIO  2020-05-28         1   1
28              ABM INDUSTRIES INC    ABM  2020-05-28         1   1
29                     ABIOMED INC   ABMD  2020-05-28         1   1
                           ...    ...         ...       ...  ..
8806  ZK INTERNATIONAL GROUP CO LT   ZKIN  2020-05-28         1   1
8807               ZAI LAB LTD-ADR   ZLAB  2020-05-28         1   1
8808   ZOOM VIDEO COMMUNICATIONS-A     ZM  2020-05-28         1   1
8809  DIREXION ZACKS MLP HIGH INCO   ZMLP  2020-05-28         1   1
8810            ZION OIL & GAS INC     ZN  2020-05-28         1   1
8811              ZYNGA INC - CL A   ZNGA  2020-05-28         1   1
8812  CHINA SOUTHERN AIR-SPONS ADR    ZNH  2020-05-28         1   1
8813  ZENTALIS PHARMACEUTICALS INC   ZNTL  2020-05-28         1   1
8814                                ZNWAA  2020-05-28         1   1
8815  ZOMEDICA PHARMACEUTICALS COR    ZOM  2020-05-28         1   1
8816  PIMCO 25+ YR ZERO CPN US TIF   ZROZ  2020-05-28         1   1
8817                   ZSCALER INC     ZS  2020-05-28         1   1
8818            ZOSANO PHARMA CORP   ZSAN  2020-05-28         1   1
8819   PROSHARES ULTRASHORT SILVER    ZSL  2020-05-28         1   1
8820                                ZTEST  2020-05-28         1   1
8821    ZTO EXPRESS CAYMAN INC-ADR    ZTO  2020-05-28         1   1
8822  VIRTUS TOTAL RETURN FUND INC    ZTR  2020-05-28         1   1
8823                    ZOETIS INC    ZTS  2020-05-28         1   1
8824                    ZUMIEZ INC   ZUMZ  2020-05-28         1   1
8825           ZUORA INC - CLASS A    ZUO  2020-05-28         1   1
8826                     ZOVIO INC    ZVO  2020-05-28         1   1
8827                                  ZVV  2020-05-28         1   1
8828                                 ZVVV  2020-05-28         1   1
8829                                ZVZZT  2020-05-28         1   1
8830                                ZWZZT  2020-05-28         1   1
8831                                ZXIET  2020-05-28         1   1
8832                                ZXZZT  2020-05-28         1   1
8833                 ZYMEWORKS INC   ZYME  2020-05-28         1   1
8834   ZYNERBA PHARMACEUTICALS INC   ZYNE  2020-05-28         1   1
8835                     ZYNEX INC   ZYXI  2020-05-28         1   1

[8836 rows x 5 columns]


问:
Deno - How to fetch data from distant API or URL?
I'm wondering how I can get data from other servers and API with deno ? Everything in the documentation teach me about making http servers and read files from local source. But I can't find anything useful about reading something on the network.

How can read JSON data from the Stripe API ? Or if I want to read a HTML file with text inside ?

Thank you for your time!

答:
You'll need to do a HTTP Request, for that in Deno you use fetch, the same Web API the browsers use.

To read JSON response:

const res = await fetch('https://api.stripe.com');
const data = await res.json();
```

<p>If you want HTML:</p>

<pre class="lang-js prettyprint-override"><code>const res = await fetch('https://example.com');
const html = await res.text();
// Now you can use some HTML parsing lib
</code>```

fetch requires the --allow-net flag.

Body:
You'll need to do a HTTP Request, for that in Deno you use fetch, the same Web API the browsers use.

To read JSON response:

const res = await fetch('https://api.stripe.com');
const data = await res.json();

If you want HTML:

const res = await fetch('https://example.com');
const html = await res.text();
// Now you can use some HTML parsing lib

fetch requires the --allow-net flag.


问:
MySQL: Insert if this ip dont have any records
I use:

```<code>INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
        '{$_SERVER['REMOTE_ADDR']}');";
</code>```

I would like to add an if condition in the IF statement so that.

```<code>IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row
</code>```

is it doable or I better code it in php ?
thank you very much

P.s: I know how to do it with php, I want to learn it with MySQL.

Also i require that all 3 name,section,ip matchs not only ip

答:
To expand on Eric's excellent answer.

To add a unique constraint on each of the columns ip, name, section run the following code on the database

```<code>ALTER TABLE `test`.`rating`
  ADD UNIQUE INDEX `name`(`name`),
  ADD UNIQUE INDEX `section`(`section`),
  ADD UNIQUE INDEX `ip`(`ip`);
</code>```

To run a unique constraint on the combination of columns ip+name+section do:

```<code>ALTER TABLE `test`.`rating`
  ADD UNIQUE INDEX `name_section_ip`(`name`, `section`, `ip`);
</code>```

The last thing is probably what you want.

One last thing

I'm not 100% sure, but this usage of {$_SERVER['REMOTE_ADDR']} in the query does not look SQL-injection safe.

Consider changing it into:

```<code>$remote_adr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$session = mysql_real_escape_string($_SESSION['user']);
$query = "INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
  VALUES ('$name', '$session', '$rate', '$section','$remote_adr')";
</code>```

Finally putting a ";" in a mysql_query() like so mysql_query("select * from x;"); does not work mysql_query() will only ever execute one query and will reject your ;.

Body:
I use:

INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
        '{$_SERVER['REMOTE_ADDR']}');";

I would like to add an if condition in the IF statement so that.

IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row

is it doable or I better code it in php ?
thank you very much

P.s: I know how to do it with php, I want to learn it with MySQL.

Also i require that all 3 name,section,ip matchs not only ip

Body:
To expand on Eric's excellent answer.

To add a unique constraint on each of the columns ip, name, section run the following code on the database

ALTER TABLE `test`.`rating`
  ADD UNIQUE INDEX `name`(`name`),
  ADD UNIQUE INDEX `section`(`section`),
  ADD UNIQUE INDEX `ip`(`ip`);

To run a unique constraint on the combination of columns ip+name+section do:

ALTER TABLE `test`.`rating`
  ADD UNIQUE INDEX `name_section_ip`(`name`, `section`, `ip`);

The last thing is probably what you want.

One last thing

I'm not 100% sure, but this usage of {$_SERVER['REMOTE_ADDR']} in the query does not look SQL-injection safe.

Consider changing it into:

$remote_adr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$session = mysql_real_escape_string($_SESSION['user']);
$query = "INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
  VALUES ('$name', '$session', '$rate', '$section','$remote_adr')";

Finally putting a ";" in a mysql_query() like so mysql_query("select * from x;"); does not work mysql_query() will only ever execute one query and will reject your ;.


问:
How to make Fibonacci series to print out single digit
Below is a small project for my year one submission. But in that series, an odd number input doesn't print that number of numbers from the series, instead, it adds one to the odd number, which then becomes an even number, then print out that number of numbers from the series. I want to enable it to accept odd numbers too. How do do that? I thought of having two while loops, but i am unsure.

My code (without the header files and the main functions):

```<code>                int N;
                printf("Welcome to Fibonacci Series Mode.\n\nEnter how many numbers do you want from the series, from the start (Only Even Numbers): ");
                scanf("%d", &N);
                float x = 0;
                float y = 1;
                float xy;
                int F = 1;
                while ( F <= N ){
                    printf("\n%.0lf", x);
                    Sleep(250);
                    printf("\n%.0lf", y);
                    Sleep(250);
                    xy = x + y;
                    y += xy;
                    x = xy;
                    F++;
                }
</code>```

答:
What I am understanding from your code, and your question also, that is that the current code is printing only even numbers of Fibonacci Numbers. And that is true as you can see that in the while loop, there are two numbers printing in the same iteration. So, if you want an odd number of numbers from the series, you have to print one number at a time.

Also, note what is happening in your code.
Initially x = 0, y = 1

Then, xy = 0 + 1 = 1, (the third number in the Fibonacci Series)

At the next line, y gets one step ahead of xy.
 That is y = y + xy, that means if the xy variable holds the nth number in the Fibonacci Series, then, after this assignment, variable y holds the n+1th number of the series. And setting x = xy gets the n th term.

So in each iteration of the while loop, you are printing two values of the Fibonacci Series, also the variables x and y are jumping two steps forward at the same time.

To support odd integers, I would do something like following. Note I am using integer type variables as all the numbers in the Fibonacci Series are integers.

```<code>void print_first_n_fibo( int n ){
    int x = 0, y = 1;
    if(n == 1){
        printf("0\n");
    }
    else if(n == 2){
        printf("0\n1\n");
    }
    else{
        int current_term = 3;
        while(current_term <= n){
            int xy = x + y;
            printf("%d\n",xy);
            x = y;
            y = xy;
            current_term++;
        }
    }

}
</code>```

This function is generalized. It prints any first n terms of the Fibonacci Series, regardless of n being even or odd.

Body:
Below is a small project for my year one submission. But in that series, an odd number input doesn't print that number of numbers from the series, instead, it adds one to the odd number, which then becomes an even number, then print out that number of numbers from the series. I want to enable it to accept odd numbers too. How do do that? I thought of having two while loops, but i am unsure.

My code (without the header files and the main functions):

                int N;
                printf("Welcome to Fibonacci Series Mode.\n\nEnter how many numbers do you want from the series, from the start (Only Even Numbers): ");
                scanf("%d", &N);
                float x = 0;
                float y = 1;
                float xy;
                int F = 1;
                while ( F <= N ){
                    printf("\n%.0lf", x);
                    Sleep(250);
                    printf("\n%.0lf", y);
                    Sleep(250);
                    xy = x + y;
                    y += xy;
                    x = xy;
                    F++;
                }

Body:
What I am understanding from your code, and your question also, that is that the current code is printing only even numbers of Fibonacci Numbers. And that is true as you can see that in the while loop, there are two numbers printing in the same iteration. So, if you want an odd number of numbers from the series, you have to print one number at a time.

Also, note what is happening in your code.
Initially x = 0, y = 1

Then, xy = 0 + 1 = 1, (the third number in the Fibonacci Series)

At the next line, y gets one step ahead of xy.
 That is y = y + xy, that means if the xy variable holds the nth number in the Fibonacci Series, then, after this assignment, variable y holds the n+1th number of the series. And setting x = xy gets the n th term.

So in each iteration of the while loop, you are printing two values of the Fibonacci Series, also the variables x and y are jumping two steps forward at the same time.

To support odd integers, I would do something like following. Note I am using integer type variables as all the numbers in the Fibonacci Series are integers.

void print_first_n_fibo( int n ){
    int x = 0, y = 1;
    if(n == 1){
        printf("0\n");
    }
    else if(n == 2){
        printf("0\n1\n");
    }
    else{
        int current_term = 3;
        while(current_term <= n){
            int xy = x + y;
            printf("%d\n",xy);
            x = y;
            y = xy;
            current_term++;
        }
    }

}

This function is generalized. It prints any first n terms of the Fibonacci Series, regardless of n being even or odd.


答:
Deno strives to be as close to the existent browser API as possible.

That means, you can use fetch. Example:

```<code>// fetch-kitten.ts
fetch("https://placekitten.com/200/300").then(async (d) =>
  Deno.writeFile("kitten.jpg", new Uint8Array(await d.arrayBuffer()))
);
</code>```

CLI:

```<code>deno run --allow-net --allow-write fetch-kitten.ts
</code>```

Reference

Title: Deno - How to fetch data from distant API or URL?

Body:
I'm wondering how I can get data from other servers and API with deno ? Everything in the documentation teach me about making http servers and read files from local source. But I can't find anything useful about reading something on the network.

How can read JSON data from the Stripe API ? Or if I want to read a HTML file with text inside ?

Thank you for your time!

Body:
Deno strives to be as close to the existent browser API as possible.

That means, you can use fetch. Example:

// fetch-kitten.ts
fetch("https://placekitten.com/200/300").then(async (d) =>
  Deno.writeFile("kitten.jpg", new Uint8Array(await d.arrayBuffer()))
);

CLI:

deno run --allow-net --allow-write fetch-kitten.ts

Reference


问:
Unresolved class name proguard-rules Android Studio 4.0
When I update to Android Studio 4.0 proguard-rules it shows warning Unresolved class name. Below is example but I sure it still waring the exist class in my project.

```<code>-keep class com.squareup.haha.** { *; }
-keep class com.squareup.leakcanary.** { *; }
</code>```

If I change from ** to * this warning is gone.

```<code>-keep class com.squareup.haha.* { *; }
-keep class com.squareup.leakcanary.* { *; }
</code>```

Does anyone get this? Should I ignore this warning or it's bug of Android Studio 4.0?

Update

I find it's bug, it already assigned but not resolved https://issuetracker.google.com/issues/153616200

Update July

Google team already analysis and increase priory of this bug, it may be related to a newer version of R8.

Update August

Fixed in AS 4.2 Canary 9

答:
Check this issue: https://issuetracker.google.com/issues/147802433

`If you right-click on error, there is option "suppress for statement", after that AS adds a comment such as:

noinspection ShrinkerUnresolvedReference

-keep class not.existing

And with this comment there is no error for "not.existing".`

Body:
When I update to Android Studio 4.0 proguard-rules it shows warning Unresolved class name. Below is example but I sure it still waring the exist class in my project.

-keep class com.squareup.haha.** { *; }
-keep class com.squareup.leakcanary.** { *; }

If I change from ** to * this warning is gone.

-keep class com.squareup.haha.* { *; }
-keep class com.squareup.leakcanary.* { *; }

Does anyone get this? Should I ignore this warning or it's bug of Android Studio 4.0?

Update

I find it's bug, it already assigned but not resolved https://issuetracker.google.com/issues/153616200

Update July

Google team already analysis and increase priory of this bug, it may be related to a newer version of R8.

Update August

Fixed in AS 4.2 Canary 9


问:
Why AppEventsLogger.logEvent is undefined?

react-native: 0.40

react-native-fbsdk: 0.5

I want to use react-native-fbsdk in my React Native project to log events and I did all by instruction for this library. But when I tried to launch it on iOS emulator I got an error:

undefined is not an object (evaluating 'AppEventsLogger.logEvent')

答:
In my case, react-native link react-native-fbsdk worked. Also run react-native run-android after linking.

Hope this helps.


问:
Session Id's, UUID's and GUID's and just ID's in general
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

```<code>14th of May 2011 04:36:05PM
</code>```

If used as an identifier, could be changed to:

```<code>14052011163605
</code>```

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?

答: Why not just make your session ID column a unique column, and then generate a new session ID if you get a constraint violation error? That way the database will find this problem for you in basically the same way that you did (and as a bonus, it can fix it too).</p>

Body:
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

14th of May 2011 04:36:05PM

If used as an identifier, could be changed to:

14052011163605

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?


问:
How to check if a string contains a char?
I have a text file that I want to read. I want to know if one of the lines contains [ so I tried :

```<code>if(array[i] == "[")
</code>```

But this isn't working.

How can I check if a string contains a certain character?

答:
In strings, we can use find() to get the first occurrence (position) of the given "string"

```<code>string s = "dumm[y[";
int found = s.find('[');

cout<<"$ is present at position "<<firstOccurrence;   //$ is present at position 4

if (found < str.length()) {
    // char found
}
else{
    // char not found
}
</code>```

Body:
I have a text file that I want to read. I want to know if one of the lines contains [ so I tried :

if(array[i] == "[")

But this isn't working.

How can I check if a string contains a certain character?

Body:
In strings, we can use find() to get the first occurrence (position) of the given "string"

string s = "dumm[y[";
int found = s.find('[');

cout<<"$ is present at position "<<firstOccurrence;   //$ is present at position 4

if (found < str.length()) {
    // char found
}
else{
    // char not found
}


问:
Redirect for non authorized users not working in ajax request
I have a Cookie based authentication in my webapp to which a sub application make some ajax requests to get the data from db.

the issue is that if the user is not authenticated i redirect him to expired.html, in test mode if i just run in browser or postman an api call like example.com/api/test without getting first the authentication cookie i'm correctly redirected to expired.html. the issue comes when i try to call that api via ajax so by making a simple .get request as the following:

```<code>function getPlu(codplu, callback){
      let api = 'https://www.example.it/api/plu/?codplu=' + codplu
      $.get( api, callback );
}
  getPlu('COPERTI', callback => {
       ...
  });
</code>```

i just get the response from api with code 302 and a .get to expired.html with code 304 but the user still is not redirected to expired.html

So as you can see the status code for that api request is 302 and location should be expired.html BUT it's not getting redirected.

Might it be that browser doesn't handle automatically ajax redirects and i need to do it via client-side (redirect if status.code == 302) or i could fix  it via server side?

Here is how the authentication makes the redirect

```<code>        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => {
            options.Cookie.Name = "AUTH_TOKEN";
            options.Cookie.MaxAge = TimeSpan.FromMinutes(120);
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("https://www.example.it/vmenu/expired.html");
                    return Task.CompletedTask;
                }
            };
        });
</code>```

答:
Just to make this answer more clear:

jQuery's ajax uses the XMLHttpRequest object and its methods to execute requests. XMLHttpRequest will follow redirects automatically. Since it's XMLHttpRequest who does that, jQuery's ajax function doesn't even know about it. It only receives the final response, which in the OP's case is 200 Ok (or 304 Not Modified as OP posted).

Also, since the request is made by jQuery/XMLHttpRequest, the client view is not changed if a request or a redirect is executed. Everything is only in the browser's "behind execution".

Since all redirects are executed automatically by XMLHttpRequest, and jQuery is not able to tell if a redirect was made, the most reliable way (and that's the most important thing to me) is handle it manually:

1 - On server side, when unauthenticated request, add a custom header to the response, and respond with 200 OK:

```<code>OnRedirectToLogin = (context) =>
{
    context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
    context.Response.Headers.Add("X-Unauthenticated-Redirect", "https://www.example.it/vmenu/expired.html");
    return Task.CompletedTask;
}
</code>```

2 - On client side, just check if this custom header exists. If it does, redirect manually using window.location:

```<code>var redirectHeader = jqXHR.getResponseHeader('X-Unauthenticated-Redirect');
if (redirectHeader.length > 0) {
    window.location = redirectHeader;
}
</code>```

Just for reference, from XMLHttpRequest docs:

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.

Body:
I have a Cookie based authentication in my webapp to which a sub application make some ajax requests to get the data from db.

the issue is that if the user is not authenticated i redirect him to expired.html, in test mode if i just run in browser or postman an api call like example.com/api/test without getting first the authentication cookie i'm correctly redirected to expired.html. the issue comes when i try to call that api via ajax so by making a simple .get request as the following:

function getPlu(codplu, callback){
      let api = 'https://www.example.it/api/plu/?codplu=' + codplu
      $.get( api, callback );
}
  getPlu('COPERTI', callback => {
       ...
  });

i just get the response from api with code 302 and a .get to expired.html with code 304 but the user still is not redirected to expired.html

So as you can see the status code for that api request is 302 and location should be expired.html BUT it's not getting redirected.

Might it be that browser doesn't handle automatically ajax redirects and i need to do it via client-side (redirect if status.code == 302) or i could fix  it via server side?

Here is how the authentication makes the redirect

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => {
            options.Cookie.Name = "AUTH_TOKEN";
            options.Cookie.MaxAge = TimeSpan.FromMinutes(120);
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("https://www.example.it/vmenu/expired.html");
                    return Task.CompletedTask;
                }
            };
        });

Body:
Just to make this answer more clear:

jQuery's ajax uses the XMLHttpRequest object and its methods to execute requests. XMLHttpRequest will follow redirects automatically. Since it's XMLHttpRequest who does that, jQuery's ajax function doesn't even know about it. It only receives the final response, which in the OP's case is 200 Ok (or 304 Not Modified as OP posted).

Also, since the request is made by jQuery/XMLHttpRequest, the client view is not changed if a request or a redirect is executed. Everything is only in the browser's "behind execution".

Since all redirects are executed automatically by XMLHttpRequest, and jQuery is not able to tell if a redirect was made, the most reliable way (and that's the most important thing to me) is handle it manually:

1 - On server side, when unauthenticated request, add a custom header to the response, and respond with 200 OK:

OnRedirectToLogin = (context) =>
{
    context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
    context.Response.Headers.Add("X-Unauthenticated-Redirect", "https://www.example.it/vmenu/expired.html");
    return Task.CompletedTask;
}

2 - On client side, just check if this custom header exists. If it does, redirect manually using window.location:

var redirectHeader = jqXHR.getResponseHeader('X-Unauthenticated-Redirect');
if (redirectHeader.length > 0) {
    window.location = redirectHeader;
}

Just for reference, from XMLHttpRequest docs:

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.


问:
How to avoid all TSLint errors
I have 2 angular projects in my machine.

When I doing the first project nothing wrong with me there. I worked freely(without TSLint errors). But my second project always shows TSLint errors. I want the second project to be like the first one. Is there any way to do this?

```<code>Angular CLI: 8.3.26
Node: 12.16.3
OS: win32 x64
Angular: 8.2.14

@angular-devkit/architect         0.803.26
@angular-devkit/build-angular     0.803.26
@angular-devkit/build-optimizer   0.803.26
@angular-devkit/build-webpack     0.803.26
@angular-devkit/core              8.3.26
@angular-devkit/schematics        8.3.26
@angular/cli                      8.3.26
@ngtools/webpack                  8.3.26
@schematics/angular               8.3.26
@schematics/update                0.803.26
rxjs                              6.4.0
typescript                        3.5.3
webpack                           4.39.2
</code>```

This is an image of the First project. Which if works fine. Look,5 new lines, but no TSLint errors.

This is an image of the second project.

I want to make the second project work like the first. Is there is any way to do this?

答:
I found the answer to my own question.
 I am using IntelliJ to code.
In this IDE we can disable TSLint check.

Click on the red bulb on the left side and next click the TSLint options.

After this dialog box will appear. Uncheck the enable mode. That's it!

Title: How to avoid all TSLint errors

Body:
I have 2 angular projects in my machine.

When I doing the first project nothing wrong with me there. I worked freely(without TSLint errors). But my second project always shows TSLint errors. I want the second project to be like the first one. Is there any way to do this?

Angular CLI: 8.3.26
Node: 12.16.3
OS: win32 x64
Angular: 8.2.14

@angular-devkit/architect         0.803.26
@angular-devkit/build-angular     0.803.26
@angular-devkit/build-optimizer   0.803.26
@angular-devkit/build-webpack     0.803.26
@angular-devkit/core              8.3.26
@angular-devkit/schematics        8.3.26
@angular/cli                      8.3.26
@ngtools/webpack                  8.3.26
@schematics/angular               8.3.26
@schematics/update                0.803.26
rxjs                              6.4.0
typescript                        3.5.3
webpack                           4.39.2

This is an image of the First project. Which if works fine. Look,5 new lines, but no TSLint errors.

This is an image of the second project.

I want to make the second project work like the first. Is there is any way to do this?


问:
Dynamically change header title on react navigation 5.x
I have recently updated my project to react navigation 5.x.
In earlier version we used to set header title as follows :

```<code>static navigationOptions = ({ navigation }) => ({
        title: 'find',
});
</code>```

This is not working on React Navigation 5.x.
Please Suggest.

答:
Hey you should definitly check out this: https://reactnavigation.org/docs/screen-options-resolution/ </p>

<p>Here you can see how to set the title for each tab and each stack. Read threw the page and look at this func: </p>

```<code>function getHeaderTitle(route) {
  // Access the tab navigator's state using `route.state`
  const routeName = route.state
    ? // Get the currently active route name in the tab navigator
      route.state.routes[route.state.index].name
    : // If state doesn't exist, we need to default to `screen` param if available, or the initial screen
      // In our case, it's "Feed" as that's the first screen inside the navigator
      route.params?.screen || 'Feed';

  switch (routeName) {
    case 'Feed':
      return 'News feed';
    case 'Profile':
      return 'My profile';
    case 'Account':
      return 'My account';
  }
}
</code>```

Body:
I have recently updated my project to react navigation 5.x.
In earlier version we used to set header title as follows :

static navigationOptions = ({ navigation }) => ({
        title: 'find',
});

This is not working on React Navigation 5.x.
Please Suggest.

Body:
Hey you should definitly check out this: https://reactnavigation.org/docs/screen-options-resolution/

Here you can see how to set the title for each tab and each stack. Read threw the page and look at this func:

function getHeaderTitle(route) {
  // Access the tab navigator's state using `route.state`
  const routeName = route.state
    ? // Get the currently active route name in the tab navigator
      route.state.routes[route.state.index].name
    : // If state doesn't exist, we need to default to `screen` param if available, or the initial screen
      // In our case, it's "Feed" as that's the first screen inside the navigator
      route.params?.screen || 'Feed';

  switch (routeName) {
    case 'Feed':
      return 'News feed';
    case 'Profile':
      return 'My profile';
    case 'Account':
      return 'My account';
  }
}


问:
How to make embedded chart responsive
I have embedded a stock chart from Tradingview into my site, but I cannot make it responsive (especially the width). When the page shrinks the chart begin to move outside the screen. Here is the code:

```<code><div class="tradingview-widget-container">
  <div id="tradingview_8e656"></div>
  <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/SP-SPX/" rel="noopener" target="_blank"><span class="blue-text">SPX chart</span></a> by TradingView</div>
  <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
  <script type="text/javascript">
  new TradingView.widget({
    "height": 610,
    "symbol": "SP:SPX",
    "interval": "D",
    "timezone": "Etc/UTC",
    "theme": "Light",
    "style": "1",
    "locale": "en",
    "toolbar_bg": "#f1f3f6",
    "enable_publishing": false,
    "hide_side_toolbar": false,
    "allow_symbol_change": true,
    "container_id": "tradingview_8e656"
  });
  </script>
</div>
</code>```

I tried changing the units in width to rem and % (because I suppose they use px) but it didn't work. I also tried erasing height and width completly and adding "autosize": true instead. Then I thought that maybe I'm not editing it correctly, so I started learning about JavaScript objects in W3Schools. Couldn't find the information there either.

The best solution that I could come with is to set the overflow to hidden, but you can understand it's not right. What I need is something like "shrink to fit" property or simply edit the javascript somehow.

Other links I read (which also didn't help):

Make Embedded Tableau Responsive

Why don't flex items shrink past content size?

Here is my entire code- what I wanted to achieve is to open the chart from the navbar (I am using bootstrap):

```<code><div class="container-fluid sticky-top">
  <nav class="navbar navbar-expand-lg" style="background-color:#1B2034">
    <img src="media/a1.jpg" style="height:4rem;width:8rem">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon mb-2"><i class="fa fa-bars fa-2x" style="color:#0040ff"></i></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">home page<span class="sr-only">את/ה כאן</span></a>
        </li>
        <li class="nav-item">
          **<a class="nav-link" data-toggle="collapse" href="#graphs">chart page</a>**
        </li>
        <!-- other nav items -->
        <li class="nav-item mt-2">
          <input class="form-control" type="search" placeholder="חיפוש" aria-label="Search">
                      </li>
        <li class="nav-item mt-2">
          <button class="btn btn-outline-info mr-2" type="submit">חיפוש</button>
        </li>
      </ul>
    </div>
  </nav>
  <!-- Other pages -->
  <div class="container-fluid">
    <div class="collapse sticky-top" style="top:5rem;overflow:hidden" id="graphs">
      <div class="card card-body height:100%">
        <!-- TradingView Widget BEGIN -->
        THE CHART CODE
        <!-- TradingView Widget END -->
      </div>
    </div>

<div class="collapse sticky-top" style="top:5rem;overflow:hidden" id="graphs">
          <div class="card card-body height:100%">
</code>```

... Repeats ...

答:
Here is my solution how to make it in CSS.

Using the ID of this container -

Then just add in your .css file this lines of code
Main parameter  is !important

```<code>    #tradingview_8e656 {
width: 1000px !important;
height: 750px !important;
    }
</code>```

This works for me perfectly. Also it remains responsive on a devices.
Hope this helps.

Title: How to make embedded chart responsive

Body:
I have embedded a stock chart from Tradingview into my site, but I cannot make it responsive (especially the width). When the page shrinks the chart begin to move outside the screen. Here is the code:

SPX chart by TradingView

I tried changing the units in width to rem and % (because I suppose they use px) but it didn't work. I also tried erasing height and width completly and adding "autosize": true instead. Then I thought that maybe I'm not editing it correctly, so I started learning about JavaScript objects in W3Schools. Couldn't find the information there either.

The best solution that I could come with is to set the overflow to hidden, but you can understand it's not right. What I need is something like "shrink to fit" property or simply edit the javascript somehow.

Other links I read (which also didn't help):

Make Embedded Tableau Responsive

Why don't flex items shrink past content size?

Here is my entire code- what I wanted to achieve is to open the chart from the navbar (I am using bootstrap):

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          home pageאת/ה כאן

          **chart page**

          <input class="form-control" type="search" placeholder="חיפוש" aria-label="Search">

          <button class="btn btn-outline-info mr-2" type="submit">חיפוש</button>

        THE CHART CODE

... Repeats ...

Body:
Here is my solution how to make it in CSS.

Using the ID of this container - <div id="tradingview_8e656"></div>

Then just add in your .css file this lines of code
Main parameter  is !important

    #tradingview_8e656 {
width: 1000px !important;
height: 750px !important;
    }

This works for me perfectly. Also it remains responsive on a devices.
Hope this helps.


问:
I want to prevent duplicate string output
I wrote the code like this.

```<code>sentence = input("문자열 입력 : ")
sentence = sentence.lower()
sentence = sentence.replace(' ','')
def count(string):
    for i in range(0, len(sentence)):
        a = sentence[i]
        b = sentence.count(a)
        i += 1
        print("%s : %s" %(a, b))
    return
count(sentence)
</code>```

But I want to print it out once if there is already the same alphabet. For example, if I input the word 'APPLE, apple!', the code I wrote print
a : 2
 p : 4
 p : 4
 l : 2
 e : 2
 , : 1
 a : 2
 p : 4
 p : 4
 l : 2
 e : 2
 ! : 2, but I want to print like this.
a : 2
 p : 4
 l : 2
 e : 2
 , : 1
 ! : 1

I think

```<code>for i in range(0, len(sentence)):
  a = sentence[i]
  b = sentence.count(a)
  i += 1
</code>```

is wrong, but I don't know how to fix it.

What should I do???

答:
first thing to note is that the argument you pass to the function (string) and the variable you process
inside the function are different. So, the argument should be changed to sentence.

next, you could use a dictionary to keep score:

```<code>def count(sentence):
    count_dictionary = {}
    for character in sentence:
        count_dictionary[character] = sentence.count(character)

    for a, b in count_dictionary.items():
        print(a, ' : ', b)
    return count_dictionary
</code>```

Body:
I wrote the code like this.

sentence = input("문자열 입력 : ")
sentence = sentence.lower()
sentence = sentence.replace(' ','')
def count(string):
    for i in range(0, len(sentence)):
        a = sentence[i]
        b = sentence.count(a)
        i += 1
        print("%s : %s" %(a, b))
    return
count(sentence)

But I want to print it out once if there is already the same alphabet. For example, if I input the word 'APPLE, apple!', the code I wrote print
a : 2
 p : 4
 p : 4
 l : 2
 e : 2
 , : 1
 a : 2
 p : 4
 p : 4
 l : 2
 e : 2
 ! : 2, but I want to print like this.
a : 2
 p : 4
 l : 2
 e : 2
 , : 1
 ! : 1

I think

for i in range(0, len(sentence)):
  a = sentence[i]
  b = sentence.count(a)
  i += 1

is wrong, but I don't know how to fix it.

What should I do???

Body:
first thing to note is that the argument you pass to the function (string) and the variable you process
inside the function are different. So, the argument should be changed to sentence.

next, you could use a dictionary to keep score:

def count(sentence):
    count_dictionary = {}
    for character in sentence:
        count_dictionary[character] = sentence.count(character)

    for a, b in count_dictionary.items():
        print(a, ' : ', b)
    return count_dictionary


问:
DRF: How to insert data in another model class on deleting on model class
I am trying to insert data on one modal class on destroying another model class. My First model class:

```<code>class UserDevice(models.Model):
    type = models.ForeignKey(
        'Device',
        on_delete=models.CASCADE
    )
    hardware_serial = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

class NewDevice(models.Model):
    type = models.ForeignKey(
        'Device',
        on_delete = models.CASCADE
    )
    hardware_serial = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

Whenever I will destroy the UserDevice I want to the same device should be added in NewDevice

My serializer class is :

```<code>class UserDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserSensorDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']

    def create(self, validated_data):
        app_id = models.UserDevice.objects.filter(sensor_code= validated_data.get('hardware_serial', None)).first()
        if app_id:
            msg = _('Application ID is already registered')
            raise serializers.ValidationError(msg, code='authorization')
        else :
            return models.UserDevice.objects.create(**validated_data)

class NewDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.NewDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']
</code>```

My view class:

```<code>class UserSensorRemoveDevice(generics.DestroyAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.UserDevice.objects.all()
    serializer_class = serializers.UserDeviceSerializer
</code>```

What I have tried to override UserDevice destroy. But somehow its not working:

```<code>def destroy(self, validated_data):
        return models.NewDevice.objects.create(type = validated_data.get('type', None),hardware_serial = validated_data.get('hardware_serial', None))
</code>```

Any help will be highly appreciated. Thanks in advance.

答:
You can override UserDevice.delete() method

```<code>class UserDevice(models.Model):

    ...

    def delete(self, *args, **kwargs):
        NewDevice.objects.create(type=self.type, hardware_serial=self.hardware_serial)
        super().delete(*args, **kwargs)
</code>```

Body:
I am trying to insert data on one modal class on destroying another model class. My First model class:

class UserDevice(models.Model):
    type = models.ForeignKey(
        'Device',
        on_delete=models.CASCADE
    )
    hardware_serial = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

class NewDevice(models.Model):
    type = models.ForeignKey(
        'Device',
        on_delete = models.CASCADE
    )
    hardware_serial = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

Whenever I will destroy the UserDevice I want to the same device should be added in NewDevice

My serializer class is :

class UserDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserSensorDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']

    def create(self, validated_data):
        app_id = models.UserDevice.objects.filter(sensor_code= validated_data.get('hardware_serial', None)).first()
        if app_id:
            msg = _('Application ID is already registered')
            raise serializers.ValidationError(msg, code='authorization')
        else :
            return models.UserDevice.objects.create(**validated_data)

class NewDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.NewDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']

My view class:

class UserSensorRemoveDevice(generics.DestroyAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.UserDevice.objects.all()
    serializer_class = serializers.UserDeviceSerializer

What I have tried to override UserDevice destroy. But somehow its not working:

def destroy(self, validated_data):
        return models.NewDevice.objects.create(type = validated_data.get('type', None),hardware_serial = validated_data.get('hardware_serial', None))

Any help will be highly appreciated. Thanks in advance.

Body:
You can override UserDevice.delete() method

class UserDevice(models.Model):

    ...

    def delete(self, *args, **kwargs):
        NewDevice.objects.create(type=self.type, hardware_serial=self.hardware_serial)
        super().delete(*args, **kwargs)


问:
Springfox swagger-ui not sending with content-type header
I have integrated swagger to my Spring Boot project using SpringFox build and it work for my GET API. However on my POST API which requires the request in application/json format, the swagger-ui doesn't set the header.

My Code:

```<code>@PostMapping(value="/login", consumes="application/json", produces="application/json")
    public WsResponse login(UserLoginRequest requestBody) throws Exception {

        validateAuthToken(requestBody.getId(), requestBody.getToken());

        return serviceWs.login(requestBody);
    }
</code>```

The command generated from swagger-ui:

```<code>curl -X POST "http://localhost:8080/api/login?token=2342343324&username=23434&password=123" -H "accept: application/json"
</code>```

Note that the header "Content-Type" is not set and thus backend is giving an error when trying to call.

The issue is similar to this post but there's no resolution, any help is appreciated.

答:
Try putting application/json within the braces:

Note: Works for me for springfox-swagger2 and springfox-swagger-ui v2.8.0

Body:
I have integrated swagger to my Spring Boot project using SpringFox build and it work for my GET API. However on my POST API which requires the request in application/json format, the swagger-ui doesn't set the header.

My Code:

@PostMapping(value="/login", consumes="application/json", produces="application/json")
    public WsResponse login(UserLoginRequest requestBody) throws Exception {

        validateAuthToken(requestBody.getId(), requestBody.getToken());

        return serviceWs.login(requestBody);
    }

The command generated from swagger-ui:

curl -X POST "http://localhost:8080/api/login?token=2342343324&username=23434&password=123" -H "accept: application/json"

Note that the header "Content-Type" is not set and thus backend is giving an error when trying to call.

The issue is similar to this post but there's no resolution, any help is appreciated.


问:
Pull to Refresh and setState not working - React Native
React Native App

I am implementing Pull to refresh in my Flatlist prop "onRefresh"

onRefresh called the function "refreshcontrol()" see code below.

I need to change my state "refreshing" to true before I fetch from my API. But it throws the maximum update error.

```<code>export default class NotificationScreen extends Component {

  constructor(props) {
   super(props)
   this.state = {
      refreshing: false
    }
  }
.
.
.
.
.
  refreshControl() {
    const { refreshing } = this.state;
    this.setState({ refreshing : true )}.    // throws maximum update error

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={fetchNotifications.bind(this)}      //fetch from API only when refreshing is true
        colors={['#2B70AD']}
      />
    );
  };

}
</code>```

How else can I set my state to "refreshing :  true" ??? Help please!!!!

This is how it was fixed. Solution:

```<code>refresh = async() => {
    this.setState({refreshing : true})
    try {
      const notifications = await fetchNotifications();
      this.setState({
        notifications,
        error: null,
        refreshing: false
      });
    } catch (error) {
      this.setState({
        notifications: [],
        error,
        refreshing: false
      });
    }
  }

  refreshControl() {
    const { refreshing } = this.state;

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={this.refresh}
        colors={['#2B70AD']}
      />
    );
  };

</code>```

答: This should work perfectly. I think there is a typo in your code. You are using try instead of true. I think that might be the cause of the error.</p>

Body:
React Native App

I am implementing Pull to refresh in my Flatlist prop "onRefresh"

onRefresh called the function "refreshcontrol()" see code below.

I need to change my state "refreshing" to true before I fetch from my API. But it throws the maximum update error.

export default class NotificationScreen extends Component {

  constructor(props) {
   super(props)
   this.state = {
      refreshing: false
    }
  }
.
.
.
.
.
  refreshControl() {
    const { refreshing } = this.state;
    this.setState({ refreshing : true )}.    // throws maximum update error

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={fetchNotifications.bind(this)}      //fetch from API only when refreshing is true
        colors={['#2B70AD']}
      />
    );
  };

}

How else can I set my state to "refreshing :  true" ??? Help please!!!!

This is how it was fixed. Solution:

refresh = async() => {
    this.setState({refreshing : true})
    try {
      const notifications = await fetchNotifications();
      this.setState({
        notifications,
        error: null,
        refreshing: false
      });
    } catch (error) {
      this.setState({
        notifications: [],
        error,
        refreshing: false
      });
    }
  }

  refreshControl() {
    const { refreshing } = this.state;

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={this.refresh}
        colors={['#2B70AD']}
      />
    );
  };