问:
Covariant instance types on open instance delegates
I'm trying to create open instance delegates for methods that share a common signature, but are defined on many different and unrelated types. These methods are tagged with a custom attribute, and at runtime I lookup all the methods tagged with this attribute in order to construct delegates out of their MethodInfos. For instance, given the delegate:

```<code>delegate void OpenActionDelegate(object instance, float someParam);
</code>```

I would like to match the methods:

```<code>void Foo.SomeAction(float someParam);
void Bar.SomeOtherAction(float someParam);
</code>```

Where Foo and Bar are completely unrelated classes. Armed with the MethodInfo for either method, I'd like to ultimately be able to get an open delegate like so:

```<code>MethodInfo fm = typeof(Foo).GetMethod("SomeAction", BindingFlags.Public | BindingFlags.Instance);
MethodInfo bm = typeof(Bar).GetMethod("SomeOtherAction", BindingFlags.Public | BindingFlags.Instance);
OpenActionDelegate fd = (OpenActionDelegate)Delegate.CreateDelegate(typeof(OpenActionDelegate), fm);
OpenActionDelegate bd = (OpenActionDelegate)Delegate.CreateDelegate(typeof(OpenActionDelegate), bm);
</code>```

The problem I'm running into is the type of the explicit instance specification in the delegate. Since these methods don't have a guaranteed base type they'll be defined on, I've tried just setting object. But trying to bind the MethodInfo fails, presumably because parameter types are not covariant when binding delegates. Switching the delegate signature to have the instance param be of type Foo or Bar works for binding the corresponding MethodInfo.

I don't believe it's actually possible to bind an open delegate like this, because then the explicit instance param wouldn't be of the appropriate type on which to call the method. What bothers me is it is possible to bind a closed delegate to a MethodInfo of any declaring type, since that doesn't include the troublesome instance type. Case in point, I can bind closed delegates to null instances, and then use GetField("_target").SetValue(del, instance) on the delegates just before invoking them. But that's kind of hackish.

Now, in case there are alternative solutions, the reason I'm looking to do this is to avoid heap allocation and value type boxing when directly invoking the MethodInfos, i.e.:

```<code>someActionInfo.Invoke(instance, new object[] { someParam });
</code>```

This causes boxing of the float type, and the object[] array is allocated on the heap, both slowly generating heap garbage for an otherwise throwaway invocation.

答:
Parameter types, including the implicit "this" parameter, clearly cannot be covariant and still be typesafe. Forget about instance methods for a moment and just think about static methods. If you have

```<code>static void Foo(Mammal m) {}
</code>```

then you can't assign that to a delegate that takes an Animal, because the caller of that delegate could pass in a Jellyfish. You can assign it to a delegate that takes a Giraffe though, because then the caller can only pass in Giraffes, and giraffes are mammals.

In short, to be typesafe you need contravariance, not covariance on parameters.

C# does support that in a couple of ways. First off, in C# 4 you can do this:

```<code>Action<Mammal> aa = m=>m.GrowHair();
Action<Giraffe> ag = aa;
</code>```

That is, conversions on the generic action type are contravariant when the varying type parameters are reference types.

Second, in C# 2 and above you can do this:

```<code>Action<Giraffe> aa = myMammal.GrowHair;
</code>```

That is, method group conversions to delegate are contravariant in the parameter types of the method.

But the kind of covariance you want is not typesafe and therefore not supported.

Body:
I'm trying to create open instance delegates for methods that share a common signature, but are defined on many different and unrelated types. These methods are tagged with a custom attribute, and at runtime I lookup all the methods tagged with this attribute in order to construct delegates out of their MethodInfos. For instance, given the delegate:

delegate void OpenActionDelegate(object instance, float someParam);

I would like to match the methods:

void Foo.SomeAction(float someParam);
void Bar.SomeOtherAction(float someParam);

Where Foo and Bar are completely unrelated classes. Armed with the MethodInfo for either method, I'd like to ultimately be able to get an open delegate like so:

MethodInfo fm = typeof(Foo).GetMethod("SomeAction", BindingFlags.Public | BindingFlags.Instance);
MethodInfo bm = typeof(Bar).GetMethod("SomeOtherAction", BindingFlags.Public | BindingFlags.Instance);
OpenActionDelegate fd = (OpenActionDelegate)Delegate.CreateDelegate(typeof(OpenActionDelegate), fm);
OpenActionDelegate bd = (OpenActionDelegate)Delegate.CreateDelegate(typeof(OpenActionDelegate), bm);

The problem I'm running into is the type of the explicit instance specification in the delegate. Since these methods don't have a guaranteed base type they'll be defined on, I've tried just setting object. But trying to bind the MethodInfo fails, presumably because parameter types are not covariant when binding delegates. Switching the delegate signature to have the instance param be of type Foo or Bar works for binding the corresponding MethodInfo.

I don't believe it's actually possible to bind an open delegate like this, because then the explicit instance param wouldn't be of the appropriate type on which to call the method. What bothers me is it is possible to bind a closed delegate to a MethodInfo of any declaring type, since that doesn't include the troublesome instance type. Case in point, I can bind closed delegates to null instances, and then use GetField("_target").SetValue(del, instance) on the delegates just before invoking them. But that's kind of hackish.

Now, in case there are alternative solutions, the reason I'm looking to do this is to avoid heap allocation and value type boxing when directly invoking the MethodInfos, i.e.:

someActionInfo.Invoke(instance, new object[] { someParam });

This causes boxing of the float type, and the object[] array is allocated on the heap, both slowly generating heap garbage for an otherwise throwaway invocation.

Body:
Parameter types, including the implicit "this" parameter, clearly cannot be covariant and still be typesafe. Forget about instance methods for a moment and just think about static methods. If you have

static void Foo(Mammal m) {}

then you can't assign that to a delegate that takes an Animal, because the caller of that delegate could pass in a Jellyfish. You can assign it to a delegate that takes a Giraffe though, because then the caller can only pass in Giraffes, and giraffes are mammals.

In short, to be typesafe you need contravariance, not covariance on parameters.

C# does support that in a couple of ways. First off, in C# 4 you can do this:

Action<Mammal> aa = m=>m.GrowHair();
Action<Giraffe> ag = aa;

That is, conversions on the generic action type are contravariant when the varying type parameters are reference types.

Second, in C# 2 and above you can do this:

Action<Giraffe> aa = myMammal.GrowHair;

That is, method group conversions to delegate are contravariant in the parameter types of the method.

But the kind of covariance you want is not typesafe and therefore not supported.


来源: stackexchange

问:
How can I replace the char '2' in a string with the string "to" in Java?
I am unsure which version of Java I am using, I am using the CodeHS IDE. I am trying to write a function that "fixes the grammar" in a given string. All the method needs to do is replace all of the 2s with to's. Here is my code:  </p>

```<code>public String useProperGrammar(String text) {
   String fixedString = new String();
for (int i = 0; i < text.length(); i++) {
    fixedString += text.charAt(i);
    if (text.charAt(i) == '2') {

     fixedString = text.substring(0, i) + text.substring(i + 1);

      fixedString += "to";
    }
} return fixedString; }
</code>```

答:
If it is a character then convert the char into String and use the replace method.</p>

```<code>    char ch = '2';
    String str = Character.toString(ch);
    str = str.replace('2' + "", "to");
    System.out.println(str);

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am unsure which version of Java I am using, I am using the CodeHS IDE. I am trying to write a function that "fixes the grammar" in a given string. All the method needs to do is replace all of the 2s with to's. Here is my code:

public String useProperGrammar(String text) {
   String fixedString = new String();
for (int i = 0; i < text.length(); i++) {
    fixedString += text.charAt(i);
    if (text.charAt(i) == '2') {

     fixedString = text.substring(0, i) + text.substring(i + 1);

      fixedString += "to";
    }
} return fixedString; }

Body:
If it is a character then convert the char into String and use the replace method.

    char ch = '2';
    String str = Character.toString(ch);
    str = str.replace('2' + "", "to");
    System.out.println(str);


问:
Trying to stop a single thread out of multiple running at the same time in java
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

```<code>public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}
</code>```

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

```<code>public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}
</code>```

答:
As recommended and demonstrated by Sedric, use JavaFx Animation tools for the counters.

The following one-file mre  demonstrating implementation of counters using two different animation tools.

One uses PauseTransition and uses Timeline, each with its stop button.

(copy-paste the entire code into Timers.java and run)

```<code>import java.io.IOException;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Timers extends Application {

    @Override public void start(final Stage stage) throws IOException {
        VBox root = new VBox(new CounterPane(new TimeLineCounter()), new CounterPane(new PauseTransitionCounter()));
        stage.setScene(new Scene(root));
        stage.show();
    }

    public static void main(final String[] args) { launch(args); }
}

class CounterPane extends HBox{

