问:
Passing a C# Dictionary as a function parameter to allocate its memory does not work
I have  below code

```<code>using System;
using System.Collections.Generic;
class Program {
    static void add(Dictionary<string,string> hello){
      hello = new Dictionary<string,string>();
      hello["hello"] = "hello";
    }
    static void Main(string[] args) {
      Employee employee = new Employee(); // Employee class

      add(employee.hello);     //  employee.hello is property like public Dictionary<string,string> hello {get;set;}
        Console.WriteLine(hello["hello"]);
    }
}
</code>```

I have also tried using ref but i'm getting A property or indexer may not be passed as ref

When I intialize hello this program  works fine but when i try to intialize it in function it is giving me null reference error. So is there any way to initialize dictionary by passing through a function like that ?

答:
Have you considered passing in the Employee object instead of one of its properties? Something like...</p>
```<code>static void add(Employee emp) {
  emp.hello = new Dictionary<string, string>();
  emp.hello["hello"] = "hello";
}

static void Main(string[] args) {
  Employee employee = new Employee(); // Employee class
  add(employee);
  Console.WriteLine(employee.hello["hello"]);
}
</code>```

Body:
I have  below code

using System;
using System.Collections.Generic;
class Program {
    static void add(Dictionary<string,string> hello){
      hello = new Dictionary<string,string>();
      hello["hello"] = "hello";
    }
    static void Main(string[] args) {
      Employee employee = new Employee(); // Employee class

      add(employee.hello);     //  employee.hello is property like public Dictionary<string,string> hello {get;set;}
        Console.WriteLine(hello["hello"]);
    }
}

I have also tried using ref but i'm getting A property or indexer may not be passed as ref

When I intialize hello this program  works fine but when i try to intialize it in function it is giving me null reference error. So is there any way to initialize dictionary by passing through a function like that ?

Body:
Have you considered passing in the Employee object instead of one of its properties? Something like...

static void add(Employee emp) {
  emp.hello = new Dictionary<string, string>();
  emp.hello["hello"] = "hello";
}

static void Main(string[] args) {
  Employee employee = new Employee(); // Employee class
  add(employee);
  Console.WriteLine(employee.hello["hello"]);
}


来源: stackexchange

问:
how to change the color of select text
how to change the color of the dropdown text that I am given red but initially it look like black when we click that it look like red, so how to change that initially it look like red color

<select>
  <option style="color:red">one</option>
  <option style="color:red">two</option>
</select>```

答:
What i understood is, you want the drop-down texts in red before clicking it.</p>
```<code><Select style="color:red">
    <option>one</option>
    <option>two</option>
</select>
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to change the color of select text

Body:
What i understood is, you want the drop-down texts in red before clicking it.

<Select style="color:red">
    <option>one</option>
    <option>two</option>
</select>


问:
Calculate the table's contentSize.height with custom cells of different types iphone
In my application , the tableview is having different types of custom cells with different heights. I want to put a view below this tableView, for which I need to calculate the table contentView height, how can I do it?

Earlier I used to do it like: (noOfRows * cell_height), but that was for static heights.

Thanx in advance.

答:
UITableView is a subclass of UIScrollView, therefore you can use the instance method contentSize on your tableview:

```<code>yourtableView.contentSize.height
</code>```

Should give you the height of your tableview content view

ContentLicense: CC BY-SA 2.5

Body:
UITableView is a subclass of UIScrollView, therefore you can use the instance method contentSize on your tableview:

yourtableView.contentSize.height

Should give you the height of your tableview content view

ContentLicense: CC BY-SA 3.0


问:
Im stuck on in-completed code on printing variable and list
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be

```<code>Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]
</code>```

basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section

```<code>my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]

print("All Available Genres " + str(my_list))

Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]

variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]

user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
</code>```

答:
This is quite ugly, but I've tried not to change it too much:</p>
```<code>my_list= ["Horror", "Action", "Comedy", "Thriller", "Mystery", "Fantasy", "Sci-fi", "Romance", "Drama", "Dystopian"]

print("All Available Genres " + str(my_list))

movies = {
    "Anabelle": ["Horror", "Triller"],
    "Criminal_Minds": ["Mystery", "Drama"],
    "Avengers": ["Action", "Fantasy", "Sci-fi"],
    "Scooby_doo": ["Comedy", "Horror"],
    "Brooklyn_99": ["Action", "Comedy" ],
    "The_fault_in_our_stars": ["Romance", "Drama"],
    "The_tomorrow_war": ["Drama", "Sci-Fi"],
    "Maze_Runner": ["Drama", "Dystopian", "Thriller"],
    "Hunger_Game": ["Dystopian", "Sci-Fi", "Thriller"],
    "Harry_Potter": ["Mystery", "Fantasy"],
    "Fast_Furious": ["Action"],
    "Conjuring": ["Horror"],
    "Fantastic_Beast": ["Fantasy"],
    "Parasite": ["Comedy", "Thriller"],
    "Space_between_us": ["Romance"],
    "Murder_Mystery": ["Romance", "Mystery"],
    "The_Purge": ["Dystopian", "Thriller"],
    "Spider_Man": ["Action", "Fantasy"],
}

user_genres = (input("What movie/show genre do you like to watch?: "))
user_genres = user_genres.split(", ") if ", " in user_genres else user_genres.split(",")

for (movie, genres) in movies.items():
    toPrint = False
    for genre in genres:
        if genre in user_genres:
            toPrint = True
    if toPrint:
        print(movie + " [" + ", ".join(genres) + "]")
</code>```

Body:
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be

Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]

basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section

my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]

print("All Available Genres " + str(my_list))

Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]

variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]

user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")

Body:
This is quite ugly, but I've tried not to change it too much:

my_list= ["Horror", "Action", "Comedy", "Thriller", "Mystery", "Fantasy", "Sci-fi", "Romance", "Drama", "Dystopian"]

print("All Available Genres " + str(my_list))

movies = {
    "Anabelle": ["Horror", "Triller"],
    "Criminal_Minds": ["Mystery", "Drama"],
    "Avengers": ["Action", "Fantasy", "Sci-fi"],
    "Scooby_doo": ["Comedy", "Horror"],
    "Brooklyn_99": ["Action", "Comedy" ],
    "The_fault_in_our_stars": ["Romance", "Drama"],
    "The_tomorrow_war": ["Drama", "Sci-Fi"],
    "Maze_Runner": ["Drama", "Dystopian", "Thriller"],
    "Hunger_Game": ["Dystopian", "Sci-Fi", "Thriller"],
    "Harry_Potter": ["Mystery", "Fantasy"],
    "Fast_Furious": ["Action"],
    "Conjuring": ["Horror"],
    "Fantastic_Beast": ["Fantasy"],
    "Parasite": ["Comedy", "Thriller"],
    "Space_between_us": ["Romance"],
    "Murder_Mystery": ["Romance", "Mystery"],
    "The_Purge": ["Dystopian", "Thriller"],
    "Spider_Man": ["Action", "Fantasy"],
}

user_genres = (input("What movie/show genre do you like to watch?: "))
user_genres = user_genres.split(", ") if ", " in user_genres else user_genres.split(",")

for (movie, genres) in movies.items():
    toPrint = False
    for genre in genres:
        if genre in user_genres:
            toPrint = True
    if toPrint:
        print(movie + " [" + ", ".join(genres) + "]")


问:
Where to save uploaded images in "asp.net core web api with react" spa template and serve images to client?
I start a project with asp.net core web API with react(spa template) and want to upload Images to server (for example user avatar) and then show images in client app.

There isn't any problem to upload but my question is where to save uploaded images?

There is location of static files in ConfigureServices in startup.cs

```<code>// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/build";
});
</code>```

