问:
Type guard on conditional parameter type
Why is this code not working ?

Typescript could easily guess that a variable of type (T extends '1' ? '1' : never) will never be false, so that NonFalse<TypeWithCondition<T>> is exactly the same than true | (T extends '1' ? '1' : never).

Is it a Typescript bug ? Should it be posted as a Feature Request ?

```<code>type TypeWithCondition<T> = boolean | (T extends '1' ? '1' : never);

type NonFalse<T> = Exclude<T, false>;

const logNonFalse = <T>(b: NonFalse<TypeWithCondition<T>>) => {
    console.log(b);
};

const test1 = <T>(a: TypeWithCondition<T>) => {
    if (a === false) throw new Error("Can't be false");
    logNonFalse(a);
    // Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
    //  Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
    //    Type '"1"' is not assignable to type 'true'.(2345)
};
</code>```

答: Typescript is not yet able to handle that. Cf https://github.com/microsoft/TypeScript/issues/38863</p>

Body:
Why is this code not working ?

Typescript could easily guess that a variable of type (T extends '1' ? '1' : never) will never be false, so that NonFalse<TypeWithCondition<T>> is exactly the same than true | (T extends '1' ? '1' : never).

Is it a Typescript bug ? Should it be posted as a Feature Request ?

type TypeWithCondition<T> = boolean | (T extends '1' ? '1' : never);

type NonFalse<T> = Exclude<T, false>;

const logNonFalse = <T>(b: NonFalse<TypeWithCondition<T>>) => {
    console.log(b);
};

const test1 = <T>(a: TypeWithCondition<T>) => {
    if (a === false) throw new Error("Can't be false");
    logNonFalse(a);
    // Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
    //  Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
    //    Type '"1"' is not assignable to type 'true'.(2345)
};


来源: stackexchange

问:
does a inout port work as both in and out in same appplication
I am trying to write a vhdl code including inout port and have this doubt that wheather a inout port act as both input and output in same program.Like i know reason to use inout pin is so that it works both ways,but my doubt is if you consider practical example like in microcontroller i see the pin act as input for one program or application and as output in another.Can the pin work ask both in and out in same program ?is that possible?(like in 1 clock cycle its in and in other another its out)
practically it seems like it cant happen.But can someone help with an answer</p>

答:
In your toplevel entity, the following code would allow you to both drive and sample a (bidirectional) port named bidir_port:

...

    bidir_port : inout std_logic;

...

signal bidir_port_output_level : std_logic;
signal bidir_port_output_enable : std_logic;
signal bidir_port_input_level : std_logic;

...

    -- output buffer with enable
    bidir_port <= bidir_port_output_level when bidir_port_output_enable = '1' else 'Z';
    -- input buffer
    bidir_port_input_level <= bidir_port;
```

Output: In order to drive the pin, bidir_port_output_enable has to be '1' at which point the output driver will turn on and drive the pin with the value of bidir_port_output_level ('0' or '1' in physical digital systems).  If bidir_port_output_enable is '0', the driver is disabled (turned off) at which point the value of bidir_port_output_level is irrelevant.

Input: You can always sense the pin (even when you're driving it) as shown with the assignment to signal bidir_port_input_level.

ContentLicense: CC BY-SA 4.0

Body:
In your toplevel entity, the following code would allow you to both drive and sample a (bidirectional) port named bidir_port:

...

    bidir_port : inout std_logic;

...

signal bidir_port_output_level : std_logic;
signal bidir_port_output_enable : std_logic;
signal bidir_port_input_level : std_logic;

...

    -- output buffer with enable
    bidir_port <= bidir_port_output_level when bidir_port_output_enable = '1' else 'Z';
    -- input buffer
    bidir_port_input_level <= bidir_port;

Output: In order to drive the pin, bidir_port_output_enable has to be '1' at which point the output driver will turn on and drive the pin with the value of bidir_port_output_level ('0' or '1' in physical digital systems).  If bidir_port_output_enable is '0', the driver is disabled (turned off) at which point the value of bidir_port_output_level is irrelevant.

Input: You can always sense the pin (even when you're driving it) as shown with the assignment to signal bidir_port_input_level.


问:
How to put a generic function type into std::map?
Can I use a generic function type as the value of std::map? This eliminates the need to write different std::maps for different function parameters and return values.</p>

```<code>template<class Function,class ... Args>
inline auto FuncWrapper(Function &&f, Args && ... args)-> decltype(f(std::forward<Args>(args)...))
{
    return f(std::forward<Args>(args)...);
}

std::map<std::string, FuncWrapper>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"]([](std::string data){ return "MD5: "+ data; }, "some data");
    FUNCS["RSA"]([](std::string data, std::string key) {return "RSA: "+ data +':' + key;}, "some data", "some key");
    FUNCS["Other"]([](int a, double b, char c){return (c-'0')+a+b;}, 1, 2.0, 'c');
}
</code>```

答:
A possibility could be to have a tagged union (but a known one) of closures (or function objects).

So combine std::function with std::variant and std::map.

For example, consider having some

```<code>std::map<std::string,
       std::variant<std::function(void(int)>,
                    std::function(double(std::string))>> mapunion;
</code>```

Your tagged union might  contain smart  pointers, e.g. some std::unique_ptr

Body:
Can I use a generic function type as the value of std::map? This eliminates the need to write different std::maps for different function parameters and return values.

template<class Function,class ... Args>
inline auto FuncWrapper(Function &&f, Args && ... args)-> decltype(f(std::forward<Args>(args)...))
{
    return f(std::forward<Args>(args)...);
}

std::map<std::string, FuncWrapper>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"]([](std::string data){ return "MD5: "+ data; }, "some data");
    FUNCS["RSA"]([](std::string data, std::string key) {return "RSA: "+ data +':' + key;}, "some data", "some key");
    FUNCS["Other"]([](int a, double b, char c){return (c-'0')+a+b;}, 1, 2.0, 'c');
}

Body:
A possibility could be to have a tagged union (but a known one) of closures (or function objects).

So combine std::function with std::variant and std::map.

For example, consider having some

std::map<std::string,
       std::variant<std::function(void(int)>,
                    std::function(double(std::string))>> mapunion;

Your tagged union might  contain smart  pointers, e.g. some std::unique_ptr


问:
how would i set up an h2 for a kubernetes cluster?
H2 is an open-source lightweight Java database.
Basically I am trying to build a DevOps pipeline but for the Kubernetes part I need to hook up the h2 database locally to the pod and not using  aws rds for anything like that.  Any ideas on how to configure this?</p>

答:
It’s a little unclear when you say you need to hook up H2 locally in each pod whether you mean 1 H2 overall or 1 per pod.  I’m assuming you need a server H2 and not an embedded one.

If your requirement is to have all your pods talking to the same H2 instance, you can create a container that runs H2 in server mode and run it in a Deployment.  You would also need a Service to expose the database port within the cluster.  See https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#accessing-the-service for some details.

You’d probably also want to run H2 with a file backing the database, unless you can recreate the contents of the database by some other magic when its pod restarts.  For that file to be persistent across H2 restarts, you would need to provision a persistent volume and persistent volume binding.  Details for PVs are Kubernetes platform specific.  https://kubernetes.io/docs/concepts/storage/persistent-volumes/

If you don’t need a single H2, but rather one in each pod, you could run an H2 container in each pod beside your other other container(s). Or you could fork an H2 server in a Deployment’s main container command, if you don’t want to use H2 in a container. (Ugly, though and not really the Kubernetes way.) You would not need a Service in this case, as you’d connect to H2 locally in the Pod.  But you’d have a real nightmare I’d think managing persistent volumes to hold the database for each Pod’s H2, assuming you need persistent storage.

Ultimately, you may decide that RDS is easier...


问:
Update components element from a different component
Im trying to change the classes of an element inside one of my components from a page, but the classes never change. I put a Console.Writeline inside the function, and the function is definitley running.

The CircleClass variable by default is set to "danger", and that works properly, the div starts off with the danger class. The console.writeline confirms that the variable is being changed, it just isn't updating the element.

Code in component:

```<code><div class="circle @CircleClass"></div>

@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");
    }
}
</code>```

First Attempt

```<code>@page "/"