    private final Counter counter;
    CounterPane(Counter counter) {
        super(5);
        this.counter = counter; //todo: check not null
        Button stopBtn = new Button("Stop");
        stopBtn.setOnAction(e->stop());
        getChildren().addAll(stopBtn, counter);
    }

    void stop(){
        counter.getAnimation().stop();
    }
}

abstract class Counter extends Label {

    protected int count = 0;
    public Counter() {
        setAlignment(Pos.CENTER); setPrefSize(25, 25);
        count();
    }

    abstract void count();
    abstract Animation getAnimation();
}

class TimeLineCounter extends Counter {

    private Timeline timeline;

    @Override
    void count() {

        timeline = new Timeline();
        timeline.setCycleCount(Animation.INDEFINITE);
        final KeyFrame keyFrame = new KeyFrame(
                Duration.seconds(1),
                event -> {  setText(String.valueOf(count++) );  }
                );
        timeline.getKeyFrames().add(keyFrame);
        timeline.play();
    }

    @Override
    Animation getAnimation() {
        return timeline;
    }
}

class PauseTransitionCounter extends Counter {

    private PauseTransition pauseTransition;

    @Override
    void count() {

        pauseTransition = new PauseTransition(Duration.seconds(1));
        pauseTransition.setOnFinished(event ->{
            setText(String.valueOf(count++) );
            pauseTransition.play();
        });
        pauseTransition.play();
    }

    @Override
    Animation getAnimation() {
        return pauseTransition;
    }
}
</code>```

Body:
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}

Body:
As recommended and demonstrated by Sedric, use JavaFx Animation tools for the counters.

The following one-file mre  demonstrating implementation of counters using two different animation tools.

One uses PauseTransition and uses Timeline, each with its stop button.

(copy-paste the entire code into Timers.java and run)

import java.io.IOException;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Timers extends Application {

    @Override public void start(final Stage stage) throws IOException {
        VBox root = new VBox(new CounterPane(new TimeLineCounter()), new CounterPane(new PauseTransitionCounter()));
        stage.setScene(new Scene(root));
        stage.show();
    }

    public static void main(final String[] args) { launch(args); }
}

class CounterPane extends HBox{

    private final Counter counter;
    CounterPane(Counter counter) {
        super(5);
        this.counter = counter; //todo: check not null
        Button stopBtn = new Button("Stop");
        stopBtn.setOnAction(e->stop());
        getChildren().addAll(stopBtn, counter);
    }

    void stop(){
        counter.getAnimation().stop();
    }
}

abstract class Counter extends Label {

    protected int count = 0;
    public Counter() {
        setAlignment(Pos.CENTER); setPrefSize(25, 25);
        count();
    }

    abstract void count();
    abstract Animation getAnimation();
}

class TimeLineCounter extends Counter {

    private Timeline timeline;

    @Override
    void count() {

        timeline = new Timeline();
        timeline.setCycleCount(Animation.INDEFINITE);
        final KeyFrame keyFrame = new KeyFrame(
                Duration.seconds(1),
                event -> {  setText(String.valueOf(count++) );  }
                );
        timeline.getKeyFrames().add(keyFrame);
        timeline.play();
    }

    @Override
    Animation getAnimation() {
        return timeline;
    }
}

class PauseTransitionCounter extends Counter {

    private PauseTransition pauseTransition;

    @Override
    void count() {

        pauseTransition = new PauseTransition(Duration.seconds(1));
        pauseTransition.setOnFinished(event ->{
            setText(String.valueOf(count++) );
            pauseTransition.play();
        });
        pauseTransition.play();
    }

    @Override
    Animation getAnimation() {
        return pauseTransition;
    }
}


问:
How to pass props from html div to the function component in react?
Don't know how to pass properties from html into react file.
This is the existing code,

```<code><html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<body>

<div id="mydiv" parm="some info"></div>
<script type="text/babel" src="h2.js"></script>

</body>
</html>
</code>```

The react file, i'm manually sending props "parm={2}" for now.

```<code>const Hello = (props) => {
        console.log(props);
        return (<h2>h2 with function component {props.parm}</h2>);
}

ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));
</code>```

My Q is, how to pass parm from html to Hello() component ?
Pls note, i have to turn off CORS for local testing,
https://alfilatov.com/posts/run-chrome-without-cors/

答:
React is not designed to behave in that way, HTML div you are using is the root element and all component is going to render in that. so you can not pass. but in first place why you want to do that. there are other ways to use global values inside of react component.

Not ideal solution but you can use global scope to get the value inside, or else create separate service to store values and then import that inside react component.

Body:
Don't know how to pass properties from html into react file.
This is the existing code,

The react file, i'm manually sending props "parm={2}" for now.

const Hello = (props) => {
        console.log(props);
        return (
h2 with function component {props.parm}
);
}

ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));

My Q is, how to pass parm from html to Hello() component ?
Pls note, i have to turn off CORS for local testing,
https://alfilatov.com/posts/run-chrome-without-cors/


问:
Do you believe the Firefox project should be forked into a developer targeted version?
I've just got this idea that there is a need for a forked version of Firefox that would provide right out of the box tools for web development. Like FireBug, YSlow, FireCookie, LiveHTTPHeaders, etc.

Maybe the fork should only include those extensions or take a further step and implement them in existing chrome.

The reason I'm thinking about this is that right now I have two Firefox profiles. A "browsing" one which has only one extension and a "development" one which has lots and lots of extensions. The advantage is obviously that the former is faster than the latter. Maybe if aimed from the beginning at developers, a forked version would bring some speed improvements and other niceties.

What do you think? Any volunteers?

答: I fear that pulling mentioned extensions into an official, maybe even Mozilla-branded, distribution would cause a slowdown in the development of those extensions because their authors would have to worry about coordinating their development with the provider of the browser distribution.</p>

OwnerDisplayName: Ionut G. Stan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: hillu


问:
Handling device communication and GUI updates separately in C#
I'm developing an application that scans images from connected scanners on well defined time intervals, say every 5 minutes, for a specified amount of time. While my app is running I have a label (timerlabel) counting down the total time of the project left, and this is handled by a DispatcherTimer which updates the label every second.

The scanners are handled by another DispatcherTimer which every five minutes will call a function Scan() for each scanner. When this function is called the scanning starts, but the GUI stops updating, and the timerlabel freezes for the duration of the scan. When it starts again it just keeps counting down, not having registered the time that elapsed when the scanning was in progress.

How can I make the timerlabel keep running while the scanning is in progress?

答: Although not being sure to get the full story I would try to start your Scan() method by a BackgroundWorker, which has support for progress metering via delegates baked in, created when the corresponding DispatchTimer() has fired.

ContentLicense: CC BY-SA 3.0


问:
Laravel - Eloquent Relationship not working One to Many relationship
I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Products Table

```<code>Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
</code>```

Categories Table

```<code>Table name = categories
PrimaryKey = cat_id
</code>```

Products Model Code

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class productsModel extends Model
{
    //code...
    protected $table      = 'products';
    protected $primaryKey = 'pro_id';

    // Every Products Belongs To One Category

    public function category()
    {
        # code...
        return $this->belongsTo('APP\abcModel','cat_id');
    }
}
</code>```