and in react I know I must use "public" folder for statics files but the problem is in development and debugging with vs 2019 files dynamically adds to "ClientApp/build/public" does not showing in browser and I will get error 404.

Am I must handle static files like .jpg with asp.net core? or there is another option?

I expect to retrieve image by url like this: "https://{sitename}/img/example.jpg"

答:
in startup.cs under configure you should do this :

```<code>app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath,"images")),
    RequestPath = "/img"
});
</code>```

and then in your c# you can access images like this:

```<code> Path.Combine("img","example.jpg")
</code>```

and in client side you can access images like this:

```<code><img src="/img/example.jpg"/>
</code>```

and with url you like this:

```<code>https://{sitename}/img/example.jpg
</code>```

Body:
I start a project with asp.net core web API with react(spa template) and want to upload Images to server (for example user avatar) and then show images in client app.

There isn't any problem to upload but my question is where to save uploaded images?

There is location of static files in ConfigureServices in startup.cs

// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/build";
});

and in react I know I must use "public" folder for statics files but the problem is in development and debugging with vs 2019 files dynamically adds to "ClientApp/build/public" does not showing in browser and I will get error 404.

Am I must handle static files like .jpg with asp.net core? or there is another option?

I expect to retrieve image by url like this: "https://{sitename}/img/example.jpg"

Body:
in startup.cs under configure you should do this :

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath,"images")),
    RequestPath = "/img"
});

and then in your c# you can access images like this:

 Path.Combine("img","example.jpg")

and in client side you can access images like this:

<img src="/img/example.jpg"/>

and with url you like this:

https://{sitename}/img/example.jpg


问:
Shrink Row size when content size decreases
I have a Xamarin Forms page with a grid and an editor within the grid.

My Grid definition is...

```<code>            <Grid Grid.Row="1" x:Name="btmGrid">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>

                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="2*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>

</Grid>

</code>```

When my editor height increases as more text is added it expands as excepted. When text is removed and the editor height decreases, the grid height doesn't decrease - it keeps the max height value it reached while the editor was expanding.

Is there any way to decrease the row height again as the editor height decreases?

答:
I had done a demo to test your code. But the row height will change with the editor height. My code is as following.</p>
```<code> <ContentPage.Content>

    <Grid Grid.Row="1" x:Name="btmGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>

            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="2*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Editor  Grid.Column="0"
             Grid.Row="0"
               Grid.ColumnSpan="2"
                 AutoSize="TextChanges"
             />
        <Editor  Grid.Column="0"
             Grid.Row="1"
               Grid.ColumnSpan="2"
                 AutoSize="TextChanges"
             />
    </Grid>
</ContentPage.Content>
</code>```

Body:
I have a Xamarin Forms page with a grid and an editor within the grid.

My Grid definition is...

            <Grid Grid.Row="1" x:Name="btmGrid">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>

                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="2*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>

</Grid>

When my editor height increases as more text is added it expands as excepted. When text is removed and the editor height decreases, the grid height doesn't decrease - it keeps the max height value it reached while the editor was expanding.

Is there any way to decrease the row height again as the editor height decreases?

Body:
I had done a demo to test your code. But the row height will change with the editor height. My code is as following.

 <ContentPage.Content>

    <Grid Grid.Row="1" x:Name="btmGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>

            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="2*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Editor  Grid.Column="0"
             Grid.Row="0"
               Grid.ColumnSpan="2"
                 AutoSize="TextChanges"
             />
        <Editor  Grid.Column="0"
             Grid.Row="1"
               Grid.ColumnSpan="2"
                 AutoSize="TextChanges"
             />
    </Grid>
</ContentPage.Content>


问:
Swift - Button text color won't change with setTitleColor
I can not seem to get the text in two of my buttons to change to white, unless I manually do it through the storyboard. Any ideas?

class AppUIButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        backgroundColor = Theme.tintColor
        layer.cornerRadius = frame.height / 2
        setTitleColor(UIColor.white, for: .normal)
    }
}

class AddTripViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tripTextField: UITextField!
    @IBOutlet weak var cencelButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!

    var doneSaving: (() -> ())?

    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.font = UIFont(name: Theme.mainFontName, size: 24)

        //I can force the text color to change with the bellow
        //cencelButton.setTitle("Cancel", for: .normal)
        //cencelButton.setTitleColor(UIColor.white, for: .normal)

        //saveButton.setTitle("Add", for: .normal)
        //saveButton.setTitleColor(UIColor.white, for: .normal)

    }

    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true)
    }

    @IBAction func save(_ sender: Any) {
        TripFunctions.createTrip(tripModel: TripModel(title: tripTextField.text!))
        if let doneSaving = doneSaving {
            doneSaving()
        }
        dismiss(animated: true)
    }
}
```

答:
If you want to create a custom class for UIButton you can do something like this

```<code>import UIKit

@IBDesignable
class ThemeButton: UIButton {

    @IBInspectable var borderRadius:CGFloat = 10.0 {
        didSet {
            self.layer.cornerRadius = self.borderRadius
        }
    }

    @IBInspectable var fontSize:CGFloat = 14 {
        didSet {
            self.titleLabel?.font = UIFont.ThemeRegular(ofSize: fontSize)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUI()
        //        self.isSelected = true
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    override func prepareForInterfaceBuilder() {
        setUI()
    }

    private func setUI() {
        DispatchQueue.main.async {
            self.clipsToBounds = true
            self.setTitleColor(.white, for: .normal)
            self.titleLabel?.font = UIFont.ThemeRegular(ofSize: self.fontSize)
            self.backgorundColor = .red
            self.layer.cornerRadius = self.borderRadius
        }
    }
}
</code>```

And you can use it by giving your button class name to the UIButton

Body:
If you want to create a custom class for UIButton you can do something like this

import UIKit

@IBDesignable
class ThemeButton: UIButton {

    @IBInspectable var borderRadius:CGFloat = 10.0 {
        didSet {
            self.layer.cornerRadius = self.borderRadius
        }
    }

    @IBInspectable var fontSize:CGFloat = 14 {
        didSet {
            self.titleLabel?.font = UIFont.ThemeRegular(ofSize: fontSize)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUI()
        //        self.isSelected = true
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    override func prepareForInterfaceBuilder() {
        setUI()
    }

    private func setUI() {
        DispatchQueue.main.async {
            self.clipsToBounds = true
            self.setTitleColor(.white, for: .normal)
            self.titleLabel?.font = UIFont.ThemeRegular(ofSize: self.fontSize)
            self.backgorundColor = .red
            self.layer.cornerRadius = self.borderRadius
        }
    }
}

And you can use it by giving your button class name to the UIButton


问:
How to merge dicts, collecting values from matching keys?
I have multiple dicts (or sequences of key-value pairs) like this:

```<code>d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
</code>```

How can I efficiently get a result like this, as a new dict?

```<code>d = {key1: (x1, x2), key2: (y1, y2)}
</code>```

See also: How can one make a dictionary with duplicate keys in Python?.

答:
Modifying this answer to create a dictionary of tuples (what the OP asked for), instead of a dictionary of lists:

from collections import defaultdict

d1 = {1: 2, 3: 4}
d2 = {1: 6, 3: 7}

dd = defaultdict(tuple)

for d in (d1, d2): # you can list as many input dicts as you want here
    for key, value in d.items():
        dd[key] += (value,)

print(dd)
```
<p>The above prints the following:</p>
```defaultdict(<class 'tuple'>, {1: (2, 6), 3: (4, 7)})
```

Body:
I have multiple dicts (or sequences of key-value pairs) like this:

d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}

How can I efficiently get a result like this, as a new dict?

d = {key1: (x1, x2), key2: (y1, y2)}

See also: How can one make a dictionary with duplicate keys in Python?.

Body:
Modifying this answer to create a dictionary of tuples (what the OP asked for), instead of a dictionary of lists:

from collections import defaultdict

d1 = {1: 2, 3: 4}
d2 = {1: 6, 3: 7}

dd = defaultdict(tuple)

for d in (d1, d2): # you can list as many input dicts as you want here
    for key, value in d.items():
        dd[key] += (value,)

print(dd)

The above prints the following:

defaultdict(<class 'tuple'>, {1: (2, 6), 3: (4, 7)})


问:
java.util.Scanner does not return to Prompt
```<code>import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}
</code>```

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

答:
This is a reply to a comment above. Here, the application will quit when receiving "quit".</p>

```<code>import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String temp = s.next();
            if(temp.trim().equals("quit"))
                System.exit(0);
            System.out.println(s.next());
        }
        s.close();
    }
}
</code>```

Body:
import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

Body:
This is a reply to a comment above. Here, the application will quit when receiving "quit".

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String temp = s.next();
            if(temp.trim().equals("quit"))
                System.exit(0);
            System.out.println(s.next());
        }
        s.close();
    }
}