@Inject Nav nav

<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>
</code>```

In Startup.cs I added this:

```<code>services.AddSingleton<Nav>();
</code>```

Second Attempt

```<code>@page "/"

<button @onclick="@(e => ChangeStatus(2))">Two</button>

private void ChangeStatus(int status)
{
    Nav nav = new Nav();
    nav.ChangeStatus(status);
}
</code>```

I think it may have something to do with it creating a new instance of the class which isn't able to change the classes of the elements I need changing, although I believe that should be solved when using AddSingleton.

Anyone know what could be causing this issue?

Calling the function inside of the component confirms that the function actually works.

Component:

```<code>protected override void OnInitialized()
{
    ChangeStatus(1);
}
</code>```

What I am trying:

Nav.razor

```<code><li id="status">
    <div class="circle @CircleClass"></div>
</li>

@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
            default:
                CircleClass = "idle";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");

        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }
}
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();

    services.AddSingleton<Nav>();
}
</code>```

Index.razor

```<code>@page "/"

@inject Nav nav

<button @onclick="@(e => nav.ChangeStatus(0))">Zero</button>
<button @onclick="@(e => nav.ChangeStatus(1))">One</button>
<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>
</code>```

In my code examples above, I am using buttons to try to run functions in the nav component from a page, but eventually I am going to run these functions from different places that wont be pages without direct user input.

The Nav component is defined/created in my MainLayout, it isn't directly applied to the Index page.

答:
You can do something like this. I think you don't need Nav service. You can call and change class value from page itself.

Inside index page

HTML

```<code><Nav @ref="navComp"></Nav>

<button @onclick="@(e => navComp.ChangeStatus(0))">Zero</button>
<button @onclick="@(e => navComp.ChangeStatus(1))">One</button>
<button @onclick="@(e => navComp.ChangeStatus(2))">Two</button>
</code>```

C# Code

```<code>@code {
Nav navComp;

    //other code
}
</code>```

Inside Nav component

HTML

```<code><h3>Nav</h3>
<li id="status">
    <div class="circle @CircleClass"></div>
</li>
</code>```

C# Code

```<code>@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
            default:
                CircleClass = "idle";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");

        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }
}
</code>```

you can see the output right here..

Body:
Im trying to change the classes of an element inside one of my components from a page, but the classes never change. I put a Console.Writeline inside the function, and the function is definitley running.

The CircleClass variable by default is set to "danger", and that works properly, the div starts off with the danger class. The console.writeline confirms that the variable is being changed, it just isn't updating the element.

Code in component:

@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");
    }
}

First Attempt

@page "/"

@Inject Nav nav

<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>

In Startup.cs I added this:

services.AddSingleton();

Second Attempt

@page "/"

<button @onclick="@(e => ChangeStatus(2))">Two</button>

private void ChangeStatus(int status)
{
    Nav nav = new Nav();
    nav.ChangeStatus(status);
}

I think it may have something to do with it creating a new instance of the class which isn't able to change the classes of the elements I need changing, although I believe that should be solved when using AddSingleton.

Anyone know what could be causing this issue?

Calling the function inside of the component confirms that the function actually works.

Component:

protected override void OnInitialized()
{
    ChangeStatus(1);
}

What I am trying:

Nav.razor

@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
            default:
                CircleClass = "idle";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");

        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();

    services.AddSingleton();
}

Index.razor

@page "/"

@inject Nav nav

<button @onclick="@(e => nav.ChangeStatus(0))">Zero</button>
<button @onclick="@(e => nav.ChangeStatus(1))">One</button>
<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>

In my code examples above, I am using buttons to try to run functions in the nav component from a page, but eventually I am going to run these functions from different places that wont be pages without direct user input.

The Nav component is defined/created in my MainLayout, it isn't directly applied to the Index page.

Body:
You can do something like this. I think you don't need Nav service. You can call and change class value from page itself.

Inside index page

HTML

<Nav @ref="navComp"></Nav>

<button @onclick="@(e => navComp.ChangeStatus(0))">Zero</button>
<button @onclick="@(e => navComp.ChangeStatus(1))">One</button>
<button @onclick="@(e => navComp.ChangeStatus(2))">Two</button>

C# Code

@code {
Nav navComp;

    //other code
}

Inside Nav component

HTML

<h3>Nav</h3>
<li id="status">
    <div class="circle @CircleClass"></div>
</li>

C# Code

@code {
    private string CircleClass = "danger";

    public void ChangeStatus(int status)
    {
        switch (status)
        {
            case 0:
                CircleClass = "idle";
                break;
            case 1:
                CircleClass = "safety";
                break;
            case 2:
                CircleClass = "danger";
                break;
            default:
                CircleClass = "idle";
                break;
        }

        Console.WriteLine($"{status} Circle: {CircleClass}");

        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }
}

you can see the output right here..


问:
Is it possible to add custom DNS entries to the Service Fabric DNS service
Service Fabric has its own built in DNS service that will automatically resolve service names to one of the IPs in the cluster running that service.  However, is it possible to add manual entries to this DNS server that do not map to a Service Fabric service?  For example, if I wanted rediscache.cluster to resolve to 10.0.100.4, is that possible?

The alternative would be to make this a public DNS entry, however we'd rather hide our internal network addresses from the public.  Thanks!

答:
I don't think you can add custom records to the DNS service.

As alternatives:

you could consider to use a containerized Redis and deploy that in your cluster. This way it will be accessible through the DNS Service.

e.g. sfctl compose create --deployment-name MyRedisApp --file-path docker-compose.yml

you can run a reverse proxy service that forwards traffic to the real Redis server in the network

e.g. sfctl service create --app-id MyRedisProxyApp --name fabric:/MyRedisProxyApp/MyRedisProxy --service-type MyRedisProxyType --stateless --singleton-scheme --instance-count 1 --dns-name rediscache.cluster


问:
Hackerearth Feel Taller
Link to the problem -> https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/feel-taller/

What is wrong with my code or logic?

I keep track of the number of building taller than the current building starting from the last building using STACK. I do this by keeping track of number of elements in the stack(the elements which are taller than the current element).

In the queries i subtract the left from right and add 1.
left -> number of building that can be seen from left
right -> number of building that can be seen from right
If we subtract both we get number of building than can be seen in the range.

Consider an example: There are 7 pillars (k) and height of each pillar is 5 2 3 7 9 8 11. Using stack I keep track of number of pillars greater than the current pillar (so visible over it) and store it in array p . Whose values are (height of the current pillar)->(number of pillars greater than this pillar) 5->3 2->4 3->3 7->2 9->1 8->1 11->0 . In the queries i subtract right from left because left has the number of pillars greater than the current pillar and if i subtract right i get the pillars in range.

I want to know what is wrong with this logic.

There is a different approach for the problem and i know that.
Please tell me what is wrong with this code.

Link to my code -> https://www.hackerearth.com/submission/42773897/

```<code>//https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/feel-taller/
//Feel Taller
import java.util.*;
import java.io.*;
public class Feel_Taller{
    public static void main(String[] args) throws Exception{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        int k = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine().trim());