Categories Model Code

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    //code...
    protected $table      = 'categories';
    protected $primaryKey = 'cat_id';

    // One Category Has Many Products

    public function products()
    {
        # code...
        return $this->hasMany('App\productsModel','cat_id','pro_id');
    }
}
</code>```

Controller Code

namespace App\Http\Controllers;

```<code>use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
    //code...
    public function products($category_id='')
    {
        # code...
        $data["products"] = productsModel::where
                            ('cat_id',$category_id)
                            ->get();
        $data["categories"] = productsModel::where
                            ('cat_id',$category_id)->first()->category;
        echo "```";
        print_r($data);
        echo "```";
    }
}
</code>```

ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found

答:
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:

```<code>public function category()
{
    # code...
    return $this->belongsTo('App\categoryModel','cat_id');
}
</code>```

Also a sincere request, as @alithedeveloper mentioned please follow PSR standards for writing code.

Body:
I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Products Table

Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id

Categories Table

Table name = categories
PrimaryKey = cat_id

Products Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class productsModel extends Model
{
    //code...
    protected $table      = 'products';
    protected $primaryKey = 'pro_id';

    // Every Products Belongs To One Category

    public function category()
    {
        # code...
        return $this->belongsTo('APP\abcModel','cat_id');
    }
}

Categories Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    //code...
    protected $table      = 'categories';
    protected $primaryKey = 'cat_id';

    // One Category Has Many Products

    public function products()
    {
        # code...
        return $this->hasMany('App\productsModel','cat_id','pro_id');
    }
}

Controller Code

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
    //code...
    public function products($category_id='')
    {
        # code...
        $data["products"] = productsModel::where
                            ('cat_id',$category_id)
                            ->get();
        $data["categories"] = productsModel::where
                            ('cat_id',$category_id)->first()->category;
        echo "
";
        print_r($data);
        echo "
";
    }
}

ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found

Body:
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:

public function category()
{
    # code...
    return $this->belongsTo('App\categoryModel','cat_id');
}

Also a sincere request, as @alithedeveloper mentioned please follow PSR standards for writing code.


问:
Python regular expression to find all occurences of a string with multiple variations
I'm having trouble finding the appropriate regex pattern to that will match each variation of the following:

```<code>regular expression
regular-expression
regular:expression
regular&expression
</code>```

I am provided with the following string which I would need to use the findall() method to match each occurence listed above:

```<code>str="This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression"
</code>```

答:
This is done by:</p>

```<code>import re
search_string='''This is a string to search for a regular expression like regular
expression or
regular-expression or regular:expression or regular&expression'''
results1 = re.sub ("regular[ -:&]expression","regular expression", search_string)
print (results1)
</code>```

Body:
I'm having trouble finding the appropriate regex pattern to that will match each variation of the following:

regular expression
regular-expression
regular:expression
regular&expression

I am provided with the following string which I would need to use the findall() method to match each occurence listed above:

str="This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression"

Body:
This is done by:

import re
search_string='''This is a string to search for a regular expression like regular
expression or
regular-expression or regular:expression or regular&expression'''
results1 = re.sub ("regular[ -:&]expression","regular expression", search_string)
print (results1)


问:
Finding most frequency number in array
By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.

```<code>class FindingMostFrequencyOccur {

    public static void main(String args[]) {
        int A[] = { 1, 2, 3, 3, 1, 3, 1};
        int M = 3; // Maximum Number in Array
        int result = findFrequency(M, A);
        System.out.println("Result "+result);
    }

    static int findFrequency(int M, int[] A) {
        int N = A.length;
        int[] count = new int[M + 1];
        for (int i = 0; i <= M; i++)
            count[i] = 0;
        int maxOccurence = 1;
        int index = -1;
        for (int i = 0; i < N; i++) {
            if (count[A[i]] > 0) {
                int tmp = count[A[i]];
                if (tmp > maxOccurence) {
                    maxOccurence = tmp;
                    index = i;
                }
                count[A[i]] = tmp + 1;
            } else {
                count[A[i]] = 1;
            }
        }
        return A[index];
    }
}
</code>```

Can you we improve in this line

```<code>if (count[A[i]] > 0) {
                    int tmp = count[A[i]];
                    if (tmp > maxOccurence) {
                        maxOccurence = tmp;
                        index = i;
                    }
                    count[A[i]] = tmp + 1;
                } else {
                    count[A[i]] = 1;
                }
</code>```

答:
In this logic, you take each element of the array, and find the number of times it is repeated to the right of it, in the array. This is given by local_frequency. If this happens to be more than max_frequency, then this number at arr[i] is stored in number, and then max_frequency stores local_frequency

```<code>public static void main(String[] args)
{
    int[] arr = {1, 2, 3, 4, 3, 2, 1, 5, 5, 5, 4, 4, 3, 4};
    int result = findMostFrequent(arr);
    System.out.println(result + " is the most frequent number");
}

public static int findMostFrequent(int[] arr)
{
    int number = arr[0];
    int maxFrequency = 0;

    for(int i =0 ; i < arr.length; i++)
    {
        int local_frequency = 0;
        for(int j = i; j < arr.length; j++)
        {
            if(arr[i] == arr[j])
            local_frequency++;
        }

        if(local_frequency > maxFrequency)
        {
            number = arr[i];
            maxFrequency = local_frequency;
        }
    }

    return number;
}
</code>```

Title: Finding most frequency number in array

Body:
By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.

class FindingMostFrequencyOccur {

    public static void main(String args[]) {
        int A[] = { 1, 2, 3, 3, 1, 3, 1};
        int M = 3; // Maximum Number in Array
        int result = findFrequency(M, A);
        System.out.println("Result "+result);
    }

    static int findFrequency(int M, int[] A) {
        int N = A.length;
        int[] count = new int[M + 1];
        for (int i = 0; i <= M; i++)
            count[i] = 0;
        int maxOccurence = 1;
        int index = -1;
        for (int i = 0; i < N; i++) {
            if (count[A[i]] > 0) {
                int tmp = count[A[i]];
                if (tmp > maxOccurence) {
                    maxOccurence = tmp;
                    index = i;
                }
                count[A[i]] = tmp + 1;
            } else {
                count[A[i]] = 1;
            }
        }
        return A[index];
    }
}

Can you we improve in this line

if (count[A[i]] > 0) {
                    int tmp = count[A[i]];
                    if (tmp > maxOccurence) {
                        maxOccurence = tmp;
                        index = i;
                    }
                    count[A[i]] = tmp + 1;
                } else {
                    count[A[i]] = 1;
                }

Body:
In this logic, you take each element of the array, and find the number of times it is repeated to the right of it, in the array. This is given by local_frequency. If this happens to be more than max_frequency, then this number at arr[i] is stored in number, and then max_frequency stores local_frequency

public static void main(String[] args)
{
    int[] arr = {1, 2, 3, 4, 3, 2, 1, 5, 5, 5, 4, 4, 3, 4};
    int result = findMostFrequent(arr);
    System.out.println(result + " is the most frequent number");
}

public static int findMostFrequent(int[] arr)
{
    int number = arr[0];
    int maxFrequency = 0;

    for(int i =0 ; i < arr.length; i++)
    {
        int local_frequency = 0;
        for(int j = i; j < arr.length; j++)
        {
            if(arr[i] == arr[j])
            local_frequency++;
        }

        if(local_frequency > maxFrequency)
        {
            number = arr[i];
            maxFrequency = local_frequency;
        }
    }

    return number;
}


问:
Exclude jQuery From Specific Div Using CSS
The site uses this js which breaks the search-form input fields added within the site-branding div

```<code>/**
 * Remove all off-canvas states
 */
 function removeAllFocusStates() {
    'use strict';

    var siteBranding = document.getElementsByClassName('site-branding')[0];
    var getFocusedElements = siteBranding.querySelectorAll(':hover, :focus, :focus-within');
    var getFocusedClassElements = siteBranding.querySelectorAll('.is-focused');
    var i;
    var o;

    for (i = 0; i < getFocusedElements.length; i++) {
        getFocusedElements[i].blur();
    }

    for (o = 0; o < getFocusedClassElements.length; o++) {
        deleteClass(getFocusedClassElements[o], 'is-focused');
    }
}
</code>```

Here's the HTML output for the site-branding container

```<code><div class="site-branding">
    <form role="search" method="get" class="search-form" action="http://dev.local/">
        <label>
            <span class="screen-reader-text">Search for:</span>
            <input type="search" class="search-field" placeholder="Search …" value="" name="s" />
        </label>
        <input type="submit" class="search-submit" value="Search" />
    </form>