问:
Is there a standard-compliant way to detect whether a function in the C standard library is implemented via intrinsic/builtin?
Is there a standard-compliant way to detect whether a function in the C standard  library is implemented via intrinsic/builtin?

I'm pretty confident I can implement code which performs better than the function provided by the standard library for a specific call site if only because of function call overhead. But if the function in question is implemented via intrinsic/builtin, there's no function call overhead to beat, so it would be foolish to try.

If there's a way, I have a feeling it won't be simple because it may vary by call site. For example, passing a constant length to memcpy may provide the compiler a great opportunity to generate inline code, but a variable length may provide a lesser opportunity. I guess the best hint available might be one of three values, "always", "never", or "sometimes". That would be good enough for me.

The details of how this might be accomplished are negotiable as long as they're standard-compliant. The version of the standard is even negotiable because that's testable and I'd be happy making the safest assumption if the question weren't answerable for an earlier version of the standard. But of course a way to do this at compile-time would be preferred.

(edited to include concrete details to make it easier to think about even though these details don't matter)

Let's assume memcpy is indeed the function in question and that we know the length is always variable because it was passed in to the function which calls memcpy, but we also know that length is frequently 1.

The overhead of calling into a library will surely dominate both if (1==length) and *dst = *src;. So the questions are how frequently 1 is actually the value, which is a question only I can answer, and whether any possibility the implementation will call into a library can be eliminated.

This question isn't about whether one can write a function which goes faster than memcpy or any other standard library function. There are plenty of questions on that and this isn't one of them.

答: It seems the closest we'll get to a simple YES or NO answer is this comment from Nate Eldredge: "The C standard doesn't even have the concept of 'intrinsic / builtin'".</p>


问:
How can I fetch Google Sheet name from Google sheet ID using python and google sheets API?
I have a code which exports Google sheets into csv and stores it in my local storage. I want to store the csv file with the same name as the google sheet name. Can someone help me out with this ?
So right now, this code saves the csv file as sheet1.csv , how can I make it have the original sheet name ?</p>
```<code>import pandas as pd
from Google import Create_Service

def sheets_to_csv(GOOGLE_SHEET_ID):
    CLIENT_SECRET_FILE = 'secret.json'
    API_SERVICE_NAME = 'sheets'
    API_VERSION = 'v4'
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

    service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME, API_VERSION, SCOPES)

    try:
        gsheets = service.spreadsheets().get(spreadsheetId=GOOGLE_SHEET_ID).execute()
        sheets = gsheets['sheets']

        for sheet in sheets:
            dataset = service.spreadsheets().values().get(
                spreadsheetId=GOOGLE_SHEET_ID,
                range=sheet['properties']['title'],
                majorDimension='ROWS'
            ).execute()
            df = pd.DataFrame(dataset['values'])
            df.columns = df.iloc[0]
            df.drop(df.index[0], inplace=True)
            df.to_csv(sheet['properties']['title'] + '.csv', index=False)
            print()

    except Exception as e:
        print(e)

sheets_to_csv('1LqynjF33-mrO9M5INf4wJvJuY57Hhy4vjv_FjtuM')
</code>```

答:
From your following reply,

each sheet is being exported as the CSV file. But i would like to fetch the name of the overall sheet and name the csv files as Name-sheet1.csv, Name-sheet2.csv and so on..

I understood your goal as follows.

You want to retrieve the Spreadsheet title and use it as the filename of CSV file like Name-sheet1.csv, Name-sheet2.csv.

In your script, how about the following modification?

From:

```<code>df.to_csv(sheet['properties']['title'] + '.csv', index=False)
</code>```

To:

```<code>df.to_csv(gsheets['properties']['title'] + '-' + sheet['properties']['title'] + '.csv', index=False)
</code>```

Reference:

SpreadsheetProperties

Body:
I have a code which exports Google sheets into csv and stores it in my local storage. I want to store the csv file with the same name as the google sheet name. Can someone help me out with this ?
So right now, this code saves the csv file as sheet1.csv , how can I make it have the original sheet name ?

import pandas as pd
from Google import Create_Service

def sheets_to_csv(GOOGLE_SHEET_ID):
    CLIENT_SECRET_FILE = 'secret.json'
    API_SERVICE_NAME = 'sheets'
    API_VERSION = 'v4'
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

    service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME, API_VERSION, SCOPES)

    try:
        gsheets = service.spreadsheets().get(spreadsheetId=GOOGLE_SHEET_ID).execute()
        sheets = gsheets['sheets']

        for sheet in sheets:
            dataset = service.spreadsheets().values().get(
                spreadsheetId=GOOGLE_SHEET_ID,
                range=sheet['properties']['title'],
                majorDimension='ROWS'
            ).execute()
            df = pd.DataFrame(dataset['values'])
            df.columns = df.iloc[0]
            df.drop(df.index[0], inplace=True)
            df.to_csv(sheet['properties']['title'] + '.csv', index=False)
            print()

    except Exception as e:
        print(e)

sheets_to_csv('1LqynjF33-mrO9M5INf4wJvJuY57Hhy4vjv_FjtuM')

Body:
From your following reply,

each sheet is being exported as the CSV file. But i would like to fetch the name of the overall sheet and name the csv files as Name-sheet1.csv, Name-sheet2.csv and so on..

I understood your goal as follows.

You want to retrieve the Spreadsheet title and use it as the filename of CSV file like Name-sheet1.csv, Name-sheet2.csv.

In your script, how about the following modification?

From:

df.to_csv(sheet['properties']['title'] + '.csv', index=False)

To:

df.to_csv(gsheets['properties']['title'] + '-' + sheet['properties']['title'] + '.csv', index=False)

Reference:

SpreadsheetProperties


问:
Mochawesome report is not opening in browser?
I'm doing unit testing using mocha chai. I want to see the reports in browser. Using mochawesome-report I'm able to generate test cases report in a folder mochawesome-report. In that I could see mochawesome.json and mochawesome.html. But unable to open the mochawesome.html file in browser. Kindly help.

Is there any other module to see the report generation in the browser or how can I see the test result in the browser which is displaying in console ?

答: Keep/generate mochawesome.html file in the same folder where you have "assets" folder. assets folder contains the supporting files for the html.</p>


问:
twilio error 'username required'

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());

router.post('/', function(req, res) {
    console.log('this is the req', req.body);
    client.messages.creat({
        to:'+19522209630',
        from:'+17633249718',
        body:'hello World'
    }, function(err, data) {
        if (err) {
            console.log('err', err);
            console.log('data', data);
        }
    });//en d of sendMessage
    res.send(200);
});