        long a[] = new long[k];
        for(int i=0;i<k;i++)
            a[i] = Long.parseLong(st.nextToken());

        Stack<Integer> s = new Stack<Integer>();
        int n = 0;                              //Number of elements in the stack
        int p[] = new int[k];                   //Number of pillars greater than this pillar

        for(int i = k-1;i>=0;i--)
        {
            while(!s.empty() && a[s.peek()]<=a[i]){
                s.pop();
                n--;
            }
            p[i] = n;
            s.push(i);
            n++;
        }

        //Queries
        int q = Integer.parseInt(br.readLine().trim());
        while(q-->0){
            st = new StringTokenizer(br.readLine().trim());
            int l = Integer.parseInt(st.nextToken());
            int r = Integer.parseInt(st.nextToken());
            if(r>=k)
                r = k-1;
            sb.append(p[l]-p[r]+1).append("\n");
        }

        pw.print(sb);
        pw.flush();
        pw.close();
    }
}
</code>```

Or please explain how can we solve the problem using my approach.
Thank you.

答:
Without having studied your code, this is where your logic seems to go wrong: your subtraction will not always give the correct result.

Consider this row of buildings or pillars:

```<code>7 3 5
</code>```

Now I believe that your counts of taller pillars should be 7->0 3->1 and 5->0.

When I query the range [0, 1] the answer should be 1: only the 7 tall building is visible. Your subtraction p[l]-p[r]+1 yields 0 - 1 + 1 = 0, so one building too few. One way to put it is, you subtract 1 for the 5 tall building because it is outside the queried range, but that building was never visible in the first place so should not be subtracted.

Title: Hackerearth Feel Taller

Body:
Link to the problem -> https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/feel-taller/

What is wrong with my code or logic?

I keep track of the number of building taller than the current building starting from the last building using STACK. I do this by keeping track of number of elements in the stack(the elements which are taller than the current element).

In the queries i subtract the left from right and add 1.
left -> number of building that can be seen from left
right -> number of building that can be seen from right
If we subtract both we get number of building than can be seen in the range.

Consider an example: There are 7 pillars (k) and height of each pillar is 5 2 3 7 9 8 11. Using stack I keep track of number of pillars greater than the current pillar (so visible over it) and store it in array p . Whose values are (height of the current pillar)->(number of pillars greater than this pillar) 5->3 2->4 3->3 7->2 9->1 8->1 11->0 . In the queries i subtract right from left because left has the number of pillars greater than the current pillar and if i subtract right i get the pillars in range.

I want to know what is wrong with this logic.

There is a different approach for the problem and i know that.
Please tell me what is wrong with this code.

Link to my code -> https://www.hackerearth.com/submission/42773897/

//https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/feel-taller/
//Feel Taller
import java.util.*;
import java.io.*;
public class Feel_Taller{
    public static void main(String[] args) throws Exception{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        int k = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine().trim());

        long a[] = new long[k];
        for(int i=0;i<k;i++)
            a[i] = Long.parseLong(st.nextToken());

        Stack<Integer> s = new Stack<Integer>();
        int n = 0;                              //Number of elements in the stack
        int p[] = new int[k];                   //Number of pillars greater than this pillar

        for(int i = k-1;i>=0;i--)
        {
            while(!s.empty() && a[s.peek()]<=a[i]){
                s.pop();
                n--;
            }
            p[i] = n;
            s.push(i);
            n++;
        }

        //Queries
        int q = Integer.parseInt(br.readLine().trim());
        while(q-->0){
            st = new StringTokenizer(br.readLine().trim());
            int l = Integer.parseInt(st.nextToken());
            int r = Integer.parseInt(st.nextToken());
            if(r>=k)
                r = k-1;
            sb.append(p[l]-p[r]+1).append("\n");
        }

        pw.print(sb);
        pw.flush();
        pw.close();
    }
}

Or please explain how can we solve the problem using my approach.
Thank you.

Body:
Without having studied your code, this is where your logic seems to go wrong: your subtraction will not always give the correct result.

Consider this row of buildings or pillars:

7 3 5

Now I believe that your counts of taller pillars should be 7->0 3->1 and 5->0.

When I query the range [0, 1] the answer should be 1: only the 7 tall building is visible. Your subtraction p[l]-p[r]+1 yields 0 - 1 + 1 = 0, so one building too few. One way to put it is, you subtract 1 for the 5 tall building because it is outside the queried range, but that building was never visible in the first place so should not be subtracted.


问:
Changing image in django user change form
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

```<code>
class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

</code>```

This is my USER CHANGE FORM

```<code>class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```
```

答: Basically you are getting the instance but you are not only able to update only the picture.</p>

Body:
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

This is my USER CHANGE FORM

class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```


问:
Copying from one stream to another?
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

```<code>BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();
</code>```

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

答:
The size of the buffer does matter. If you're copying a megabyte of data one byte at a time, for example, you're going to make a 2^20 iterations through the loop. If you're copying 1 kilobyte at a time, you'll only make 2^10 iterations through the loop. There is significant overhead in the calls to Read and Write when you're making a million of them.

For reading FileStream, I typically use a buffer that's between 64K and 256K. Anything less than 32K shows a marked decrease in performance, as does anything above 256K. The difference between using a 64K buffer and a 256K buffer is not worth the extra memory. Be aware, though, that those numbers are on my system and across my network. Your numbers will vary depending on hardware and operating system.

For network streams, you should select a buffer size that will keep up with the incoming data stream. I'd suggest at least 4 kilobytes, which will give you some buffer if the write stalls for any reason.

ContentLicense: CC BY-SA 3.0

Title: Copying from one stream to another?

Body:
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.


问:
Why do I not need to use Input.Length[i]?
```<code>        var input = Console.ReadLine();
        int letterCount = 0;
        int wordCount = 0;
        int specialChar = 0;
        for (int i = 0; i <= input.Length-1; i++)
        {
            if ((input[i] >= 'a'&& input[i] <= 'z' )|| (input[i] >= 'A' && input[i] <= 'Z'))
            {
                letterCount++;
            }
            else if (input[i] >='0'&&input[i]<='9')
            {
                wordCount++;
            }
            else
            {
                specialChar++;
            }
        }