</div>
</code>```

Update : Here's the removeAllFocusStates() function in use which needs modifying to exclude the search-form

```<code>  ...
  document.addEventListener('click', function(event) {

      // Remove all focused menu states when clicking outside site branding
      if (event.target !== document.getElementsByClassName('site-branding')[0]) {
          removeAllFocusStates();
      } else {
          // nothing
      }

  }, false);
}
</code>```

Users cannot enter text in the search input field because the js is modifying default input field.

Is there a way to use CSS to fix this so it doesn't apply to the search-form input field added within the site-branding div within the header?

Otherwise, is there a way to modify the js so it doesn't effect the search-form?

I did search the similar questions however couldn't find anything which applies specifically to this problem.

答:
CSS solution may not preferable in this case. It is because the problem is that event.target returns the clicked element (the input field) instead of the parent. So event.target !== document.getElementsByClassName('site-branding')[0] would not return true when you click on the input field inside .site-branding.

I suggest add the EventListener to .site-branding element, and watch if the clicked element has parent .search-form.

```<code>document.getElementsByClassName('site-branding')[0].addEventListener('click', function(event) {

  // Value of event.target would be the input field but not the parent.
  // So if you want to exclude element inside a specific parent,
  // try to select the target's parent.

  if (event.target.closest('.search-form') === null){
    removeAllFocusStates();
  } else {

  }
}, false);
</code>```

Body:
The site uses this js which breaks the search-form input fields added within the site-branding div

/**
 * Remove all off-canvas states
 */
 function removeAllFocusStates() {
    'use strict';

    var siteBranding = document.getElementsByClassName('site-branding')[0];
    var getFocusedElements = siteBranding.querySelectorAll(':hover, :focus, :focus-within');
    var getFocusedClassElements = siteBranding.querySelectorAll('.is-focused');
    var i;
    var o;

    for (i = 0; i < getFocusedElements.length; i++) {
        getFocusedElements[i].blur();
    }

    for (o = 0; o < getFocusedClassElements.length; o++) {
        deleteClass(getFocusedClassElements[o], 'is-focused');
    }
}

Here's the HTML output for the site-branding container

    <form role="search" method="get" class="search-form" action="http://dev.local/">

            Search for:
            <input type="search" class="search-field" placeholder="Search …" value="" name="s" />

        <input type="submit" class="search-submit" value="Search" />
    </form>

Update : Here's the removeAllFocusStates() function in use which needs modifying to exclude the search-form

  ...
  document.addEventListener('click', function(event) {

      // Remove all focused menu states when clicking outside site branding
      if (event.target !== document.getElementsByClassName('site-branding')[0]) {
          removeAllFocusStates();
      } else {
          // nothing
      }

  }, false);
}

Users cannot enter text in the search input field because the js is modifying default input field.

Is there a way to use CSS to fix this so it doesn't apply to the search-form input field added within the site-branding div within the header?

Otherwise, is there a way to modify the js so it doesn't effect the search-form?

I did search the similar questions however couldn't find anything which applies specifically to this problem.

Body:
CSS solution may not preferable in this case. It is because the problem is that event.target returns the clicked element (the input field) instead of the parent. So event.target !== document.getElementsByClassName('site-branding')[0] would not return true when you click on the input field inside .site-branding.

I suggest add the EventListener to .site-branding element, and watch if the clicked element has parent .search-form.

document.getElementsByClassName('site-branding')[0].addEventListener('click', function(event) {

  // Value of event.target would be the input field but not the parent.
  // So if you want to exclude element inside a specific parent,
  // try to select the target's parent.

  if (event.target.closest('.search-form') === null){
    removeAllFocusStates();
  } else {

  }
}, false);


问:
SCNText rendering without curves, not font-like
When I run this SceneKit code:

```<code>let txt = SCNText(string: "Hello", extrusionDepth: 0.2)
let textNode = SCNNode(geometry: txt)
scene.rootNode.addChildNode(textNode)
</code>```

I get very angular text:

It seems to do this regardless of font and it behaves the same way on a device as in the simulator.

Here's the code in context:

```<code>    // create a new scene
    let scene = SCNScene()

    // create and add a camera to the scene
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene.rootNode.addChildNode(cameraNode)

    // place the camera
    cameraNode.position = SCNVector3(x: 10, y: 0, z: 75)

    // create and add a light to the scene
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light!.type = SCNLightTypeOmni
    lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
    scene.rootNode.addChildNode(lightNode)

    // create and add an ambient light to the scene
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = SCNLightTypeAmbient
    ambientLightNode.light!.color = UIColor.darkGrayColor()
    scene.rootNode.addChildNode(ambientLightNode)

    let txt = SCNText(string: "Hello", extrusionDepth: 0.2)

    let textNode = SCNNode(geometry: txt)
    scene.rootNode.addChildNode(textNode)

    // retrieve the SCNView
    let scnView = self.view as! SCNView

    // set the scene to the view
    scnView.scene = scene
</code>```

答:
My solution was using big font as @mnuages was suggested then using scale on the text node with

```<code>     animatedTextNode.scale = SCNVector3(0.1, 0.1, 0.1)
</code>```

to get what size I wanted.

In that case when you animate text and when it comes closer to the camera it looks smooth.

Body:
When I run this SceneKit code:

let txt = SCNText(string: "Hello", extrusionDepth: 0.2)
let textNode = SCNNode(geometry: txt)
scene.rootNode.addChildNode(textNode)

I get very angular text:

It seems to do this regardless of font and it behaves the same way on a device as in the simulator.

Here's the code in context:

    // create a new scene
    let scene = SCNScene()

    // create and add a camera to the scene
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene.rootNode.addChildNode(cameraNode)

    // place the camera
    cameraNode.position = SCNVector3(x: 10, y: 0, z: 75)

    // create and add a light to the scene
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light!.type = SCNLightTypeOmni
    lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
    scene.rootNode.addChildNode(lightNode)

    // create and add an ambient light to the scene
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = SCNLightTypeAmbient
    ambientLightNode.light!.color = UIColor.darkGrayColor()
    scene.rootNode.addChildNode(ambientLightNode)

    let txt = SCNText(string: "Hello", extrusionDepth: 0.2)

    let textNode = SCNNode(geometry: txt)
    scene.rootNode.addChildNode(textNode)

    // retrieve the SCNView
    let scnView = self.view as! SCNView

    // set the scene to the view
    scnView.scene = scene

Body:
My solution was using big font as @mnuages was suggested then using scale on the text node with

     animatedTextNode.scale = SCNVector3(0.1, 0.1, 0.1)

to get what size I wanted.

In that case when you animate text and when it comes closer to the camera it looks smooth.


问:
python override a api class method with different name
first, create my own class object inherit the api

```<code>class mainobject1(XAPI):
    def __init__(self):
        XAPI.__init__(self)
        self.count = 0
        # built-in to run api
        self.run()
    # default api method name
    def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.count += 1
</code>```

this allows me to access self.count in "error" method, but is it possible to direct the API method "error" to other specific name like "xapi_error"? there are few api in my program so I wanna declare them clearly.
i simply do not want self.error be accessible in mainobject class.

so, create an api object separately

```<code>class myapi(XAPI):
    def __init__(self):
        XAPI.__init__(self)
    # default api method name
    def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        # self.count += 1 # not working here
class mainobject2():
    def __init__(self):
        self.api = myapi()
        self.count = 0
        # built-in to run api
        self.api.run()
</code>```

this approach won't have naming issue but not straight-forward to access to my own class variable self.count.

Then I tried the followings:

```<code>......
class mainobject2():
    ......
    # Failed approach
    @self.api.error # <------ ERROR
    def xapi_error(self, regId, errorCode, errorString):
        ......
</code>```

NameError: name 'self' is not defined

i had some success with this @ approach long ago but forget what it is and how to use it...

```<code>......
import ctypes
class mainobject2():
    # Failed approach
    def RegCallback(self):
        def xapi_error(None, regId, errorCode, errorString):
            ......
        self.xapi_ErrorAddr = PYFUNCTYPE(None, c_char_p)(xapi_error)
        self.app.error(self.xapi_ErrorAddr) # <------ ERROR
</code>```

TypeError: error() missing 2 required positional arguments: 'errorCode' and 'errorString'

i am able to use ctypes to map the dll callback to my class...I wonder if there is something similar for python callback...

Ultimately, my structure:

```<code>mainobject(self)
├── objectx (self)
│      └── xapi
├── objecty (self)
│      └── yapi
......
</code>```

self params shares with each other so can be accessed everywhere. so i hope, inside a thread code, it will be :

```<code>import XAPI
......
class objectx():
    def __init__(self):
        self.xapi = myxapi()
        self.xcount = 0
        # built-in to run api
        self.xapi.run()
    # answer to this question
    ......
    # then finally
    def xapi_error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.xcount += 1
    ......
</code>```

答:
Can you handle the first error() call with the inputs?

Then you can do something like:

```<code>def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.count += 1 # you can remove this and put it in another function
        if errorCode == 1: # whatever the error codes are
            self.xapi_error(.....)
        elif errorCode == 2:
            self.app_error(....)
        else:
            super().error(....)

def xapi_error(....):
    pass

def app_error(...):
    pass