module.exports = router;```
<pre class="snippet-code-html lang-html prettyprint-override"><code>/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101
    throw new Error('username is required');
    ^

Error: username is required
    at new Twilio (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101:11)
    at initializer (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/index.js:8:10)
    at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/routes/sendMessage.js:6:31)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/server.js:10:19)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! solo_project@1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the solo_project@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/moisesmiguelhernandez/.npm/_logs/2017-07-11T15_02_02_750Z-debug.log</code>```

I am getting and error that says username is required. I am trying to use twilio. I followed a youtube video and i have it like he does. Any suggestions on how to fix this? P.S The index file is the terminal error message

答: In my case, everything was correct except I was using the account_sid and auth_token of test credential instead of Live credential.</p>

Title: twilio error 'username required'

Body:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());

router.post('/', function(req, res) {
    console.log('this is the req', req.body);
    client.messages.creat({
        to:'+19522209630',
        from:'+17633249718',
        body:'hello World'
    }, function(err, data) {
        if (err) {
            console.log('err', err);
            console.log('data', data);
        }
    });//en d of sendMessage
    res.send(200);
});

module.exports = router;

/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101
    throw new Error('username is required');
    ^

Error: username is required
    at new Twilio (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101:11)
    at initializer (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/index.js:8:10)
    at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/routes/sendMessage.js:6:31)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/server.js:10:19)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! solo_project@1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the solo_project@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/moisesmiguelhernandez/.npm/_logs/2017-07-11T15_02_02_750Z-debug.log

I am getting and error that says username is required. I am trying to use twilio. I followed a youtube video and i have it like he does. Any suggestions on how to fix this? P.S The index file is the terminal error message


问:
Is there a lightweight way to embed a YouTube video in a website?
The base YouTube JS file adds 500Kb to your website, slowing down load time.