</code>```

(input[i] >= 'a'&& input[i] <= 'z' )|| (input[i] >= 'A' && input[i] <= 'Z') this is whats bugging me. Shouldn't I have to write input.Length[i] how does the program know that I am still using the input length ?

答:
Your limitations defined in this loop, "i" will go from 0 to the length-1.

```<code>for (int i = 0; i <= input.Length-1; i++)
</code>```

each time you enter the loop you will take input[0], input[1] and so on, that way you will iterate over all the input

Also Input.Length[i] in not valid.

Input.Length will return length

Input[I] will return the value in place "i" in the input.

Body:
        var input = Console.ReadLine();
        int letterCount = 0;
        int wordCount = 0;
        int specialChar = 0;
        for (int i = 0; i <= input.Length-1; i++)
        {
            if ((input[i] >= 'a'&& input[i] <= 'z' )|| (input[i] >= 'A' && input[i] <= 'Z'))
            {
                letterCount++;
            }
            else if (input[i] >='0'&&input[i]<='9')
            {
                wordCount++;
            }
            else
            {
                specialChar++;
            }
        }

(input[i] >= 'a'&& input[i] <= 'z' )|| (input[i] >= 'A' && input[i] <= 'Z') this is whats bugging me. Shouldn't I have to write input.Length[i] how does the program know that I am still using the input length ?

Body:
Your limitations defined in this loop, "i" will go from 0 to the length-1.

for (int i = 0; i <= input.Length-1; i++)

each time you enter the loop you will take input[0], input[1] and so on, that way you will iterate over all the input

Also Input.Length[i] in not valid.

Input.Length will return length

Input[I] will return the value in place "i" in the input.


问:
failed run Postgres in alpine dockerfile
i am trying to deploy my Go app with Alpine in docker, I was able to use it on my Mac and then going to Production with Centos 8 got issues
here is my Dockerfile:

```<code>FROM golang:alpine

RUN apk add --no-cache postgresql

RUN apk update && apk add --no-cache gcc && apk add --no-cache libc-dev && apk add --no-cache --update make

# Set the current working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. they will be cached of the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the WORKDIR inisde the container
COPY . .

# Build the Go app
RUN go build .

RUN rm -rf /usr/local/var/postgres/postmaster.pid

// this commands below like "psql -c ;'DROP DATABASE IF EXISTS prod'"
// "psql -c ;'CREATE USER prod'"
RUN make setup

# Exporse port 3000 or 8000 to the outisde world
EXPOSE 3000..

CMD ["make", "run" ]
</code>```

then i got error:

```<code>psql: error: could not connect to server: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
</code>```

on my make setup i do the migration, create user, database

can make SUPERUSER on psql for that alpine also??

what u can see on the above syntax, is there any wrong and how to correct it? I have stuck from yesterday

答:
Delete your original docker file's from 8th line to 20th and add these.

If your folder structure like this :

```<code>- directory
    |
    -> Dockerfile
    -> go.mod
    -> go.sum
    -> go source files
</code>```

```<code># Copy go mod and sum files
COPY . /app

# Set the current working Directory inside the container
WORKDIR /app

RUN go mod download

RUN go build .
</code>```

Body:
i am trying to deploy my Go app with Alpine in docker, I was able to use it on my Mac and then going to Production with Centos 8 got issues
here is my Dockerfile:

FROM golang:alpine

RUN apk add --no-cache postgresql

RUN apk update && apk add --no-cache gcc && apk add --no-cache libc-dev && apk add --no-cache --update make

# Set the current working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. they will be cached of the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the WORKDIR inisde the container
COPY . .

# Build the Go app
RUN go build .

RUN rm -rf /usr/local/var/postgres/postmaster.pid

// this commands below like "psql -c ;'DROP DATABASE IF EXISTS prod'"
// "psql -c ;'CREATE USER prod'"
RUN make setup

# Exporse port 3000 or 8000 to the outisde world
EXPOSE 3000..

CMD ["make", "run" ]

then i got error:

psql: error: could not connect to server: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

on my make setup i do the migration, create user, database

can make SUPERUSER on psql for that alpine also??

what u can see on the above syntax, is there any wrong and how to correct it? I have stuck from yesterday

Body:
Delete your original docker file's from 8th line to 20th and add these.

If your folder structure like this :

- directory
    |
    -> Dockerfile
    -> go.mod
    -> go.sum
    -> go source files

# Copy go mod and sum files
COPY . /app

# Set the current working Directory inside the container
WORKDIR /app

RUN go mod download

RUN go build .


问:
Unable to iterate a dictionary in django templating language
I have not been able to iterate (key and values) in a nested dictionary generated from views.py where

context = { "orders_current": orders_current }

with

return render(request, "orders/cart.html", context)
orders_current is a result from a query in views.py:

orders_current = Orders.objects.values('def', 'abc', 'toppings')

'toppings' is stored in the database as JSON data but converted (loads) back to a dictionary in the class method:

def __str__(self)

in models.py. I did this since I read somewhere this is a recommend way of storing a dictionary in the postgresql.

Note that orders_current has multiple and nested dictionaries e.g.:

< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >

The dictionary {{ order.toppings }} passed to the html, cart.html is shown to have the value (in verbatim) e.g.:

{"Mushrooms": 1.5, "Canadian Bacon": 1.5}

So my latest attempt to extract the topping name and the corresponding price (key, value) from the dictionary is:

```<code>{% for order in orders_current %}
...
<table>
  {% for name, price in order.toppings.items %}
      <tr>
          <td>{{ name }}:</td>
          <td>${{ price }}</td>
      </tr>
  {% endfor %}
</table>
</code>```

I got no values (name, price)from this code snippet.
Based on my web searches, I've tried almost all variations of the above and with different ways of setting up the context for transfer.  Any help will be appreciated.

答:
Based on your queryset:

```<code>< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >
</code>```

order.toppings is a string, try to convert it to dictionary in the views:

```<code>import ast
for order in orders_current:
     order["toppings"] = ast.literal_eval(order["toppings"])