</code>```

Is this what you were looking for?

If you don't call the

```<code>super().error(...)
</code>```

in your error function, it will not call the overridden method.

Body:
first, create my own class object inherit the api

class mainobject1(XAPI):
    def __init__(self):
        XAPI.__init__(self)
        self.count = 0
        # built-in to run api
        self.run()
    # default api method name
    def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.count += 1

this allows me to access self.count in "error" method, but is it possible to direct the API method "error" to other specific name like "xapi_error"? there are few api in my program so I wanna declare them clearly.
i simply do not want self.error be accessible in mainobject class.

so, create an api object separately

class myapi(XAPI):
    def __init__(self):
        XAPI.__init__(self)
    # default api method name
    def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        # self.count += 1 # not working here
class mainobject2():
    def __init__(self):
        self.api = myapi()
        self.count = 0
        # built-in to run api
        self.api.run()

this approach won't have naming issue but not straight-forward to access to my own class variable self.count.

Then I tried the followings:

......
class mainobject2():
    ......
    # Failed approach
    @self.api.error # <------ ERROR
    def xapi_error(self, regId, errorCode, errorString):
        ......

NameError: name 'self' is not defined

i had some success with this @ approach long ago but forget what it is and how to use it...

......
import ctypes
class mainobject2():
    # Failed approach
    def RegCallback(self):
        def xapi_error(None, regId, errorCode, errorString):
            ......
        self.xapi_ErrorAddr = PYFUNCTYPE(None, c_char_p)(xapi_error)
        self.app.error(self.xapi_ErrorAddr) # <------ ERROR

TypeError: error() missing 2 required positional arguments: 'errorCode' and 'errorString'

i am able to use ctypes to map the dll callback to my class...I wonder if there is something similar for python callback...

Ultimately, my structure:

mainobject(self)
├── objectx (self)
│      └── xapi
├── objecty (self)
│      └── yapi
......

self params shares with each other so can be accessed everywhere. so i hope, inside a thread code, it will be :

import XAPI
......
class objectx():
    def __init__(self):
        self.xapi = myxapi()
        self.xcount = 0
        # built-in to run api
        self.xapi.run()
    # answer to this question
    ......
    # then finally
    def xapi_error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.xcount += 1
    ......

Body:
Can you handle the first error() call with the inputs?

Then you can do something like:

def error(self, regId, errorCode, errorString):
        print("Error:", errorCode)
        self.count += 1 # you can remove this and put it in another function
        if errorCode == 1: # whatever the error codes are
            self.xapi_error(.....)
        elif errorCode == 2:
            self.app_error(....)
        else:
            super().error(....)

def xapi_error(....):
    pass

def app_error(...):
    pass

Is this what you were looking for?

If you don't call the

super().error(...)

in your error function, it will not call the overridden method.


问:
Which design pattern to use for a 2D iPhone game?
To give a little background about the game: falling items float from the top, and the objective is to flick/slide another object to hit them. If an item hits the ground, you lose a life, and gain points for hitting falling items.

Here is where I'm a little confused. In O'Reilly's iPhone game development. They state have the AppDelegate inherit a game state machine object, and have the main game loop in the App Delegate. Nothing about MVC.

I was going to use MVC. I have all the objects identified for the models, and was going to use one controller to update each model and their corresponding view. Then have a navigation controller in the App Delegate, and push certain controllers (Play, instructions, stats) from the home screen. Then have the game loop run in my gameViewController. I am using Chipmunk as a physics engine by the way.

This is my first game so I'm little confused. I would greatly appreciate any advice on how to proceed. I would like to get the object orientated design right from the start before jumping into code.

答:
I don't think MVC is really what you want here. MVC could apply to your overall application state - ie a view for the menu, a view for the gameboard etc. It doesn't fit well WITHIN the game play - at least just thinking off the top of my head.

Take a look at this post on gameDev. Lots of useful patterns from people smarter about this than I.

https://gamedev.stackexchange.com/questions/4157/what-are-some-programming-design-patterns-that-are-useful-in-game-development


问:
vuejs typescript property router does not exist
I try to access router in my typescript class component:

```<code>import {Vue} from 'vue-property-decorator'
import Component from 'nuxt-class-component'
import {Getter, Action} from 'vuex-class'

@Component
export default class Login extends Vue {
    @Action login

    username = ''
    password = ''

    async submit () {
        await this.login({username: this.username, password: this.password})
        this.$router.push('/results')
    }
}
</code>```

Unfortunately, I get:

```<code>error TS2339: Property '$router' does not exist on type 'Login'.
</code>```

答:
other answer don't work for me

but the code below works

```<code>import Vue from 'vue';

import VueRouter from 'vue-router';

...
  public rowClick(row: object, column: object, event: object): void {
      console.log(row, column, event);
      this.$router.push('/login');
  }
...
</code>```

Body:
I try to access router in my typescript class component:

import {Vue} from 'vue-property-decorator'
import Component from 'nuxt-class-component'
import {Getter, Action} from 'vuex-class'

@Component
export default class Login extends Vue {
    @Action login

    username = ''
    password = ''

    async submit () {
        await this.login({username: this.username, password: this.password})
        this.$router.push('/results')
    }
}

Unfortunately, I get:

error TS2339: Property '$router' does not exist on type 'Login'.

Body:
other answer don't work for me

but the code below works

import Vue from 'vue';

import VueRouter from 'vue-router';

...
  public rowClick(row: object, column: object, event: object): void {
      console.log(row, column, event);
      this.$router.push('/login');
  }
...


问:
Virtual destructor with virtual members in C++11
In these slides about C++11/14 standard, on slide 15, the author writes that "many classic coding rules [are] no longer applicable" in C++11. He proposes a list of three examples, and I agree with the Rule of Three and the memory management.

However his second example is "Virtual destructor with virtual members" (just that). What does it mean? I know one must declare as virtual the base class destructor in order to call the right destructor if we have something like

```<code>Base *b = new Derived;
...
delete b;
</code>```

This is well explained here: When to use virtual destructors?

But is it useless now in C++11 to declare virtual your destructor if you have virtual members?

答:
To answer the specific question...

But is it useless now in C++11 to declare virtual your destructor if you have virtual members?

The need for a virtual destructor has NOT changed in the C++11 core language. You must declare your destructor as virtual if you are deleting the derived object using the base pointer.

The statement in the slide gives the impression that somehow C++11 has changed the behavior with respect to virtual destructor - which is not the case. As the author has clarified, it's only applicable when using a shared_ptr. But the fact that a virtual destructor is still required (except with the use shared_ptr) gets diluted in the long explanation.

Body:
In these slides about C++11/14 standard, on slide 15, the author writes that "many classic coding rules [are] no longer applicable" in C++11. He proposes a list of three examples, and I agree with the Rule of Three and the memory management.

However his second example is "Virtual destructor with virtual members" (just that). What does it mean? I know one must declare as virtual the base class destructor in order to call the right destructor if we have something like

Base *b = new Derived;
...
delete b;

This is well explained here: When to use virtual destructors?

But is it useless now in C++11 to declare virtual your destructor if you have virtual members?


问:
Error: ModuleNotFoundError: No module named 'MySQLdb'
I want to create SQL tables for json data usign python 3 google colab.
Here is the code:

```<code>from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import create_engine

total_data = [
    {
        "fields": {
            "bkdate": None,
            "business_credit_card_total_balances": None,
            "business_credit_card_total_limits": None,
            "business_total_monthly_debt_payments": None,
            "business_total_mortgage_monthly_payments": None,
            "created_at": "2016-08-04T00:29:03.067Z",
            "detail_results": None,
            "error_reason": "no reasons",
            "fico_v2": "695",
            "fico_v3": None,
            "loanapp_id": 194,
            "personal_credit_card_total_balances": None,
            "personal_credit_card_total_limits": None,
            "personal_total_monthly_payments": None,
            "report_type": "CreditProfile",
            "result": True,
            "role": "applicant",
            "total_mortgage_monthly_payments": None,
            "username": "cho",
            "version": "CF Microloan"
            },
        "model": "common.prequalresult",
        "pk": 1
    }
]

engine = create_engine('mysql://user:password@localhost:5432/my_data', echo=False)

Base = declarative_base()

class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    pk = Column(Integer, primary_key=False)
    model = Column(String(100), nullable=True)
    child = relationship('Comment', backref='article', uselist=False)

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True, autoincrement=True)
    bkdate = Column(String(100), nullable=True)
    business_credit_card_total_balances = Column(Integer, nullable=True)
    business_credit_card_total_limits = Column(Integer, nullable=True)
    business_total_monthly_debt_payments= Column(Integer, nullable=True)
    business_total_mortgage_monthly_payments= Column(Integer, nullable=True)
    detail_resultsColumn(String(100), nullable=True)
    created_at = Column(String(100), nullable=True)
    error_reason = Column(String(100), nullable=True)
    fico_v2= Column(String(100), nullable=True)
    fico_v3= Column(String(100), nullable=True)
    loanapp_id= Column(Integer, nullable=True)
    personal_credit_card_total_balances= Column(Integer, nullable=True)
    personal_credit_card_total_limits= Column(Integer, nullable=True)
    personal_total_monthly_payments= Column(Integer, nullable=True)
    report_type= Column(String(100), nullable=True)
    result= Column(Integer, nullable=True)
    role= Column(String(100), nullable=True)
    total_mortgage_monthly_payments= Column(Integer, nullable=True)
    username= Column(String(100), nullable=True)
    version= Column(String(100), nullable=True)
    article_id = Column(Integer, ForeignKey('article.id'))

x = Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