(Image source: https://www.labnol.org/internet/light-youtube-embeds/27941/)

How can we speed up page load time, while keeping YouTube videos embedded?

答:
A great solution worth sharing on StackOverflow:

https://www.labnol.org/internet/light-youtube-embeds/27941/


问:
Extracting credentials from ORCID seach with ORCID id using python
I re-edited my question so it's explaining my problem better

I'm trying to get name and last name of a person from ORCID database (db of scientific articles and authors).

I use requests_html and .render() to access url:

"https://orcid.org/orcid-search/search?searchQuery=0000-0001-9077-1041" and get html code out of it. Html is parsed and stored in _text list. (if you access the url yoou'll see that it contains search results of ORCID db by id "0000-0001-9077-1041" - name: "Andreas" and last name: "Leimbach" as well as some additional data).

I want to retrieve name and last name text from the html code of that page. However when I ran the program multiple times, sometimes name and last name are in output results and sometimes they are not. I expect program to allways retrieve the same data.

I use the following  Python script:

```<code>from requests_html import HTMLSession
from bs4 import BeautifulSoup

def GetCredentialsFromORCID(_id):
    base_url = "https://orcid.org/orcid-search/search?searchQuery=" + _id
    session = HTMLSession()
    response = session.get(base_url)
    response.html.render()

    soup = BeautifulSoup(response.html.html, 'lxml')
    _text = soup.get_text().strip().split()
    print("This is whet we got:\n", _text)

GetCredentialsFromORCID("0000-0001-9077-1041")

</code>```

(Try running this code few times (5 - 10+ times) and see for yourself).

I can only assume thet it may have something to do with the fact that this page uses JavaScript cause I keep recieveing:

Please enable JavaScript to continue using this application.

in the console but I don't know much about it.

Can anyone help me with that ?

答:
The webpage actually goes on to run an expanded search following the initial search. You can re-write your code to use that expanded search as the initial call and then you only need requests. You can certainly re-work example below. It is simply structured as your original was in terms of accepting an id and returning a response. Minimal error handling included.</p>
```<code>def GetCredentialsFromORCID(_id):
    import requests

    r = requests.get(f'https://pub.orcid.org/v3.0/expanded-search/?start=0&rows=200&q=orcid:{_id}',
                    headers = {'User-Agent':'Mozilla/5.0', 'accept' : 'application/json'})
    try:
        return r.json()
    except Exception as e:
        return (f'Error for {_id}', e)

print(GetCredentialsFromORCID("0000-0001-9077-1041"))
</code>```

Body:
I re-edited my question so it's explaining my problem better

I'm trying to get name and last name of a person from ORCID database (db of scientific articles and authors).

I use requests_html and .render() to access url:

"https://orcid.org/orcid-search/search?searchQuery=0000-0001-9077-1041" and get html code out of it. Html is parsed and stored in _text list. (if you access the url yoou'll see that it contains search results of ORCID db by id "0000-0001-9077-1041" - name: "Andreas" and last name: "Leimbach" as well as some additional data).

I want to retrieve name and last name text from the html code of that page. However when I ran the program multiple times, sometimes name and last name are in output results and sometimes they are not. I expect program to allways retrieve the same data.

I use the following  Python script:

from requests_html import HTMLSession
from bs4 import BeautifulSoup

def GetCredentialsFromORCID(_id):
    base_url = "https://orcid.org/orcid-search/search?searchQuery=" + _id
    session = HTMLSession()
    response = session.get(base_url)
    response.html.render()

    soup = BeautifulSoup(response.html.html, 'lxml')
    _text = soup.get_text().strip().split()
    print("This is whet we got:\n", _text)

GetCredentialsFromORCID("0000-0001-9077-1041")

(Try running this code few times (5 - 10+ times) and see for yourself).

I can only assume thet it may have something to do with the fact that this page uses JavaScript cause I keep recieveing:

Please enable JavaScript to continue using this application.

in the console but I don't know much about it.

Can anyone help me with that ?

Body:
The webpage actually goes on to run an expanded search following the initial search. You can re-write your code to use that expanded search as the initial call and then you only need requests. You can certainly re-work example below. It is simply structured as your original was in terms of accepting an id and returning a response. Minimal error handling included.

def GetCredentialsFromORCID(_id):
    import requests

    r = requests.get(f'https://pub.orcid.org/v3.0/expanded-search/?start=0&rows=200&q=orcid:{_id}',
                    headers = {'User-Agent':'Mozilla/5.0', 'accept' : 'application/json'})
    try:
        return r.json()
    except Exception as e:
        return (f'Error for {_id}', e)

print(GetCredentialsFromORCID("0000-0001-9077-1041"))


问:
C++ friend operator definition inside class body serves as function declaration?
I'm a newbie reading the C++ Primer book. It says:

A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself.

But I just found that this is not the case for friend operator functions defined inside the class body. In the following code, f could not be found but operator+ is found:

```<code>struct X
{
    friend void f()
    {
        // friend functions can be defined in the class
        // this does NOT serve as a declaration, even though this is already a definition
        // to use this function, another declaration is REQUIRED
    }

    friend X operator+(const X & x1, const X & x2)
    {
        // this stuff serves as declaration somehow
        return {x1.v + x2.v};
    }

    void foo()
    {
        f();                    // ERROR: no declaration for f
        X tmp = X {1} + X {2};  // CORRECT
    }

    int v;
};
</code>```

Could someone tell me what makes this difference?
I am using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, as a reference.
I have searched many questions involving friend declaration and definition on StackOverflow but did not find an answer on this. Sorry if this question is duplicated.

答:
Even if we define the function inside the class, we must still provide a declaration outside of the class itself to make that function visible. A declaration must exist even if we only call the friend from members of the friendship granting class. This means in your example, you should forward declare the function f as shown below:

```<code>//forward declare f
void f();

struct X
{
    //no ADL here since this function f has no parameters of type X. So we also need to declare this outside struct X which we did by providing forward declaration
    friend void f()
    {

    }

    void foo()
    {
        f();                    // WORKS NOW because of the forward declaration
        X tmp = X {1} + X {2};  //operator+ found using ADL
    }
    //other members here
};

</code>```

The output of the program can be seen here.

The reason why the call to operator+ works is because of ADL which stands for argument dependent lookup. In particular, operator+ can be found using ADL since it has parameters of type X. So in this case, you do not need to explicitly declare operator+ outside struct X.

Body:
I'm a newbie reading the C++ Primer book. It says:

A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself.

But I just found that this is not the case for friend operator functions defined inside the class body. In the following code, f could not be found but operator+ is found:

struct X
{
    friend void f()
    {
        // friend functions can be defined in the class
        // this does NOT serve as a declaration, even though this is already a definition
        // to use this function, another declaration is REQUIRED
    }

    friend X operator+(const X & x1, const X & x2)
    {
        // this stuff serves as declaration somehow
        return {x1.v + x2.v};
    }

    void foo()
    {
        f();                    // ERROR: no declaration for f
        X tmp = X {1} + X {2};  // CORRECT
    }

    int v;
};

Could someone tell me what makes this difference?
I am using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, as a reference.
I have searched many questions involving friend declaration and definition on StackOverflow but did not find an answer on this. Sorry if this question is duplicated.

Body:
Even if we define the function inside the class, we must still provide a declaration outside of the class itself to make that function visible. A declaration must exist even if we only call the friend from members of the friendship granting class. This means in your example, you should forward declare the function f as shown below:

//forward declare f
void f();

struct X
{
    //no ADL here since this function f has no parameters of type X. So we also need to declare this outside struct X which we did by providing forward declaration
    friend void f()
    {

    }

    void foo()
    {
        f();                    // WORKS NOW because of the forward declaration
        X tmp = X {1} + X {2};  //operator+ found using ADL
    }
    //other members here
};

The output of the program can be seen here.

The reason why the call to operator+ works is because of ADL which stands for argument dependent lookup. In particular, operator+ can be found using ADL since it has parameters of type X. So in this case, you do not need to explicitly declare operator+ outside struct X.


问:
Proper use of new/delete
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

```<code>void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}
</code>```

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

答:
The destructor of newVar is called and memory allocated by new is returned back to the heap when you call delete.

You shouldn't call delete at this point. Do it in destructor of myclass1 or in another member function.

The best practise is: Store in vector values or smart pointers like boost::shared_ptr<>. Smart pointers are for your case. You can even don't worry about deleting elements of myvector because they'll be destructed correctlly when myvector is destructed.
the example code is:

```<code>void myclass1::myfun()
{
   myvector.push_back(boost::shared_ptr<myclass2>(new myclass2()));
}
</code>```

Title: Proper use of new/delete

Body:
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

Body:
The destructor of newVar is called and memory allocated by new is returned back to the heap when you call delete.

You shouldn't call delete at this point. Do it in destructor of myclass1 or in another member function.

The best practise is: Store in vector values or smart pointers like boost::shared_ptr<>. Smart pointers are for your case. You can even don't worry about deleting elements of myvector because they'll be destructed correctlly when myvector is destructed.
the example code is:

void myclass1::myfun()
{
   myvector.push_back(boost::shared_ptr<myclass2>(new myclass2()));
}


问:
What are differents between drawLine directly and drawLine wrapped in drawIntoCanvas in Jetpack Compose?
I'm learning Jetpack Compose Canvas.

I met the two different Code both Code A and Code B.

Code A invoke drawLine directly, and Code B invoke drawLine which is wrapped in drawIntoCanvas.

1: What are differents between Code A and Code B ?

2: Which one is the better between Code A and Code B ?

Code A

```<code>@Composable
fun setCanvas() {
    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawLine(
            start = Offset(x = 0f, y = canvasHeight),
            end = Offset(x = canvasWidth, y = 0f),
            color = Color.Blue
        )
    }

}
</code>```

Code B

```<code>@Composable
fun setCanvas() {
    val linePaint = Paint()
    linePaint.isAntiAlias = true
    linePaint.style = PaintingStyle.Stroke
    linePaint.color = Color.Blue

    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawIntoCanvas {
            it.drawLine(
               Offset(x = 0f, y = canvasHeight),
               Offset(x = canvasWidth, y = 0f),
               linePaint
            )
        }

    }

}
</code>```

答: Function drawIntoCanvas has access to the underlying Canvas with nativeCanvas (quite helpful if you can to reuse some draw logic you implemented in previous Android apps). Then, you can call all the methods related to the native Canvas like drawText() or drawVertices() for example.</p>

Body:
I'm learning Jetpack Compose Canvas.

I met the two different Code both Code A and Code B.

Code A invoke drawLine directly, and Code B invoke drawLine which is wrapped in drawIntoCanvas.

1: What are differents between Code A and Code B ?

2: Which one is the better between Code A and Code B ?

Code A

@Composable
fun setCanvas() {
    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawLine(
            start = Offset(x = 0f, y = canvasHeight),
            end = Offset(x = canvasWidth, y = 0f),
            color = Color.Blue
        )
    }

}

Code B

@Composable
fun setCanvas() {
    val linePaint = Paint()
    linePaint.isAntiAlias = true
    linePaint.style = PaintingStyle.Stroke
    linePaint.color = Color.Blue

    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawIntoCanvas {
            it.drawLine(
               Offset(x = 0f, y = canvasHeight),
               Offset(x = canvasWidth, y = 0f),
               linePaint
            )
        }

    }

}


问:
Blazor & Custom Certificates
I'm investigating the idea of using Blazor WASM to build a retail application that would run on an office Intranet. The application would be installed on a given machine, to be accessed via browser from any of several machines on the LAN.

The biggest stumbling block I'm running into is the question of how to go about securing the channel.

The app itself would run as a Windows Service, listening on port 443 on one of the workstations, e.g. https://reception/. But how do we tell Blazor to use a self-signed TLS cert for that hostname?

If there's a better way to go about this, I'm all ears. I can't use Let's Encrypt certs, because neither the application nor its hostname will be exposed to the public Internet.

There is a glut of information on working with Blazor to build such an app, but most if not all demos run on localhost. That works fine for dev, but not for production (in a self-hosting scenario, anyway). There doesn't seem to be much discussion at all of this aspect of things.

How can we use a custom certificate for browser requests from the client to a Blazor WASM app?

Any ideas?

答:
The easiest way to handle SSL is to use IIS that will act as a proxy for your Blazor app.

IIS will give you easy access to well documented SSL settings.

https://learn.microsoft.com/en-us/aspnet/core/blazor/host-and-deploy/webassembly?view=aspnetcore-6.0#standalone-deployment

Title: Blazor & Custom Certificates


问:
How to iterate over all tables or DbSet then iterate over all columns in Entity Framework 6 code-first?
I have a problem regarding on how to iterate over all the tables/DbSet in EF6 (not EF Core 6) code first.

I have these DbSet examples:

```<code>public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() : base(AppHelper.ConnectionString())//"name=cn"
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public virtual DbSet<Function> Functions { get; set; }
    public virtual DbSet<Role> Roles { get; set; }
    public virtual DbSet<User> Users { get; set; }
}
</code>```

Then in my Winforms app, I did find some example from Stackoverflow which I revised the below code to loop all the table or Dbset. Please I need your help on how do I call and get the value of columns
using the GetValue() method shown below:

```<code>private void Form_Load(object sender, EventArgs e)
{
    var myEntityModel = new ApplicationDbContext(); //your context
    var dbSets = myEntityModel.GetType().GetProperties().Where(p => p.PropertyType.Name.StartsWith("DbSet")); //get Dbset<T>

    foreach (var dbSetProps in dbSets)
    {
        var dbSet = dbSetProps.GetValue(myEntityModel, null);
        var dbSetType = dbSet.GetType().GetGenericArguments().First();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] properties = dbSetType.GetProperties(flags);

        foreach (PropertyInfo prop in properties)
        {
            var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

            if (type == typeof(DateTime))
            {
                // DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue(, null)); //<-- This is my problem what should i put here
            }
            else
            {
                // Not a DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue( , null));//<-- This is my problem what should i put here
            }
        }
    }
}
</code>```

答:
With this code, you'll get all of tables in DB

```<code>var tableNames = context.Model.GetEntityTypes()
    .Select(t => t.GetTableName())
    .Distinct()
    .ToList();
</code>```

then iterate over the tables and get individual table info

```<code>foreach(var tableName in tableNames  {

    var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
        foreach (var property in tableType.GetProperties())
        {
            var type = property.ClrType;
            var typeName = type.ShortDisplayName();
        }
    }
</code>```

Body:
I have a problem regarding on how to iterate over all the tables/DbSet in EF6 (not EF Core 6) code first.

I have these DbSet examples:

public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() : base(AppHelper.ConnectionString())//"name=cn"
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public virtual DbSet<Function> Functions { get; set; }
    public virtual DbSet<Role> Roles { get; set; }
    public virtual DbSet<User> Users { get; set; }
}