</code>```

Here are different ways to convert string dictionary to dictionary.
https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/

After you convert it, it should work in the template.

Body:
I have not been able to iterate (key and values) in a nested dictionary generated from views.py where

context = { "orders_current": orders_current }

with

return render(request, "orders/cart.html", context)
orders_current is a result from a query in views.py:

orders_current = Orders.objects.values('def', 'abc', 'toppings')

'toppings' is stored in the database as JSON data but converted (loads) back to a dictionary in the class method:

def __str__(self)

in models.py. I did this since I read somewhere this is a recommend way of storing a dictionary in the postgresql.

Note that orders_current has multiple and nested dictionaries e.g.:

< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >

The dictionary {{ order.toppings }} passed to the html, cart.html is shown to have the value (in verbatim) e.g.:

{"Mushrooms": 1.5, "Canadian Bacon": 1.5}

So my latest attempt to extract the topping name and the corresponding price (key, value) from the dictionary is:

{% for order in orders_current %}
...

  {% for name, price in order.toppings.items %}

          {{ name }}:
          ${{ price }}

  {% endfor %}

I got no values (name, price)from this code snippet.
Based on my web searches, I've tried almost all variations of the above and with different ways of setting up the context for transfer.  Any help will be appreciated.

Body:
Based on your queryset:

< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >

order.toppings is a string, try to convert it to dictionary in the views:

import ast
for order in orders_current:
     order["toppings"] = ast.literal_eval(order["toppings"])

Here are different ways to convert string dictionary to dictionary.
https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/

After you convert it, it should work in the template.


问:
Multiple condition on same column inside Linq where
How can I write a linq query to match two condition on same column in the table?

Here one person can be assigned to multiple types of works and it is store in PersonWorkTypes table containing the details of persons and their worktypes.

So I need to get the list of persons who have both fulltime and freelance works.

I have tried

```<code>people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")
</code>```

But it returns an empty result.

答:
You can try this

```<code>public class Person {
    public string Name {get;set;}
    public List<PersonWorkType> PersonWorkTypes {get;set;}
}

public class PersonWorkType {
    public string Type {get;set;}
}