for temp_data in total_data:
    pk = temp_data['pk']
    model = temp_data['model']
    bkdate = temp_data['fields']['bkdate']
    business_credit_card_total_balances = temp_data['fields']['business_credit_card_total_balances']
    created_at = temp_data['fields']['created_at']
    business_credit_card_total_limits = temp_data['fields']['business_credit_card_total_limits']
    business_total_monthly_debt_payments = temp_data['fields']['business_total_monthly_debt_payments']
    business_total_mortgage_monthly_payments = temp_data['fields']['business_total_mortgage_monthly_payments']
    detail_resultsColumn = temp_data['fields']['detail_resultsColumn']
    error_reason = temp_data['fields']['error_reason']
    fico_v2 = temp_data['fields']['fico_v2']
    fico_v3 = temp_data['fields']['fico_v3']
    loanapp_id = temp_data['fields']['loanapp_id']
    personal_credit_card_total_balances = temp_data['fields']['personal_credit_card_total_balances']
    personal_credit_card_total_limits = temp_data['fields']['personal_credit_card_total_limits']
    personal_total_monthly_payments = temp_data['fields']['personal_total_monthly_payments']
    report_type = temp_data['fields']['report_type']
    result = temp_data['fields']['result']
    role = temp_data['fields']['role']
    total_mortgage_monthly_payments = temp_data['fields']['total_mortgage_monthly_payments']
    username= temp_data['fields']['username']
    version = temp_data['fields']['version']
    article_id = temp_data['fields']['article_id']

    parent1 = Article(pk=temp_data['pk'], model=model)
    child = Comment(bkdate=bkdate,
                    business_credit_card_total_balances=business_credit_card_total_balances,
                    created_at=created_at,
                    business_credit_card_total_limits=business_credit_card_total_limits,
                    business_total_monthly_debt_payments=business_total_monthly_debt_payments,
                    business_total_mortgage_monthly_payments=business_total_mortgage_monthly_payments,
                    detail_resultsColumn=detail_resultsColumn,
                    error_reason=error_reason,
                    fico_v2=fico_v2,
                    fico_v3=fico_v3,
                    loanapp_id=loanapp_id,
                    personal_credit_card_total_balances=personal_credit_card_total_balances,
                    personal_credit_card_total_limits=personal_credit_card_total_limits,
                    personal_total_monthly_payments=personal_total_monthly_payments,
                    report_type=report_type,
                    result=result,
                    role=role,
                    total_mortgage_monthly_payments=total_mortgage_monthly_payments,
                    username=username,
                    version=version,
                    article_id=article_id,
                    article=parent1)

    session.add(parent1)
    session.add(child)

session.commit()
</code>```

It shows the error when I execute the code above: ModuleNotFoundError: No module named 'MySQLdb' .
  The code include the data and using SQLAlchemy ORM to create tables. Does anyone has another method to create SQL tables for the data?

I installed the module using :

```<code>!pip install PyMySQL
</code>```

I do not know how to fix it.Can someone help with it?

答:
Here's an example how to use mysql in colab.

You can adapt it to your problem. It use PyMySQL instead of MySQLdb.

# install, set connection
!apt-get install mysql-server > /dev/null
!service mysql start
!mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'"
!pip -q install PyMySQL
%load_ext sql
%config SqlMagic.feedback=False
%config SqlMagic.autopandas=True
%sql mysql+pymysql://root:root@/
# query using %sql or %%sql
df = %sql SELECT Host, User, authentication_string FROM mysql.user
df
```

Body:
I want to create SQL tables for json data usign python 3 google colab.
Here is the code:

from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import create_engine

total_data = [
    {
        "fields": {
            "bkdate": None,
            "business_credit_card_total_balances": None,
            "business_credit_card_total_limits": None,
            "business_total_monthly_debt_payments": None,
            "business_total_mortgage_monthly_payments": None,
            "created_at": "2016-08-04T00:29:03.067Z",
            "detail_results": None,
            "error_reason": "no reasons",
            "fico_v2": "695",
            "fico_v3": None,
            "loanapp_id": 194,
            "personal_credit_card_total_balances": None,
            "personal_credit_card_total_limits": None,
            "personal_total_monthly_payments": None,
            "report_type": "CreditProfile",
            "result": True,
            "role": "applicant",
            "total_mortgage_monthly_payments": None,
            "username": "cho",
            "version": "CF Microloan"
            },
        "model": "common.prequalresult",
        "pk": 1
    }
]

engine = create_engine('mysql://user:password@localhost:5432/my_data', echo=False)

Base = declarative_base()

class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    pk = Column(Integer, primary_key=False)
    model = Column(String(100), nullable=True)
    child = relationship('Comment', backref='article', uselist=False)

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True, autoincrement=True)
    bkdate = Column(String(100), nullable=True)
    business_credit_card_total_balances = Column(Integer, nullable=True)
    business_credit_card_total_limits = Column(Integer, nullable=True)
    business_total_monthly_debt_payments= Column(Integer, nullable=True)
    business_total_mortgage_monthly_payments= Column(Integer, nullable=True)
    detail_resultsColumn(String(100), nullable=True)
    created_at = Column(String(100), nullable=True)
    error_reason = Column(String(100), nullable=True)
    fico_v2= Column(String(100), nullable=True)
    fico_v3= Column(String(100), nullable=True)
    loanapp_id= Column(Integer, nullable=True)
    personal_credit_card_total_balances= Column(Integer, nullable=True)
    personal_credit_card_total_limits= Column(Integer, nullable=True)
    personal_total_monthly_payments= Column(Integer, nullable=True)
    report_type= Column(String(100), nullable=True)
    result= Column(Integer, nullable=True)
    role= Column(String(100), nullable=True)
    total_mortgage_monthly_payments= Column(Integer, nullable=True)
    username= Column(String(100), nullable=True)
    version= Column(String(100), nullable=True)
    article_id = Column(Integer, ForeignKey('article.id'))

x = Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

for temp_data in total_data:
    pk = temp_data['pk']
    model = temp_data['model']
    bkdate = temp_data['fields']['bkdate']
    business_credit_card_total_balances = temp_data['fields']['business_credit_card_total_balances']
    created_at = temp_data['fields']['created_at']
    business_credit_card_total_limits = temp_data['fields']['business_credit_card_total_limits']
    business_total_monthly_debt_payments = temp_data['fields']['business_total_monthly_debt_payments']
    business_total_mortgage_monthly_payments = temp_data['fields']['business_total_mortgage_monthly_payments']
    detail_resultsColumn = temp_data['fields']['detail_resultsColumn']
    error_reason = temp_data['fields']['error_reason']
    fico_v2 = temp_data['fields']['fico_v2']
    fico_v3 = temp_data['fields']['fico_v3']
    loanapp_id = temp_data['fields']['loanapp_id']
    personal_credit_card_total_balances = temp_data['fields']['personal_credit_card_total_balances']
    personal_credit_card_total_limits = temp_data['fields']['personal_credit_card_total_limits']
    personal_total_monthly_payments = temp_data['fields']['personal_total_monthly_payments']
    report_type = temp_data['fields']['report_type']
    result = temp_data['fields']['result']
    role = temp_data['fields']['role']
    total_mortgage_monthly_payments = temp_data['fields']['total_mortgage_monthly_payments']
    username= temp_data['fields']['username']
    version = temp_data['fields']['version']
    article_id = temp_data['fields']['article_id']

    parent1 = Article(pk=temp_data['pk'], model=model)
    child = Comment(bkdate=bkdate,
                    business_credit_card_total_balances=business_credit_card_total_balances,
                    created_at=created_at,
                    business_credit_card_total_limits=business_credit_card_total_limits,
                    business_total_monthly_debt_payments=business_total_monthly_debt_payments,
                    business_total_mortgage_monthly_payments=business_total_mortgage_monthly_payments,
                    detail_resultsColumn=detail_resultsColumn,
                    error_reason=error_reason,
                    fico_v2=fico_v2,
                    fico_v3=fico_v3,
                    loanapp_id=loanapp_id,
                    personal_credit_card_total_balances=personal_credit_card_total_balances,
                    personal_credit_card_total_limits=personal_credit_card_total_limits,
                    personal_total_monthly_payments=personal_total_monthly_payments,
                    report_type=report_type,
                    result=result,
                    role=role,
                    total_mortgage_monthly_payments=total_mortgage_monthly_payments,
                    username=username,
                    version=version,
                    article_id=article_id,
                    article=parent1)

    session.add(parent1)
    session.add(child)

session.commit()

It shows the error when I execute the code above: ModuleNotFoundError: No module named 'MySQLdb' .
  The code include the data and using SQLAlchemy ORM to create tables. Does anyone has another method to create SQL tables for the data?

I installed the module using :

!pip install PyMySQL

I do not know how to fix it.Can someone help with it?


问:
How do you call another process from within a process c#
So basically i have an action or process on a linkedlabel called Refresh. which refreshes a drop down, but i need to then call that from another button which is basically a posting button, but then refreshes the drop down which the linked label refreshes. I think this is simple but i don't know the coding..thanks</p>

```<code>    private void Refresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string connetionString; SqlConnection cnn;
        SqlCommand cmd;
        cmd = new SqlCommand("exec vfpMRUFiles @exec,'365'", cnn);
        cmd.Parameters.AddWithValue("@exec", Exec.Text);
        SqlDataReader sReader = cmd.ExecuteReader();
        while (sReader.Read())
        {
            string MattResult = sReader["MT05"] + " - " + sReader["MT01"];
            comboBox1.Items.Add(MattResult);
        }
    }
</code>```