Then in my Winforms app, I did find some example from Stackoverflow which I revised the below code to loop all the table or Dbset. Please I need your help on how do I call and get the value of columns
using the GetValue() method shown below:

private void Form_Load(object sender, EventArgs e)
{
    var myEntityModel = new ApplicationDbContext(); //your context
    var dbSets = myEntityModel.GetType().GetProperties().Where(p => p.PropertyType.Name.StartsWith("DbSet")); //get Dbset<T>

    foreach (var dbSetProps in dbSets)
    {
        var dbSet = dbSetProps.GetValue(myEntityModel, null);
        var dbSetType = dbSet.GetType().GetGenericArguments().First();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] properties = dbSetType.GetProperties(flags);

        foreach (PropertyInfo prop in properties)
        {
            var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

            if (type == typeof(DateTime))
            {
                // DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue(, null)); //<-- This is my problem what should i put here
            }
            else
            {
                // Not a DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue( , null));//<-- This is my problem what should i put here
            }
        }
    }
}

Body:
With this code, you'll get all of tables in DB

var tableNames = context.Model.GetEntityTypes()
    .Select(t => t.GetTableName())
    .Distinct()
    .ToList();

then iterate over the tables and get individual table info

foreach(var tableName in tableNames  {

    var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
        foreach (var property in tableType.GetProperties())
        {
            var type = property.ClrType;
            var typeName = type.ShortDisplayName();
        }
    }


问:
Can I call a functional component inside a custom hook? Is it okay for such a hook to be a .tsx, not .ts files?
I made a custom hook that wraps Chakra's custom hook. Chakra UI is a component library.

```<code>export const useToast = () => {
  const chakraToast = useChakraToast();

  // ...

  const toast = ({ id, title, delay, position = `bottom-right` }: Options) => {
    return chakraToast({
      id,
      position,
      duration: null,
      render: ({ onClose }) => (<Toast title={title} onClose={onClose} />)
    });
  };

  // ...

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

As you can see, I need to tell Chakra to use my Toast component. The question is, is it okay to call a functional component in a custom hook? If so, I need to change the extension of my custom hook file from .ts to .tsx. Is it okay as well?

Thanks!

答:
Given:

```<code>export const useToast = () => {
  const chakraToast = useChakraToast();

  // ...

  const toast = ({ id, title, delay, position = `bottom-right` }: Options) => {
    return chakraToast({
      id,
      position,
      duration: null,
      render: ({ onClose }) => (<Toast title={title} onClose={onClose} />)
    });
  };

  // ...

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

The question is, is it okay to call a functional component in a custom
hook?

It seems you are specifically referring to the render function. As such, it seems a perfectly valid use of a render function that returns JSX. From what I can tell, your question about function components is irrelevant. You are defining a function that returns JSX.

See Custom Component

If so, I need to change the extension of my custom hook file from *.ts
to *.tsx. Is it okay as well?

I see no issue here. *.jsx and *.tsx (vs *.js and *.ts) only indicate that JSX syntax is used in the file. The Rules of Hooks make no rules governing the files they can be declared in, but rather only how they are used.

Body:
I made a custom hook that wraps Chakra's custom hook. Chakra UI is a component library.

export const useToast = () => {
  const chakraToast = useChakraToast();

  // ...

  const toast = ({ id, title, delay, position = `bottom-right` }: Options) => {
    return chakraToast({
      id,
      position,
      duration: null,
      render: ({ onClose }) => (<Toast title={title} onClose={onClose} />)
    });
  };

  // ...

  return toast;
};

As you can see, I need to tell Chakra to use my Toast component. The question is, is it okay to call a functional component in a custom hook? If so, I need to change the extension of my custom hook file from .ts to .tsx. Is it okay as well?

Thanks!

Body:
Given:

export const useToast = () => {
  const chakraToast = useChakraToast();

  // ...

  const toast = ({ id, title, delay, position = `bottom-right` }: Options) => {
    return chakraToast({
      id,
      position,
      duration: null,
      render: ({ onClose }) => (<Toast title={title} onClose={onClose} />)
    });
  };

  // ...

  return toast;
};

The question is, is it okay to call a functional component in a custom
hook?

It seems you are specifically referring to the render function. As such, it seems a perfectly valid use of a render function that returns JSX. From what I can tell, your question about function components is irrelevant. You are defining a function that returns JSX.

See Custom Component

If so, I need to change the extension of my custom hook file from *.ts
to *.tsx. Is it okay as well?

I see no issue here. *.jsx and *.tsx (vs *.js and *.ts) only indicate that JSX syntax is used in the file. The Rules of Hooks make no rules governing the files they can be declared in, but rather only how they are used.


问:
Getting number of queries in a MongoDB collection in NodeJS
New to MongoDb, I am working on a small phonebook application where the user can add and remove phonebook entries using a name and phone number. I am able to successfully add and delete entries and have the database updated successfully, but not sure how to get the number of total entries/queries in a specific MongoDB collection.

MongoDB module:

```<code>const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)

mongoose.connect(url)
.then(result => {
    console.log('connected to MongoDB')
  })
.catch((error) => {
    console.log('error connecting to MongoDB:', error.message)
})

const personSchema = new mongoose.Schema({
    name: String,
    number: String,
}, { collection: 'phonebook' })

personSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Person', personSchema)
</code>```

On my MongoDB cluster, the name of my DB is 'myFirstDatabase' and the collection name is 'phonebook'

Current DB looks like this:

On index.js:

```<code>app.get('/info', (request, response) => {
    const date = new Date();
    const numPersons = Person.countDocuments()
    //Should be 2
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})
</code>```

答:
countDocuments is asynchronous

Try with async await and add an empty {} inside countDocuments

```<code>app.get('/info', async(request, response) => {
    const date = new Date();
    const numPersons = await Person.countDocuments({})
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})
</code>```

Body:
New to MongoDb, I am working on a small phonebook application where the user can add and remove phonebook entries using a name and phone number. I am able to successfully add and delete entries and have the database updated successfully, but not sure how to get the number of total entries/queries in a specific MongoDB collection.

MongoDB module:

const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)

mongoose.connect(url)
.then(result => {
    console.log('connected to MongoDB')
  })
.catch((error) => {
    console.log('error connecting to MongoDB:', error.message)
})

const personSchema = new mongoose.Schema({
    name: String,
    number: String,
}, { collection: 'phonebook' })

personSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Person', personSchema)

On my MongoDB cluster, the name of my DB is 'myFirstDatabase' and the collection name is 'phonebook'

Current DB looks like this:

On index.js:

app.get('/info', (request, response) => {
    const date = new Date();
    const numPersons = Person.countDocuments()
    //Should be 2
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})

Body:
countDocuments is asynchronous

Try with async await and add an empty {} inside countDocuments

app.get('/info', async(request, response) => {
    const date = new Date();
    const numPersons = await Person.countDocuments({})
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})


问:
How to align elements in three columns, even when resizing
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

```<code><section class="sub-offer">
      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>
    </section>
</code>```

CSS:

```<code>.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}
</code>```

How they look now:

答:
I'm not really a good dev, but I can give it a try. What I do when I want to make things line up perfectly is use grid, so I tried adding it to .offer-container like this .offer-container {display: grid; grid-template-rows: 1fr 1fr 1fr;}. A working example is below. Though, since I'm new to helping people on StackOverflow or really StackOverflow in general, I'm sure I didn't do something right. for example, providing a solution to a different problem or fixing issues that you didn't as for. If you need a list of what I changed, you can see that here: added } for sub-offer removed extra closing bracket on a{} separated &:hover to a:hover{} made
 text white. I hope this is the solution you were looking for if your problem hasn't already been fixed.

.sub-offer {
    text-align: center;
    display: flex;
    position: relative;
    width:100px
}

.offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
    display: grid;
    grid-template-rows: 1fr 1fr 1fr;
}