public static void Main()
{
    var people = new List<Person>();
    var person = new Person { Name = "Toño", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" } } };
    var person2 = new Person { Name = "Aldo", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };
    var person3 = new Person { Name = "John", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };

    people.Add(person);
    people.Add(person2);
    people.Add(person3);

    var filter = people.Where(p => p.PersonWorkTypes.Any(t => t.Type == "freelance") && p.PersonWorkTypes.Any(t => t.Type == "fulltime"));

    foreach(var item in filter) {
        Console.WriteLine(item.Name);
    }
}
</code>```

This returns person that contains both types in PersonWorkTypes

Body:
How can I write a linq query to match two condition on same column in the table?

Here one person can be assigned to multiple types of works and it is store in PersonWorkTypes table containing the details of persons and their worktypes.

So I need to get the list of persons who have both fulltime and freelance works.

I have tried

people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")

But it returns an empty result.

Body:
You can try this

public class Person {
    public string Name {get;set;}
    public List<PersonWorkType> PersonWorkTypes {get;set;}
}

public class PersonWorkType {
    public string Type {get;set;}
}

public static void Main()
{
    var people = new List<Person>();
    var person = new Person { Name = "Toño", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" } } };
    var person2 = new Person { Name = "Aldo", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };
    var person3 = new Person { Name = "John", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };

    people.Add(person);
    people.Add(person2);
    people.Add(person3);

    var filter = people.Where(p => p.PersonWorkTypes.Any(t => t.Type == "freelance") && p.PersonWorkTypes.Any(t => t.Type == "fulltime"));

    foreach(var item in filter) {
        Console.WriteLine(item.Name);
    }
}

This returns person that contains both types in PersonWorkTypes


问:
Call to MKL_SDNSCSR of intell MKL failing
I just dowloaded MKL in intend to try its sparse BLAS, the first thing I tried was the conversion of full matrix to sparse one with MKL_SDNSCSR

Here my code:

```<code>implicit none

real::A(2,5)
integer::job(8)
INTEGER::  info,n=2,m=5
INTEGER      ja(10), ia(6)
REAL          acsr(10)

A(1,:)=(/1, 0 ,1,0,2/)
A(2,:)=(/2,0,0,0,1/)

job=0
job(1)=0
job(2)=1
job(3)=1
job(4)=2
job(5)=10
job(6)=1

print*,A
print*,job

call mkl_sdnscsr(job,n,m,A,m,acsr,ja,ia,info)

end
</code>```

It gives the following error:

```<code>Intel MKL ERROR: Parameter 1 was incorrect on entry to MKL_SDNSCSR.
</code>```

What did I did wrong?

Best

Body:
I just dowloaded MKL in intend to try its sparse BLAS, the first thing I tried was the conversion of full matrix to sparse one with MKL_SDNSCSR

Here my code:

implicit none

real::A(2,5)
integer::job(8)
INTEGER::  info,n=2,m=5
INTEGER      ja(10), ia(6)
REAL          acsr(10)

A(1,:)=(/1, 0 ,1,0,2/)
A(2,:)=(/2,0,0,0,1/)

job=0
job(1)=0
job(2)=1
job(3)=1
job(4)=2
job(5)=10
job(6)=1

print*,A
print*,job

call mkl_sdnscsr(job,n,m,A,m,acsr,ja,ia,info)

end

It gives the following error:

Intel MKL ERROR: Parameter 1 was incorrect on entry to MKL_SDNSCSR.

What did I did wrong?

Best

Body:
I see no problems with this example. I tried the MKL v.2020 on win64.
here is the output I obtained:

   1.000000       2.000000      0.0000000E+00  0.0000000E+00   1.000000
  0.0000000E+00  0.0000000E+00  0.0000000E+00   2.000000       1.000000
           0           1           1           2          10           1
           0           0


问:
Get comma separated string from Mysql
I'm saving a string from PHP to MySQL like this..

```<code>$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");
</code>```

I'm then trying to extract data from the table if $a = "15"

```<code>$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");
</code>```

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

答:
Expanding on @ecchymose's answer, you can use a regex instead of LIKE.

```<code>SELECT *
FROM table
WHERE ustaffid='$ustaffid'
AND groupid RLIKE '(^|, )$a(, |$)'
</code>```

Note: You may need to escape the last $ with a \.

Note 2: This isn't the optimal solution.  You should really have a separate row for each ID (with the ID being the PRIMARY key).

Title: Get comma separated string from Mysql

Body:
I'm saving a string from PHP to MySQL like this..

$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");

I'm then trying to extract data from the table if $a = "15"

$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

Body:
Expanding on @ecchymose's answer, you can use a regex instead of LIKE.

SELECT *
FROM table
WHERE ustaffid='$ustaffid'
AND groupid RLIKE '(^|, )$a(, |$)'

Note: You may need to escape the last $ with a \.

Note 2: This isn't the optimal solution.  You should really have a separate row for each ID (with the ID being the PRIMARY key).


问:
check if input equals a specific string without repeating code
So im making a simple console menu for my program.

```<code># Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)
</code>```

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

答:
That is a very good question and you almost have the right answer - yes to a dedicated custom input function. Then, the only missing puzzle piece is using exceptions as flow control!

I couldn't find a nice documentation link quickly but I found a good post about it here.

Python is built with using exceptions as a tool to control your code flow in mind. They perform faster than if statements (unless they occur frequently which isn't our case) and let's you write with very few if statements. It might seem unnatural, at first, but it is Pythonic.

The idea is to raise an exception in custom_input for special cases such as "quit". You maintain the logic of when the program should exit (such as "quit", "exit" or others if you need) in one place and indicate to the calling stack (other functions chain) that a special case needs to be handled by raise-ing an exception.

def custom_input(prompt):
    value = input(prompt)
    if value == 'quit':
        raise KeyboardInterrupt("User requested to exit.")
    else:
        return value

def main():
    try:
        while True:
            value = custom_input(prompt = "Input parameters")
    except KeyboardInterrupt:
        print("Thank you, come again! Bye!")
```

And you can use custom_input several times, only needing if statements for menu choices. But, having the quit logic in one place rather than repeating the code.

Couldn't post from my phone fast enough :(

Body:
So im making a simple console menu for my program.

# Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

Body:
That is a very good question and you almost have the right answer - yes to a dedicated custom input function. Then, the only missing puzzle piece is using exceptions as flow control!

I couldn't find a nice documentation link quickly but I found a good post about it here.

Python is built with using exceptions as a tool to control your code flow in mind. They perform faster than if statements (unless they occur frequently which isn't our case) and let's you write with very few if statements. It might seem unnatural, at first, but it is Pythonic.

The idea is to raise an exception in custom_input for special cases such as "quit". You maintain the logic of when the program should exit (such as "quit", "exit" or others if you need) in one place and indicate to the calling stack (other functions chain) that a special case needs to be handled by raise-ing an exception.

def custom_input(prompt):
    value = input(prompt)
    if value == 'quit':
        raise KeyboardInterrupt("User requested to exit.")
    else:
        return value

def main():
    try:
        while True:
            value = custom_input(prompt = "Input parameters")
    except KeyboardInterrupt:
        print("Thank you, come again! Bye!")

And you can use custom_input several times, only needing if statements for menu choices. But, having the quit logic in one place rather than repeating the code.

Couldn't post from my phone fast enough :(


问:
Is there a function in R that splits a matrix along a margin using a factor or categorical vector?
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

```<code>m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)
</code>```

split doesn't seem to work with matrices so we could convert it into a data.frame:

```<code>split(data.frame(m), f = g)
</code>```

This works but I'd like to keep it as a matrix. The following loop works:

```<code>lapply(groups, function(x) m[g == x,])
</code>```

But is there a dedicated function, or a better way?

Body:
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)

split doesn't seem to work with matrices so we could convert it into a data.frame:

split(data.frame(m), f = g)

This works but I'd like to keep it as a matrix. The following loop works:

lapply(groups, function(x) m[g == x,])

But is there a dedicated function, or a better way?

Body:
You could iterate over unique values of g and use it to subset the matrices.

sapply(unique(g), function(x) m[g == x, ])

#$B
#        [,1]   [,2]   [,3]   [,4]   [,5]
#[1,] -0.3752 -0.180 -0.333 -0.634  2.011
#[2,] -0.0628 -0.537  2.089  2.069  0.605
#[3,] -0.7635  1.028 -0.779  1.205 -0.110

#$A
#       [,1]   [,2]  [,3]   [,4]   [,5]
#[1,] -0.128 -1.037 0.512 -1.104  0.303
#[2,] -0.246 -0.691 1.303 -0.571  2.023
#[3,] -1.374  0.867 0.810 -0.904 -0.268
#[4,]  0.111 -0.013 0.827  1.294  0.999

#$C
#      [,1]   [,2]   [,3]   [,4]   [,5]
#[1,] 0.712  1.465 -0.471 -0.383 -0.191
#[2,] 1.400  0.121  0.360 -0.890  0.412
#[3,] 0.967 -1.176  0.146  0.570 -0.143


问:
didFinishReceivingResourceWithName not being called
I'm sending video over MC on an app I'm making, didStartReceivingResourceWithName is being called correctly. The NSProgress object associated with that callback reaches 101.0% and then didFinishReceivingResourceWithName is never called. Do you have any ideas? Heres the code in each.</p>

```<code>func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
    print("Did start receiving resource")
    dispatch_async(dispatch_get_main_queue()){
        self.progressTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "progressManager", userInfo: nil, repeats: true)
        self.progress = progress
    }
}
func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
    dispatch_async(dispatch_get_main_queue()){
        self.status.text = "Recieved!"
    }
    self.progressTimer.invalidate()
    let destinationPath  =
    NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("movie.mov")
    let fileManager: NSFileManager = NSFileManager.defaultManager()
    do{
        try fileManager.moveItemAtURL(localURL, toURL: destinationPath)
    }
    catch let error as NSError {
        print(error)
    }
    print("Did finish receiving resource")
}
</code>```

答: I ran into this issue when calling sendResource with the local URL to a video file that I created using AVAssetWriter. It turns out that I was calling sendResource on the video file before AVAssetWriter was finished writing the video. After I modified my code to call sendResource in the completion handler for .finishWriting, everything worked as expected.</p>

Body:
I'm sending video over MC on an app I'm making, didStartReceivingResourceWithName is being called correctly. The NSProgress object associated with that callback reaches 101.0% and then didFinishReceivingResourceWithName is never called. Do you have any ideas? Heres the code in each.

func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
    print("Did start receiving resource")
    dispatch_async(dispatch_get_main_queue()){
        self.progressTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "progressManager", userInfo: nil, repeats: true)
        self.progress = progress
    }
}
func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
    dispatch_async(dispatch_get_main_queue()){
        self.status.text = "Recieved!"
    }
    self.progressTimer.invalidate()
    let destinationPath  =
    NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("movie.mov")
    let fileManager: NSFileManager = NSFileManager.defaultManager()
    do{
        try fileManager.moveItemAtURL(localURL, toURL: destinationPath)
    }
    catch let error as NSError {
        print(error)
    }
    print("Did finish receiving resource")
}


答:
AS already said, && operator means, that BOTH conditions has to be met. So in your condition it means that you want worktype type to by freelanceand fulltime at the same time, which is not possible :)

Most probably you want employees that have work type freelance OR fulltime, thus your condition should be:

```<code>people.Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")
</code>```

Or, if person can be set more than once in this table, then you could do:

```<code>people
  .Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")
  // here I assume that you have name of a person,
  // Basically, here I group by person
  .GroupBy(p => p.Name)
  // Here we check if any person has two entries,
  // but you have to be careful here, as if person has two entries
  // with worktype freelance or two entries with fulltime, it
  // will pass condition as well.
  .Where(grp => grp.Count() == 2)
  .Select(grp => grp.FirstOrDefault());
</code>```

Title: Multiple condition on same column inside Linq where

Body:
AS already said, && operator means, that BOTH conditions has to be met. So in your condition it means that you want worktype type to by freelanceand fulltime at the same time, which is not possible :)

Most probably you want employees that have work type freelance OR fulltime, thus your condition should be:

people.Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")

Or, if person can be set more than once in this table, then you could do:

people
  .Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")
  // here I assume that you have name of a person,
  // Basically, here I group by person
  .GroupBy(p => p.Name)
  // Here we check if any person has two entries,
  // but you have to be careful here, as if person has two entries
  // with worktype freelance or two entries with fulltime, it
  // will pass condition as well.
  .Where(grp => grp.Count() == 2)
  .Select(grp => grp.FirstOrDefault());


问:
Class Not Found in PHP Laravel 6.x when another class extends
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

```<code><?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}
</code>```

Class myUser: extension is fine.

```<code><?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}
</code>```

Class oauth: extension returns myContext class not found.

```<code><?php
namespace config\models;

class oauth extends myContext {
    private $user;
}
</code>```

Instantiate the class - returns class not found.

```<code><?php

use config\models\myContext as context;

$cont = new context();
</code>```

答:
In composer.json file,

```<code>"autoload": {
    "psr-4": {
        "App\\": "app/",
        "config\\models\\": "config/models"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ]
},
</code>```

After that composer dump-autoload.

Body:
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

<?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}

Class myUser: extension is fine.

<?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}

Class oauth: extension returns myContext class not found.

<?php
namespace config\models;

class oauth extends myContext {
    private $user;
}

Instantiate the class - returns class not found.

<?php

use config\models\myContext as context;

$cont = new context();

Body:
In composer.json file,

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "config\\models\\": "config/models"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ]
},

After that composer dump-autoload.


问:
Select statement based on category
I have a table like this

```<code>Code
A123
B3123
C93485
D345
E29845
</code>```

The first letter of rows in code column are classified into the following:

```<code>Char Category
A-B      A
C        B
D-E      C
</code>```

I would like to display the output table like this

```<code>Category Total Percentage
A          2     0.4%
B          1     0.2%
C          2     0.4%
     Total 5     1.0%
</code>```

I'm not sure how to start. Any hints or help is much appreciated

答:
Here is one option:

```<code>SELECT
    CASE WHEN SUBSTR(Code, 1, 1) IN ('A', 'B') THEN 'A'
         WHEN SUBSTR(Code, 1, 1) = 'C' THEN 'B'
         ELSE 'C' END AS Category,
    COUNT(*) AS Total,
    200.0 * COUNT(*) / SUM(COUNT(*)) OVER () AS Percentage
FROM yourTable
GROUP BY
    ROLLUP(CASE WHEN SUBSTR(Code, 1, 1) IN ('A', 'B') THEN 'A'
         WHEN SUBSTR(Code, 1, 1) = 'C' THEN 'B'
         ELSE 'C' END);
</code>```

Demo

This approach uses a CASE expression on the first letter of each code to assign a category.  Then, we aggregate by category and find the totals, as well as the percentages.  Note that ROLLUP is used to generate a total record at the bottom of the result set.  As a side effect of this, we multiply by 200%, because the summary row already contains the entire table count, which then gets counted twice.

Title: Select statement based on category

Body:
I have a table like this

Code
A123
B3123
C93485
D345
E29845

The first letter of rows in code column are classified into the following:

Char Category
A-B      A
C        B
D-E      C

I would like to display the output table like this

Category Total Percentage
A          2     0.4%
B          1     0.2%
C          2     0.4%
     Total 5     1.0%

I'm not sure how to start. Any hints or help is much appreciated

Body:
Here is one option:

SELECT
    CASE WHEN SUBSTR(Code, 1, 1) IN ('A', 'B') THEN 'A'
         WHEN SUBSTR(Code, 1, 1) = 'C' THEN 'B'
         ELSE 'C' END AS Category,
    COUNT(*) AS Total,
    200.0 * COUNT(*) / SUM(COUNT(*)) OVER () AS Percentage
FROM yourTable
GROUP BY
    ROLLUP(CASE WHEN SUBSTR(Code, 1, 1) IN ('A', 'B') THEN 'A'
         WHEN SUBSTR(Code, 1, 1) = 'C' THEN 'B'
         ELSE 'C' END);

Demo

This approach uses a CASE expression on the first letter of each code to assign a category.  Then, we aggregate by category and find the totals, as well as the percentages.  Note that ROLLUP is used to generate a total record at the bottom of the result set.  As a side effect of this, we multiply by 200%, because the summary row already contains the entire table count, which then gets counted twice.


问:
Getting "System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'"
I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormApp32
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text + textBox6.Text == " ")
                    MessageBox.Show("Please fill mandatory fields");

                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
                using (var cmd = new SqlDataAdapter())
                using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@First_Name, @Last_Name, @Email_ID, @Contact, @Address, @Gender, @Department, @Username, @Password) "))
                {
                    insertCommand.Connection = connectionString;
                    cmd.InsertCommand = insertCommand;

                    connectionString.Open();

                }
                sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Registration successful");
                }
            }

        }
    }
</code>```

I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part

The code shows following now

```<code>                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());
                sqlCmd.Connection = connectionString;```

```

答: You are mixing u everything here. You need to run the respective command in the respective connection. this line is also wrong connectionString.Open(); Also you have not provided Connection to sqlCmd.

Body:
I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormApp32
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text + textBox6.Text == " ")
                    MessageBox.Show("Please fill mandatory fields");

                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
                using (var cmd = new SqlDataAdapter())
                using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@First_Name, @Last_Name, @Email_ID, @Contact, @Address, @Gender, @Department, @Username, @Password) "))
                {
                    insertCommand.Connection = connectionString;
                    cmd.InsertCommand = insertCommand;

                    connectionString.Open();

                }
                sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Registration successful");
                }
            }

        }
    }

I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part

The code shows following now

                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());
                sqlCmd.Connection = connectionString;```


问:
How Can I Solve error: method does not override or implement a method from a supertype @Override ^
I found this error on my android studio after I upgrade some implementation. I dont know which one cause this issue.

```<code>/Users/ridhoswasta/Documents/Aplikasi Project/moneywallet-master/app/src/main/java/com/oriondev/moneywallet/model/WalletAccount.java:50: error: method does not override or implement a method from a supertype
    @Override