答:
You can try this:

in your button Clicked event

```<code>private void Button1_Click(object sender, EventArgs e)
{
    //just call the LinkClicked function when your button get clicked
    LinkLabel1_LinkClicked(linkLabel1, new LinkLabelLinkClickedEventArgs(linkLabel1.Links[0], MouseButtons.Left));
}

private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //your code that do the refresh
}
</code>```

another way:

extract your refresh code to a method

```<code>private void RefreshDropDown()
{
    string connetionString; SqlConnection cnn;
    SqlCommand cmd;
    cmd = new SqlCommand("exec vfpMRUFiles @exec,'365'", cnn);
    cmd.Parameters.AddWithValue("@exec", Exec.Text);
    SqlDataReader sReader = cmd.ExecuteReader();
    while (sReader.Read())
    {
        string MattResult = sReader["MT05"] + " - " + sReader["MT01"];
        comboBox1.Items.Add(MattResult);
    }
}
</code>```

and then:

```<code>private void yourbutton_Clicked(object sender, EventArgs e)
{
    RefreshDropDown();
}
</code>```

Body:
So basically i have an action or process on a linkedlabel called Refresh. which refreshes a drop down, but i need to then call that from another button which is basically a posting button, but then refreshes the drop down which the linked label refreshes. I think this is simple but i don't know the coding..thanks

    private void Refresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string connetionString; SqlConnection cnn;
        SqlCommand cmd;
        cmd = new SqlCommand("exec vfpMRUFiles @exec,'365'", cnn);
        cmd.Parameters.AddWithValue("@exec", Exec.Text);
        SqlDataReader sReader = cmd.ExecuteReader();
        while (sReader.Read())
        {
            string MattResult = sReader["MT05"] + " - " + sReader["MT01"];
            comboBox1.Items.Add(MattResult);
        }
    }

Body:
You can try this:

in your button Clicked event

private void Button1_Click(object sender, EventArgs e)
{
    //just call the LinkClicked function when your button get clicked
    LinkLabel1_LinkClicked(linkLabel1, new LinkLabelLinkClickedEventArgs(linkLabel1.Links[0], MouseButtons.Left));
}

private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //your code that do the refresh
}

another way:

extract your refresh code to a method

private void RefreshDropDown()
{
    string connetionString; SqlConnection cnn;
    SqlCommand cmd;
    cmd = new SqlCommand("exec vfpMRUFiles @exec,'365'", cnn);
    cmd.Parameters.AddWithValue("@exec", Exec.Text);
    SqlDataReader sReader = cmd.ExecuteReader();
    while (sReader.Read())
    {
        string MattResult = sReader["MT05"] + " - " + sReader["MT01"];
        comboBox1.Items.Add(MattResult);
    }
}

and then:

private void yourbutton_Clicked(object sender, EventArgs e)
{
    RefreshDropDown();
}


问:
Edit User Data with savechanges modelstate.Isvaild problem
I want to update user details like Firstname, Lastname and date-of-birth. although the ModelState is valid and SaveChanges doesn't work. I got some errors for ModelState which are about password and email fields.
the error about SaveChanges is about confirmpassword partial class I think that's what errors say!

Error = The function evaluation requires all threads to run.
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

here are my files
database UI
database table user with datatype

Registration and password usage

```<code>        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
        {
            bool Status = false;
            string message = "";
            //
            // Model Validation
            if (ModelState.IsValid)
            {

                #region //Email is already Exist

                var isExist = IsEmailExist(user.EmailID);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "ایمیل شما قبلا ثبت شده است");
                    return View(user);
                }
                #endregion

                #region Generate Activation Code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region  Password Hashing
                user.Password = Crypto.Hash(user.Password);
                user.Confirmpassword = Crypto.Hash(user.Confirmpassword); //
                #endregion
                user.IsEmailVerified = false;

                #region Save to Database
                using (sitedatabaseEntities1 dc = new sitedatabaseEntities1())
                {
                    dc.Users.Add(user);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
                    message = "تبریک ثبت نام شما با موفقیت انجام شد. " +
                        " و کد فعال سازی برای شما ارسال گردید به ایمیل:" + user.EmailID;
                    Status = true;
                }
                #endregion
            }
            else
            {
                message = "درخواست نادرست";
            }

            ViewBag.Message = message;
            ViewBag.Status = Status;
            return View(user);
        }

</code>```

profile view() usercontroller.cs

```<code>            public ActionResult profile()
        {
            using (sitedatabaseEntities1 db = new sitedatabaseEntities1())
            {
                int userid = int.Parse(Request.Cookies["userid"].Value);
                return View(db.Users.Where(x => x.UserID == userid).FirstOrDefault());
            }
        }

        [HttpPost]
        public ActionResult profile([Bind(Include = "UserID,FirstName,LastName,DateOfBirth")] User user)
        {
            var message = "";
            if (ModelState.IsValid)
                {
                    if (user != null)
                    {
                        var account = db.Users.Where(a => a.UserID == user.UserID).FirstOrDefault();
                        account.FirstName = user.FirstName;
                        account.LastName = user.LastName;
                        account.DateOfBirth = user.DateOfBirth;
                        db.SaveChanges();
                        message = "اطلاعات با موفیت ویرایش شد.";
                    }
                    else
                    {
                        message = "مشکلی در فرایند ویرایش اطلاعات ایجاد شده است.";
                    }
                }
            ViewBag.Message = message;
            return View();
        }
</code>```

profile.cshtml

```<code>@model projectwebsite.Models.User

 @using (Html.BeginForm())
                                {
                                    @Html.AntiForgeryToken()
                                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                                    @Html.HiddenFor(model => model.UserID)
                                    <small class="text-muted">@Html.LabelFor(model => model.FirstName)</small>
                                    @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "form-text text-danger" })
                                    <hr>
                                    <small class="text-muted">@Html.LabelFor(model => model.LastName)</small>
                                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "form-text text-danger" })
                                    <hr>
                                    <small class="text-muted">@Html.LabelFor(model => model.DateOfBirth)</small>
                                    @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "form-text text-danger" })
                                    <button type="submit" value="Save" class="btn btn-success"> submit</button>
                                    if (ViewBag.Message != null)
                                    {
                                        <div class="alert alert-danger">
                                            <strong>error</strong>@ViewBag.Message
                                        </div>
                                    }
                                }

</code>```