h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
}

p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
    color: white;
}

a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;
}

a:hover {
    background: #e5e5e5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="sub-offer">
  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
        rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
        quis!
      </p>
    </div>
    <div class="more-btn">
      Lorem, ipsum.
    </div>
  </div>

  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
        perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
        incidunt odio?
      </p>
    </div>
    <div class="more-btn">
      Lorem, ipsum.
    </div>
  </div>

  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
        vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
        ullam quod porro atque error?
      </p>
    </div>
    <div class="more-btn">
      Lorem, ipsum.
    </div>
  </div>
</section></code>```

Body:
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?

          Lorem, ipsum.

CSS:

.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}

How they look now:

Body:
I'm not really a good dev, but I can give it a try. What I do when I want to make things line up perfectly is use grid, so I tried adding it to .offer-container like this .offer-container {display: grid; grid-template-rows: 1fr 1fr 1fr;}. A working example is below. Though, since I'm new to helping people on StackOverflow or really StackOverflow in general, I'm sure I didn't do something right. for example, providing a solution to a different problem or fixing issues that you didn't as for. If you need a list of what I changed, you can see that here: added } for sub-offer removed extra closing bracket on a{} separated &:hover to a:hover{} made <p> text white. I hope this is the solution you were looking for if your problem hasn't already been fixed.

.sub-offer {
    text-align: center;
    display: flex;
    position: relative;
    width:100px
}

.offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
    display: grid;
    grid-template-rows: 1fr 1fr 1fr;
}

h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
}

p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
    color: white;
}

a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;
}

a:hover {
    background: #e5e5e5;
}

<section class="sub-offer">
  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
        rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
        quis!
      </p>
    </div>
    <div class="more-btn">
      <a href="#">Lorem, ipsum.</a>
    </div>
  </div>

  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
        perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
        incidunt odio?
      </p>
    </div>
    <div class="more-btn">
      <a href="#">Lorem, ipsum.</a>
    </div>
  </div>

  <div class="offer-container">
    <div class="offer-up">
      <h2>Lorem, ipsum.</h2>
      <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
    </div>
    <div class="offer-down">
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
        vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
        ullam quod porro atque error?
      </p>
    </div>
    <div class="more-btn">
      <a href="#">Lorem, ipsum.</a>
    </div>
  </div>
</section>


问:
How to inflate options menu from ponTouchEvent(MotionEvent me) in View
I have my menu which is called by clicking the button on android tablet. But I need to inflate the same menu by a click on view.

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    return true;
}
</code>```

Any suggestions?

答:
I called

```<code>mainActivity.openOptionsMenu();
</code>```

from View. It worked!. the one Phil suggested creates a different menu. Not an option menu.
any way thankx

Body:
I have my menu which is called by clicking the button on android tablet. But I need to inflate the same menu by a click on view.

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    return true;
}

Any suggestions?

Body:
I called

mainActivity.openOptionsMenu();

from View. It worked!. the one Phil suggested creates a different menu. Not an option menu.
any way thankx


问:
Could not assemble transaction, err proposal response was not successful, error code 500, msg chaincode registration failed: container exited with 0
I'm trying to instantiate the chaincode, but an error happens, and I can not find solutions to it.

ubuntu 18.04

hyperledger fabric 1.4.1

I've followed the document and it succeeded last week. The same code works well on another computer.

Before instantiate, everything went on well including making channels.
I have not applied node in my project.

Codes:

```<code>root@c442cc2748e7:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode instantiate -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -l golang -v 1.0 -c '{"Args":[]}' -P "AND ('Org1MSP.peer','Org2MSP.peer')"
2019-05-23 06:31:31.382 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2019-05-23 06:31:31.382 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
Error: could not assemble transaction, err proposal response was not successful, error code 500, msg chaincode registration failed: container exited with 0
</code>```

答:
Solution

Remove the dev-* containers and try again.

```<code>docker images
...
dev-peer0.org1.example.com-fabcar-1.0-93f09...
...

docker rmi $(docker images dev-* -q)
</code>```

Explanation

The lscc creates a docker image for the chaincode. Once this image exists, it will reuse it in the future. If the image is bad, you have to delete it, before attempting the instantiation again. I believe this is why so many of the "rename" solutions work, it causes a new image to be created (with a different name), since the name and version of the docker image name.

Troubleshooting

In order to determine why the chaincode failed to start, you can connect to the cli container and attempt to manually run the chaincode. For example, a nodejs chaincode might look something like this:

```<code>docker exec -it cli /bin/bash
#$ cd chaincode
#$ npm start
# <some npm error here>
</code>```

Another option is to turn up logging on the peer and try again. Peer logging can be turned up via the FABRIC_LOGGING_SPEC environment variable. I would set to debug or info and then try again. Logs can be checked via

```<code>docker logs peer0.org1.example.com
</code>```

At the end of the day, the error means that lscc chaincode failed to launch your chaincode.

Body:
I'm trying to instantiate the chaincode, but an error happens, and I can not find solutions to it.

ubuntu 18.04

hyperledger fabric 1.4.1

I've followed the document and it succeeded last week. The same code works well on another computer.

Before instantiate, everything went on well including making channels.
I have not applied node in my project.

Codes:

root@c442cc2748e7:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode instantiate -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n mycc -l golang -v 1.0 -c '{"Args":[]}' -P "AND ('Org1MSP.peer','Org2MSP.peer')"
2019-05-23 06:31:31.382 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2019-05-23 06:31:31.382 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
Error: could not assemble transaction, err proposal response was not successful, error code 500, msg chaincode registration failed: container exited with 0

Body:
Solution

Remove the dev-* containers and try again.

docker images
...
dev-peer0.org1.example.com-fabcar-1.0-93f09...
...

docker rmi $(docker images dev-* -q)

Explanation

The lscc creates a docker image for the chaincode. Once this image exists, it will reuse it in the future. If the image is bad, you have to delete it, before attempting the instantiation again. I believe this is why so many of the "rename" solutions work, it causes a new image to be created (with a different name), since the name and version of the docker image name.

Troubleshooting

In order to determine why the chaincode failed to start, you can connect to the cli container and attempt to manually run the chaincode. For example, a nodejs chaincode might look something like this:

docker exec -it cli /bin/bash
#$ cd chaincode
#$ npm start
# <some npm error here>