</code>```

Here is the related code :

/*
 * Copyright (c) 2018.
 *
 * This file is part of MoneyWallet.
 *
 * MoneyWallet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MoneyWallet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MoneyWallet.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.oriondev.moneywallet.model;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.DrawableRes;

import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.oriondev.moneywallet.utils.IconLoader;
import com.oriondev.moneywallet.utils.MoneyFormatter;

/**
 * Created by andrea on 23/01/18.
 */
public class WalletAccount extends ProfileDrawerItem {

    private MoneyFormatter mMoneyFormatter = MoneyFormatter.getInstance();

    private long mId;
    private Money mMoney;

    @Override
    public WalletAccount withIdentifier(long identifier) {
        super.withIdentifier(identifier);
        return this;
    }

    @Override
    public WalletAccount withName(String name) {
        super.withName(name);
        return this;
    }

    @Override
    public WalletAccount withEmail(String email) {
        throw new IllegalStateException("Email field is not supported in WalletAccount.");
    }

    @Override
    public StringHolder getEmail() {
        return new StringHolder(mMoneyFormatter.getNotTintedString(mMoney));
    }

    public WalletAccount withIcon(Context context, Icon icon) {
        Icon safeIcon = icon != null ? icon : IconLoader.UNKNOWN;
        if (safeIcon instanceof VectorIcon) {
            super.withIcon(((VectorIcon) safeIcon).getResource(context));
        } else if (safeIcon instanceof ColorIcon) {
            super.withIcon(((ColorIcon) safeIcon).getDrawable());
        }
        return this;
    }

    @Override
    public WalletAccount withIcon(Drawable icon) {
        super.withIcon(icon);
        return this;
    }

    @Override
    public WalletAccount withIcon(@DrawableRes int iconRes) {
        super.withIcon(iconRes);
        return this;
    }

    @Override
    public WalletAccount withIcon(Bitmap iconBitmap) {
        super.withIcon(iconBitmap);
        return this;
    }

    @Override
    public WalletAccount withIcon(IIcon icon) {
        super.withIcon(icon);
        return this;
    }

    @Override
    public WalletAccount withIcon(String url) {
        super.withIcon(url);
        return this;
    }

    @Override
    public WalletAccount withIcon(Uri uri) {
        super.withIcon(uri);
        return this;
    }

    public WalletAccount withId(long id) {
        mId = id;
        return this;
    }

    public long getId() {
        return mId;
    }

    public WalletAccount withMoney(String currency, long money) {
        mMoney = new Money(currency, money);
        return this;
    }

    public WalletAccount withMoney(Money money) {
        mMoney = money;
        return this;
    }
}```

After I try to find some alternative answers, it cant be implemented on my code. A little bit confuse about this.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

答:
@Override means you are overriding method from superclass (in this case ProfileDrawerItem). if it can't be overriden then this method probably disapear in original class after dependency upgrade. This error isn't "fixable" - you have to read what changed in which library and override proper method or fit to new flow of superclass

edit: this method doesn't exists in ProfileDrawerItem anymore, look for equivalent (or remove if not needed, but I doubt)

```<code>@Override
public WalletAccount withName(String name) {
    super.withName(name);
    return this;
}
</code>```

Body:
I found this error on my android studio after I upgrade some implementation. I dont know which one cause this issue.

/Users/ridhoswasta/Documents/Aplikasi Project/moneywallet-master/app/src/main/java/com/oriondev/moneywallet/model/WalletAccount.java:50: error: method does not override or implement a method from a supertype
    @Override

Here is the related code :

/*
 * Copyright (c) 2018.
 *
 * This file is part of MoneyWallet.
 *
 * MoneyWallet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MoneyWallet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MoneyWallet.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.oriondev.moneywallet.model;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.DrawableRes;

import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.oriondev.moneywallet.utils.IconLoader;
import com.oriondev.moneywallet.utils.MoneyFormatter;

/**
 * Created by andrea on 23/01/18.
 */
public class WalletAccount extends ProfileDrawerItem {

    private MoneyFormatter mMoneyFormatter = MoneyFormatter.getInstance();

    private long mId;
    private Money mMoney;

    @Override
    public WalletAccount withIdentifier(long identifier) {
        super.withIdentifier(identifier);
        return this;
    }

    @Override
    public WalletAccount withName(String name) {
        super.withName(name);
        return this;
    }

    @Override
    public WalletAccount withEmail(String email) {
        throw new IllegalStateException("Email field is not supported in WalletAccount.");
    }

    @Override
    public StringHolder getEmail() {
        return new StringHolder(mMoneyFormatter.getNotTintedString(mMoney));
    }

    public WalletAccount withIcon(Context context, Icon icon) {
        Icon safeIcon = icon != null ? icon : IconLoader.UNKNOWN;
        if (safeIcon instanceof VectorIcon) {
            super.withIcon(((VectorIcon) safeIcon).getResource(context));
        } else if (safeIcon instanceof ColorIcon) {
            super.withIcon(((ColorIcon) safeIcon).getDrawable());
        }
        return this;
    }

    @Override
    public WalletAccount withIcon(Drawable icon) {
        super.withIcon(icon);
        return this;
    }

    @Override
    public WalletAccount withIcon(@DrawableRes int iconRes) {
        super.withIcon(iconRes);
        return this;
    }

    @Override
    public WalletAccount withIcon(Bitmap iconBitmap) {
        super.withIcon(iconBitmap);
        return this;
    }

    @Override
    public WalletAccount withIcon(IIcon icon) {
        super.withIcon(icon);
        return this;
    }

    @Override
    public WalletAccount withIcon(String url) {
        super.withIcon(url);
        return this;
    }

    @Override
    public WalletAccount withIcon(Uri uri) {
        super.withIcon(uri);
        return this;
    }

    public WalletAccount withId(long id) {
        mId = id;
        return this;
    }

    public long getId() {
        return mId;
    }

    public WalletAccount withMoney(String currency, long money) {
        mMoney = new Money(currency, money);
        return this;
    }

    public WalletAccount withMoney(Money money) {
        mMoney = money;
        return this;
    }
}

After I try to find some alternative answers, it cant be implemented on my code. A little bit confuse about this.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

I try to resolve this issue.

Body:
@Override means you are overriding method from superclass (in this case ProfileDrawerItem). if it can't be overriden then this method probably disapear in original class after dependency upgrade. This error isn't "fixable" - you have to read what changed in which library and override proper method or fit to new flow of superclass

edit: this method doesn't exists in ProfileDrawerItem anymore, look for equivalent (or remove if not needed, but I doubt)

@Override
public WalletAccount withName(String name) {
    super.withName(name);
    return this;
}


问:
I am getting a different maximum and minimum value here
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done
```

<p>Output: </p>

<p>Invalid Input</p>

<p>Maximum is 10</p>

<p>Minimum is 4</p>

<p><strong>Expected Output:</strong></p>

<p><strong>Invalid Input</strong></p>

<p><strong>Maximum is 11</strong></p>

<p><strong>Minimum is 2</strong></p>

```a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()
```

答:
Instead of finding the maximum and minimum value after appending to the array, you can find it before. This will reduce the cost of iterating the array each and every time to find the maximum and minimum.</p>

```<code>a=list()
max_, min_ = float('-inf'), float('inf')
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value = int(sval)
        if value > max_:
            max_ = value
        elif value < min_:
            min_ = value
        a.append(value)
    except:
        print("Invalid")
        continue

print("Maximum is", max_)
print("Minimum is", min_)
</code>```

Body:
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done

Output:

Invalid Input

Maximum is 10

Minimum is 4

Expected Output:

Invalid Input

Maximum is 11

Minimum is 2

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()

Body:
Instead of finding the maximum and minimum value after appending to the array, you can find it before. This will reduce the cost of iterating the array each and every time to find the maximum and minimum.

a=list()
max_, min_ = float('-inf'), float('inf')
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value = int(sval)
        if value > max_:
            max_ = value
        elif value < min_:
            min_ = value
        a.append(value)
    except:
        print("Invalid")
        continue

print("Maximum is", max_)
print("Minimum is", min_)