and last file user.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace projectwebsite.Models
{
    [MetadataType(typeof(UserMetadata))]
    public partial class User
    {
        public string Confirmpassword { get; set; }
    }
    public class UserMetadata
    {
        [Display(Name="نام")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "نام خود را وارد کنید.")]
        public string FirstName { get; set; }

        [Display(Name ="نام خانوادگی")]
        [Required(AllowEmptyStrings = false, ErrorMessage ="نام خانوادگی را وارد کنید.")]
        public string LastName { get; set; }

        [Display(Name ="ایمیل")]
        [Required(AllowEmptyStrings = false, ErrorMessage ="ایمیل خود را وارد کنید")]
        [DataType(DataType.EmailAddress)]
        public string EmailID { get; set; }

        [Display(Name = "تاریخ تولد")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime DateOfBirth { get; set; }

        [Display(Name = "پسورد")]
        [Required(AllowEmptyStrings =false, ErrorMessage ="پسورد را وارد کنید.")]
        [DataType(DataType.Password)]
        [MinLength(6,ErrorMessage ="6 حرف کمترین طول پسورد میباشد.")]
        public string Password { get; set; }

        [Display(Name ="تکرار پسورد")]
        [DataType(DataType.Password)]
        [Compare("Password",ErrorMessage ="رمز عبور برابر نیست.")]
        public string Confirmpassword { get; set; }
    }
}
</code>```

答:
I've found an answer here: Entity Framework/MVC3: temporarily disable validation

By temporarily disabling validation I can bypass other properties validation check.

Body:
I want to update user details like Firstname, Lastname and date-of-birth. although the ModelState is valid and SaveChanges doesn't work. I got some errors for ModelState which are about password and email fields.
the error about SaveChanges is about confirmpassword partial class I think that's what errors say!

Error = The function evaluation requires all threads to run.
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

here are my files
database UI
database table user with datatype

Registration and password usage

        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
        {
            bool Status = false;
            string message = "";
            //
            // Model Validation
            if (ModelState.IsValid)
            {

                #region //Email is already Exist

                var isExist = IsEmailExist(user.EmailID);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "ایمیل شما قبلا ثبت شده است");
                    return View(user);
                }
                #endregion

                #region Generate Activation Code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region  Password Hashing
                user.Password = Crypto.Hash(user.Password);
                user.Confirmpassword = Crypto.Hash(user.Confirmpassword); //
                #endregion
                user.IsEmailVerified = false;

                #region Save to Database
                using (sitedatabaseEntities1 dc = new sitedatabaseEntities1())
                {
                    dc.Users.Add(user);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
                    message = "تبریک ثبت نام شما با موفقیت انجام شد. " +
                        " و کد فعال سازی برای شما ارسال گردید به ایمیل:" + user.EmailID;
                    Status = true;
                }
                #endregion
            }
            else
            {
                message = "درخواست نادرست";
            }

            ViewBag.Message = message;
            ViewBag.Status = Status;
            return View(user);
        }

profile view() usercontroller.cs

            public ActionResult profile()
        {
            using (sitedatabaseEntities1 db = new sitedatabaseEntities1())
            {
                int userid = int.Parse(Request.Cookies["userid"].Value);
                return View(db.Users.Where(x => x.UserID == userid).FirstOrDefault());
            }
        }

        [HttpPost]
        public ActionResult profile([Bind(Include = "UserID,FirstName,LastName,DateOfBirth")] User user)
        {
            var message = "";
            if (ModelState.IsValid)
                {
                    if (user != null)
                    {
                        var account = db.Users.Where(a => a.UserID == user.UserID).FirstOrDefault();
                        account.FirstName = user.FirstName;
                        account.LastName = user.LastName;
                        account.DateOfBirth = user.DateOfBirth;
                        db.SaveChanges();
                        message = "اطلاعات با موفیت ویرایش شد.";
                    }
                    else
                    {
                        message = "مشکلی در فرایند ویرایش اطلاعات ایجاد شده است.";
                    }
                }
            ViewBag.Message = message;
            return View();
        }

profile.cshtml

@model projectwebsite.Models.User

 @using (Html.BeginForm())
                                {
                                    @Html.AntiForgeryToken()
                                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                                    @Html.HiddenFor(model => model.UserID)
                                    @Html.LabelFor(model => model.FirstName)
                                    @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "form-text text-danger" })

                                    @Html.LabelFor(model => model.LastName)
                                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "form-text text-danger" })

                                    @Html.LabelFor(model => model.DateOfBirth)
                                    @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "form-text text-danger" })
                                    <button type="submit" value="Save" class="btn btn-success"> submit</button>
                                    if (ViewBag.Message != null)
                                    {

                                            error@ViewBag.Message

                                    }
                                }

and last file user.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace projectwebsite.Models
{
    [MetadataType(typeof(UserMetadata))]
    public partial class User
    {
        public string Confirmpassword { get; set; }
    }
    public class UserMetadata
    {
        [Display(Name="نام")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "نام خود را وارد کنید.")]
        public string FirstName { get; set; }

        [Display(Name ="نام خانوادگی")]
        [Required(AllowEmptyStrings = false, ErrorMessage ="نام خانوادگی را وارد کنید.")]
        public string LastName { get; set; }

        [Display(Name ="ایمیل")]
        [Required(AllowEmptyStrings = false, ErrorMessage ="ایمیل خود را وارد کنید")]
        [DataType(DataType.EmailAddress)]
        public string EmailID { get; set; }

        [Display(Name = "تاریخ تولد")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime DateOfBirth { get; set; }

        [Display(Name = "پسورد")]
        [Required(AllowEmptyStrings =false, ErrorMessage ="پسورد را وارد کنید.")]
        [DataType(DataType.Password)]
        [MinLength(6,ErrorMessage ="6 حرف کمترین طول پسورد میباشد.")]
        public string Password { get; set; }

        [Display(Name ="تکرار پسورد")]
        [DataType(DataType.Password)]
        [Compare("Password",ErrorMessage ="رمز عبور برابر نیست.")]
        public string Confirmpassword { get; set; }
    }
}


问:
How to get path to nextcloud app path in javascript
Structure of my nextcloud instance

```<code>/apps
/apps2
  /myapp
    /img
      icon.svg
</code>```

I'm looking for a solution to generate a full URL to the icon from a path relative to myapp.

答:
I've injected initial state but should be a better solution

https://docs.nextcloud.com/server/18/developer_manual/app/view/js.html#loading-initial-state

```<code>        $eventDispatcher->addListener(
            'OCA\Files::loadAdditionalScripts', function () {
                script('projects', 'filelist_plugin');
                style('projects', 'filelist');
                /* @var IInitialStateService $state */
                $state = $this->getContainer()->query(IInitialStateService::class);
                $state->provideInitialState('projects', 'project-icon', image_path('projects', 'folder.svg'));
            }
        );
</code>```

Body:
Structure of my nextcloud instance

/apps
/apps2
  /myapp
    /img
      icon.svg

I'm looking for a solution to generate a full URL to the icon from a path relative to myapp.

Body:
I've injected initial state but should be a better solution

https://docs.nextcloud.com/server/18/developer_manual/app/view/js.html#loading-initial-state

        $eventDispatcher->addListener(
            'OCA\Files::loadAdditionalScripts', function () {
                script('projects', 'filelist_plugin');
                style('projects', 'filelist');
                /* @var IInitialStateService $state */
                $state = $this->getContainer()->query(IInitialStateService::class);
                $state->provideInitialState('projects', 'project-icon', image_path('projects', 'folder.svg'));
            }
        );


问:
Behavior of flatMap when applied to List[Option[T]]
Let's take a look at this code:

```<code>scala> val a = List(Some(4), None)
a: List[Option[Int]] = List(Some(4), None)
scala> a.flatMap( e=> e)
List[Int] = List(4)
</code>```

Why would applying flatMap with the function { e => e } on a List[Option[T]] returns a List[T] with the None elements removed?

Specifically, what is the conceptual reasoning behind it -- is it based on some existing theory in functional programming? Is this behavior common in other functional languages?

This, while indeed useful, does feel a bit magical and arbitrary at the same time.

EDIT:

Thank you for your feedbacks and answer.
I have rewritten my question to put more emphasis on the conceptual nature of the question. Rather than the Scala specific implementation details, I'm more interested in knowing the formal concepts behind it.

答:
A short answer to your question is: the flatMap method of the List type is defined to work with a more general function type, not just a function that only produces a List[B] result type.

The general result type is IterableOnce[B], as shown in the faltMap method signature:  final def flatMap[B](f: (A) => IterableOnce[B]): List[B]. The flatMap implementation is rather simple in that it applies the f function to each element and iterates over the result in a nested while loop. All results from the nested loop are added to a result of type List[B].

Therefore the flatMap works with any function that produces an IterableOnce[B] result from each list element. The IterableOnce is a trait that defines a minimal interface that is inherited by all iterable classes, including all collection types (Set, Map and etc.) and the Option class.

The Option class implementation returns collection.Iterator.empty for None and collection.Iterator.single(x) for Some(x). Therefore the flatMap method skips None element.

The question uses the identity function. It is better to use flatten method when the purpose is to flat iterable elements.

scala> val a = List(Some(4), None)
a: List[Option[Int]] = List(Some(4), None)

scala> a.flatten
res0: List[Int] = List(4)
```

Body:
Let's take a look at this code:

scala> val a = List(Some(4), None)
a: List[Option[Int]] = List(Some(4), None)
scala> a.flatMap( e=> e)
List[Int] = List(4)

Why would applying flatMap with the function { e => e } on a List[Option[T]] returns a List[T] with the None elements removed?

Specifically, what is the conceptual reasoning behind it -- is it based on some existing theory in functional programming? Is this behavior common in other functional languages?

This, while indeed useful, does feel a bit magical and arbitrary at the same time.

EDIT:

Thank you for your feedbacks and answer.
I have rewritten my question to put more emphasis on the conceptual nature of the question. Rather than the Scala specific implementation details, I'm more interested in knowing the formal concepts behind it.


问:
Retrieving records from other table column
I created a view where there are multiple column. I need to retrieve some data from an external table.

```<code>cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName
</code>```

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.

答:
You need to group by roadCrossSection1 as well

```<code>SELECT roadName, roadCrossSection1,
               sum(roadLength) as sumRoadLength
FROM cte4
group by roadName, roadCrossSection1
order by roadName, roadCrossSection1
</code>```

Updated

```<code>SELECT roadName, sum(roadLength) as sumRoadLength
FROM cte4
group by roadName
order by roadName
</code>```

Body:
I created a view where there are multiple column. I need to retrieve some data from an external table.

cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.

Body:
You need to group by roadCrossSection1 as well

SELECT roadName, roadCrossSection1,
               sum(roadLength) as sumRoadLength
FROM cte4
group by roadName, roadCrossSection1
order by roadName, roadCrossSection1

Updated

SELECT roadName, sum(roadLength) as sumRoadLength
FROM cte4
group by roadName
order by roadName