Another option is to turn up logging on the peer and try again. Peer logging can be turned up via the FABRIC_LOGGING_SPEC environment variable. I would set to debug or info and then try again. Logs can be checked via

docker logs peer0.org1.example.com

At the end of the day, the error means that lscc chaincode failed to launch your chaincode.


问:
How to set DynamicResource value in Setter object in code?
XAML example:

```<code>    <Style x:Key="MyStyle" TargetType="VisualElement">
        <Setter Property="BackgroundColor" Value="{DynamicResource PrimaryColor}" />
    </Style>
</code>```

How to do it in code?

```<code>    Style MyStyle = new Style(typeof(VisualElement))
    {
        Setters =
        {
            new Setter
            {
                Property = BackgroundColorProperty,
                Value = ???
              //Valye = new DynamicResourceExtension { Key = "PrimaryColor" } !!! not working
            }
        }
     }
</code>```

答:
This could be achieved by Dynamic style inheritance.

Deriving a style from a dynamic style can't be achieved using the Style.BasedOn property. Instead, the Style class includes the BaseResourceKey property, which can be set to a dictionary key whose value might dynamically change.

```<code>var tealSearchBarStyle = new Style (typeof(SearchBar)) {
    BaseResourceKey = "searchBarStyle",
            ...
};
</code>```

Body:
XAML example:

How to do it in code?

    Style MyStyle = new Style(typeof(VisualElement))
    {
        Setters =
        {
            new Setter
            {
                Property = BackgroundColorProperty,
                Value = ???
              //Valye = new DynamicResourceExtension { Key = "PrimaryColor" } !!! not working
            }
        }
     }

Body:
This could be achieved by Dynamic style inheritance.

Deriving a style from a dynamic style can't be achieved using the Style.BasedOn property. Instead, the Style class includes the BaseResourceKey property, which can be set to a dictionary key whose value might dynamically change.

var tealSearchBarStyle = new Style (typeof(SearchBar)) {
    BaseResourceKey = "searchBarStyle",
            ...
};


问:
Automatically hard wrap lines at column in VSCode
How can I automatically hard wrap lines in VSCode? By that I mean if a line reaches a specified column, automatically insert a newline at the word boundary closest to that column without going over. Vim has a setting called textwidth that does this that I like to use when editing Markdown. It doesn't seem like VSCode does, as far as I can tell. It just has ways to control softwrapping.</p>

答:
You can easily set the column limit using ColumnLimit member in C_Cpp.clang_format_fallbackStyle in settings.json (You have to install Microsoft C/C++ extension)

```<code>"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: WebKit, IndentWidth: 4, ColumnLimit: 80 }",
</code>```

Then you can format the file using Shift + Alt + F

There are many options you can change in this format feature

```<code>"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: WebKit, UseTab: Never, IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Attach, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false, ColumnLimit: 80, AccessModifierOffset: -4 }",
</code>```

Name of the predefined style used as a fallback in case clang-format
is invoked with style file but the .clang-format file is not found.
Possible values are Visual Studio, LLVM, Google, Chromium, Mozilla,
WebKit, Microsoft, GNU, none, or use {key: value, ...} to set specific
parameters. For example, the Visual Studio style is similar to: {
BasedOnStyle: LLVM, UseTab: Never, IndentWidth: 4, TabWidth: 4,
BreakBeforeBraces: Allman, AllowShortIfStatementsOnASingleLine: false,
IndentCaseLabels: false, ColumnLimit: 0, AccessModifierOffset: -4,
NamespaceIndentation: All, FixNamespaceComments: false }

Before

```<code>void Proc::Memory::getSramOff(const char* mem_name, uint dataSize, uint addrBits, uint& noOfBytes, uint& sram_off)
</code>```

After

```<code>void Proc::Memory::getSramOff(const char* mem_name, uint dataSize,
    uint addrBits, uint& noOfBytes, uint& sram_off)
</code>```

Body:
You can easily set the column limit using ColumnLimit member in C_Cpp.clang_format_fallbackStyle in settings.json (You have to install Microsoft C/C++ extension)

"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: WebKit, IndentWidth: 4, ColumnLimit: 80 }",

Then you can format the file using Shift + Alt + F

There are many options you can change in this format feature

"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: WebKit, UseTab: Never, IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Attach, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false, ColumnLimit: 80, AccessModifierOffset: -4 }",

Name of the predefined style used as a fallback in case clang-format
is invoked with style file but the .clang-format file is not found.
Possible values are Visual Studio, LLVM, Google, Chromium, Mozilla,
WebKit, Microsoft, GNU, none, or use {key: value, ...} to set specific
parameters. For example, the Visual Studio style is similar to: {
BasedOnStyle: LLVM, UseTab: Never, IndentWidth: 4, TabWidth: 4,
BreakBeforeBraces: Allman, AllowShortIfStatementsOnASingleLine: false,
IndentCaseLabels: false, ColumnLimit: 0, AccessModifierOffset: -4,
NamespaceIndentation: All, FixNamespaceComments: false }

Before

void Proc::Memory::getSramOff(const char* mem_name, uint dataSize, uint addrBits, uint& noOfBytes, uint& sram_off)

After

void Proc::Memory::getSramOff(const char* mem_name, uint dataSize,
    uint addrBits, uint& noOfBytes, uint& sram_off)


问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答:
The Guava libraries come with a method

```<code>"SetView com.google.common.collect.Sets.intersection(Set a, Set b)
</code>```

that will give the elements contained in both sets, but not the indexes. Although it should be easy to get the indexes afterwards.

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

Body:
The Guava libraries come with a method

"SetView com.google.common.collect.Sets.intersection(Set a, Set b)

that will give the elements contained in both sets, but not the indexes. Although it should be easy to get the indexes afterwards.


问:
WSO2 5.11 Console trying to reach localhost instead server
I have WSO2 IS 5.11 installed on a server under https://server1.wso2.com.
When Im trying to reach new console app Im getting redirected to:

```<code>https://localhost:9443/oauth2/token/.well-known/openid-configuration
</code>```

and then to authorize endpoint:

```<code>https://localhost:9443/oauth2/authorize?response_type=code&client_id=CONSOLE&scope=SYSTEM%20openid&redirect_uri=https://server1.wso2.com/console/login&response_mode=query&code_challenge_method=S256&code_challenge=sa3xryaGoX1IoyxZJfoIrE3tAJPUjep30j6izcDtOtc
</code>```

Why Im getting redirected to localhost:9443? I checked my configuration and there is no localhost in resident IdP.

答:
This can happen due to the server configurations set on WSO2IS, to change that go to <IS-HOME>/repository/conf directory and open deployment.toml configuration file and change the

```<code>[server]
hostname = "https://server1.wso2.com"
</code>```

Also, you can check load balancer configurations/ port mapping and opening ports from the server configurations from the server that you use.

Body:
I have WSO2 IS 5.11 installed on a server under https://server1.wso2.com.
When Im trying to reach new console app Im getting redirected to:

https://localhost:9443/oauth2/token/.well-known/openid-configuration

and then to authorize endpoint:

https://localhost:9443/oauth2/authorize?response_type=code&client_id=CONSOLE&scope=SYSTEM%20openid&redirect_uri=https://server1.wso2.com/console/login&response_mode=query&code_challenge_method=S256&code_challenge=sa3xryaGoX1IoyxZJfoIrE3tAJPUjep30j6izcDtOtc

Why Im getting redirected to localhost:9443? I checked my configuration and there is no localhost in resident IdP.

Body:
This can happen due to the server configurations set on WSO2IS, to change that go to <IS-HOME>/repository/conf directory and open deployment.toml configuration file and change the

[server]
hostname = "https://server1.wso2.com"

Also, you can check load balancer configurations/ port mapping and opening ports from the server configurations from the server that you use.