问:
How to find out which .NET framework nuget package targets?
I have C# project that has to target .NET 3.5. framework and I have several nuget packages I'd like to install in the given project.

How to find out, for a given nuget package, which .NET framework versions it supports (by version of package for example), without me trying to install every available version of the package in order to see if its installation will pass without rolling back because of the dependency of the given version of the package to .NET framework higher than 3.5.?

For example, I know that xUnit.net version 1.9.2. is the highest version that supports .NET 3.5, but I had to find out this "manually".

答:
At the risk of upsetting the Stack admins for daring to submit a wrong answer...
You can download the .nupkg file (https://www.nuget.org/packages > Download ) then unzip it. In the file you can find references to PlatformToolset, ToolsVersion which I was able to use to look up the specific version of the compiler. ("v110" = Visual C++ 2012, "v120" =  Visual C++ 2013, etc. To get the framework you could use decompiler a tool like ILSpy to inspect included files to see what version they target.</p>


来源: stackexchange

问:
error while running the spring boot program
Description

I have created a database with three tables

```<code>users (user_id, name, password),
</code>```

the Role table with columns

```<code>    role_id, role and the third column Role_user with user_id,role_id.
</code>```

error while running the program,

I have stored the username, passwords with the help of hashing with SHA2, for security purposes.

While running the program it is throwing the error as mentioned above. How should I resolve this error?

```<code>  package com.techprimers.security.securitydbexample.model;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "user")
public class Users {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "user_id")
   private int id;
   @Column(name = "password")
   private String password;
   @Column(name = "name")
   private String name;

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
   private Set<Role> roles;

   public Users() {
   }

   public Users(Users users) {
       this.roles = users.getRoles();
       this.name = users.getName();
       this.id = users.getId();
       this.password = users.getPassword();
   }

   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }

   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public Set<Role> getRoles() {
       return roles;
   }

   public void setRoles(Set<Role> roles) {
       this.roles = roles;
   }
}
</code>```

Role

```<code>package com.MonitoringDashboardNew.Model;

import javax.persistence.*;

@Entity
@Table(name = "role")
public class Role {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "role_id")
   private int roleId;

   @Column(name = "role")
   private String role;

   public Role() {
   }

   public int getRoleId() {
       return roleId;
   }

   public void setRoleId(int roleId) {
       this.roleId = roleId;
   }

   public String getRole() {
       return role;
   }

   public void setRole(String role) {
       this.role = role;
   }
}
</code>```

CustomUserDetails

```<code>
package com.MonitoringDashboardNew.Model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.stream.Collectors;

public class CustomUserDetails extends Users implements UserDetails {

    public CustomUserDetails(final Users users) {
        super(users);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return getRoles()
                .stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
</code>```

Repository

```<code>
package com.MonitoringDashboardNew.Repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.MonitoringDashboardNew.Model.Users;

@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
    Optional<Users> findByName(String username);

}
</code>```

Service

```<code>
package com.MonitoringDashboardNew.Services;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.MonitoringDashboardNew.Model.CustomUserDetails;
import com.MonitoringDashboardNew.Model.Users;
import com.MonitoringDashboardNew.Repository.UsersRepository;

import java.util.Optional;

@Service
public abstract class CustomUserDetailsService implements UserDetailsService {

   @Autowired
   private UsersRepository usersRepository;

   public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
       Optional<Users> optionalUsers = usersRepository.findByName(name);
      // Optional<Users> optionalUsers = usersRepository.findById(id);

       optionalUsers
               .orElseThrow(() -> new UsernameNotFoundException("Username not found"));
       return optionalUsers
               .map(CustomUserDetails::new).get();
   }
}
</code>```

SecurityConfuguration

```<code>

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.MonitoringDashboardNew.Services.CustomUserDetailsService;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories()
@Configuration
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService)
        .passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("**/monitoring/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin().permitAll();
    }

    private PasswordEncoder getPasswordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return true;
            }
        };
    }
}
</code>```

Error

Description:

Field userDetailsService in com.example.demo.SecurityConfiguration required a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' that could not be found.

The injection point has the following annotations:

```<code>@org.springframework.beans.factory.annotation.Autowired(required=true)
</code>```

Action:

Consider defining a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' in your configuration.

```<code>

</code>```

答:
Your CustomUserDetailsService is abstract and cannot be created.

```<code>@Service
public abstract class CustomUserDetailsService implements UserDetailsService {
</code>```

Make it non abstract:

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Description

I have created a database with three tables

users (user_id, name, password),

the Role table with columns

    role_id, role and the third column Role_user with user_id,role_id.

error while running the program,

I have stored the username, passwords with the help of hashing with SHA2, for security purposes.

While running the program it is throwing the error as mentioned above. How should I resolve this error?

  package com.techprimers.security.securitydbexample.model;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "user")
public class Users {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "user_id")
   private int id;
   @Column(name = "password")
   private String password;
   @Column(name = "name")
   private String name;

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
   private Set<Role> roles;

   public Users() {
   }

   public Users(Users users) {
       this.roles = users.getRoles();
       this.name = users.getName();
       this.id = users.getId();
       this.password = users.getPassword();
   }

   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }

   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public Set<Role> getRoles() {
       return roles;
   }

   public void setRoles(Set<Role> roles) {
       this.roles = roles;
   }
}

Role

package com.MonitoringDashboardNew.Model;

import javax.persistence.*;

@Entity
@Table(name = "role")
public class Role {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "role_id")
   private int roleId;

   @Column(name = "role")
   private String role;

   public Role() {
   }

   public int getRoleId() {
       return roleId;
   }

   public void setRoleId(int roleId) {
       this.roleId = roleId;
   }

   public String getRole() {
       return role;
   }

   public void setRole(String role) {
       this.role = role;
   }
}

CustomUserDetails

package com.MonitoringDashboardNew.Model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.stream.Collectors;

public class CustomUserDetails extends Users implements UserDetails {

    public CustomUserDetails(final Users users) {
        super(users);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return getRoles()
                .stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Repository

package com.MonitoringDashboardNew.Repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.MonitoringDashboardNew.Model.Users;

@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
    Optional<Users> findByName(String username);

}

Service

package com.MonitoringDashboardNew.Services;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.MonitoringDashboardNew.Model.CustomUserDetails;
import com.MonitoringDashboardNew.Model.Users;
import com.MonitoringDashboardNew.Repository.UsersRepository;

import java.util.Optional;

@Service
public abstract class CustomUserDetailsService implements UserDetailsService {

   @Autowired
   private UsersRepository usersRepository;

   public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
       Optional<Users> optionalUsers = usersRepository.findByName(name);
      // Optional<Users> optionalUsers = usersRepository.findById(id);

       optionalUsers
               .orElseThrow(() -> new UsernameNotFoundException("Username not found"));
       return optionalUsers
               .map(CustomUserDetails::new).get();
   }
}

SecurityConfuguration

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.MonitoringDashboardNew.Services.CustomUserDetailsService;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories()
@Configuration
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService)
        .passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("**/monitoring/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin().permitAll();
    }

    private PasswordEncoder getPasswordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return true;
            }
        };
    }
}

Error

Description:

Field userDetailsService in com.example.demo.SecurityConfiguration required a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' that could not be found.

The injection point has the following annotations:

@org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' in your configuration.

Body:
Your CustomUserDetailsService is abstract and cannot be created.

@Service
public abstract class CustomUserDetailsService implements UserDetailsService {

Make it non abstract:

@Service
public class CustomUserDetailsService implements UserDetailsService {


问:
Where can I set environment variables that crontab will use?
I have a crontab running every hour. The user running it has environment variabless in the .bash_profile that work when the user runs the job from the terminal, however, obviously these don't get picked up by crontab when it runs.

I've tried setting them in .profile and .bashrc but they still don't seem to get picked up. Does anyone know where I can put environment vars that crontab can pick up?

答:
You can also prepend your command with env to inject Environment variables like so:

```<code>0 * * * *   env VARIABLE=VALUE /usr/bin/mycommand
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can also prepend your command with env to inject Environment variables like so:

0 * * * *   env VARIABLE=VALUE /usr/bin/mycommand


问:
Must be initialized error in val variable
Following code report property must be initialized or be abstract error.

```<code>// MyApi.kt
interface MyApi {

    ...
}

// MyFetch.kt
class MyFetch {

    private val myApi: MyApi  // <- this line

    ...
}
</code>```

It can use lateinit statement in mutable variable, but how should I predefined in val?

答:
The Separation of Concerns design pattern would favor passing a value to the constructor. So some other class that instantiates your MyFetch class would also instantiate your MyApi instance and pass it to the constructor:

```<code>class MyClass(val myApi: MyApi){

}

//Some higher level class:
val myAPI = object: MyApi { //... }
val myClass = MyClass(myApi)
</code>```

But you can also just initialize it from within the class. This would make sense if MyApi is tightly coupled to the behavior of MyClass:

```<code>class MyClass {

    val myApi = object: MyApi { //... }

}

// or

class MyClass {

    val myApi: MyApi

    init {
        myApi = object: MyApi { //... }
    }
}
</code>```

In any of the three cases, a value of read-only val property has to be assigned in either the constructor, inline with the declaration, or in an init block. The only other option is to use a property delegate.

Body:
Following code report property must be initialized or be abstract error.

// MyApi.kt
interface MyApi {

    ...
}

// MyFetch.kt
class MyFetch {

    private val myApi: MyApi  // <- this line

    ...
}

It can use lateinit statement in mutable variable, but how should I predefined in val?

Body:
The Separation of Concerns design pattern would favor passing a value to the constructor. So some other class that instantiates your MyFetch class would also instantiate your MyApi instance and pass it to the constructor:

class MyClass(val myApi: MyApi){

}

//Some higher level class:
val myAPI = object: MyApi { //... }
val myClass = MyClass(myApi)

But you can also just initialize it from within the class. This would make sense if MyApi is tightly coupled to the behavior of MyClass:

class MyClass {

    val myApi = object: MyApi { //... }

}

// or

class MyClass {

    val myApi: MyApi

    init {
        myApi = object: MyApi { //... }
    }
}

In any of the three cases, a value of read-only val property has to be assigned in either the constructor, inline with the declaration, or in an init block. The only other option is to use a property delegate.


问:
MaxLength for bootstrap-vue input number Vue.js
I try to implement a maxLength for an input from bootstrap-vue, but from what I read from their documentation they don't support max. If I remove type="number", it works , but is not a number anymore.

```<code>    <b-form-input
        size="sm"
        v-model="register_volume_first"
        type="number"
        maxlength=4
        placeholder="1902"
    ></b-form-input>
</code>```

答:
maxLength only refers for text types, i tried to do a test to see if min & max are supported and it seems so, please take a look:

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">

  <b-form @submit="onSubmit">
    <b-form-input type="number" max="20" min="10"><min="10" required></b-form-input>
    <b-button type="submit" variant="primary">Submit</b-button>
  </b-form>

</div></code>```

Keep in mind that the check for min & max is done when the form is submitted, with the required parameter of course.

EDIT : added form & submit to the snippet

EDIT 2:
Without form submit

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  },
  data() {
    return{
      inputValue: 15
    }
  },
  watch: {
    inputValue(val){
      if(val < 10)
        this.inputValue = 10;
      else if(val > 20)
        this.inputValue = 20;
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">

    <b-form-input v-model="inputValue" type="number" max="20" min="10" required></b-form-input>

</div></code>```

Body:
maxLength only refers for text types, i tried to do a test to see if min & max are supported and it seems so, please take a look:

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">

  <b-form @submit="onSubmit">
    <b-form-input type="number" max="20" min="10"><min="10" required></b-form-input>
    <b-button type="submit" variant="primary">Submit</b-button>
  </b-form>

</div>

Keep in mind that the check for min & max is done when the form is submitted, with the required parameter of course.

EDIT : added form & submit to the snippet

EDIT 2:
Without form submit

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  },
  data() {
    return{
      inputValue: 15
    }
  },
  watch: {
    inputValue(val){
      if(val < 10)
        this.inputValue = 10;
      else if(val > 20)
        this.inputValue = 20;
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">

    <b-form-input v-model="inputValue" type="number" max="20" min="10" required></b-form-input>

</div>


问:
Pymysql can't connect do MySQL DB: hangs at "self.sock.recv_into(b)"?
Currently on macOS 10.15 using python 3.7, with MySQL 8.0.19 installed. Developing in VScode with a virtual environment setup. I've created a local database in phpmyadmin as well. I want to connect to it anyway possible. Script:

```<code>import pymysql

print("Before")
connection = pymysql.connect(host='localhost',
    user='myUserName', password='myPassword', db='db_name', charset='utf8mb4',
          cursorclass=pymysql.cursors.DictCursor)
print("After")
</code>```

When I run the script, execution hangs indefinitely. After printing "After", I have to quit execution. Trackback is:

```<code>Traceback (most recent call last):
File "connect.py", line 5, in <module>
  user='myUserName', password='myPassword', db='db_name', charset='utf8mb4',
  cursorclass=pymysql.cursors.DictCursor)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/__init__.py", line 94, in Connect
  return Connection(*args, **kwargs)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 325, in __init__
  self.connect()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 598, in connect
  self._get_server_information()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 975, in _get_server_information
  packet = self._read_packet()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
packages/pymysql/connections.py", line 657, in _read_packet
  packet_header = self._read_bytes(4)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 691, in _read_bytes
  data = self._rfile.read(num_bytes)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/
python3.7/socket.py", line 589, in readinto
  return self._sock.recv_into(b)
KeyboardInterrupt
</code>```

No idea why this is occurring. What is happening here? I have searched a ton of questions on stack overflow and none helped me.

答:
Problem was solved by adding the "unix_socket" param in pymysql connect function. See answer here: pymysql can't connect to MySQL on localhost

```<code>import pymysql

print("Before")
conn = pymysql.connect(db='w_dev', user='root', passwd='celebrate',
unix_socket="/tmp/mysql.sock")
print("After")
</code>```

This script worked.

Body:
Currently on macOS 10.15 using python 3.7, with MySQL 8.0.19 installed. Developing in VScode with a virtual environment setup. I've created a local database in phpmyadmin as well. I want to connect to it anyway possible. Script:

import pymysql

print("Before")
connection = pymysql.connect(host='localhost',
    user='myUserName', password='myPassword', db='db_name', charset='utf8mb4',
          cursorclass=pymysql.cursors.DictCursor)
print("After")

When I run the script, execution hangs indefinitely. After printing "After", I have to quit execution. Trackback is:

Traceback (most recent call last):
File "connect.py", line 5, in <module>
  user='myUserName', password='myPassword', db='db_name', charset='utf8mb4',
  cursorclass=pymysql.cursors.DictCursor)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/__init__.py", line 94, in Connect
  return Connection(*args, **kwargs)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 325, in __init__
  self.connect()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 598, in connect
  self._get_server_information()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 975, in _get_server_information
  packet = self._read_packet()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
packages/pymysql/connections.py", line 657, in _read_packet
  packet_header = self._read_bytes(4)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site-
  packages/pymysql/connections.py", line 691, in _read_bytes
  data = self._rfile.read(num_bytes)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/
python3.7/socket.py", line 589, in readinto
  return self._sock.recv_into(b)
KeyboardInterrupt

No idea why this is occurring. What is happening here? I have searched a ton of questions on stack overflow and none helped me.

Body:
Problem was solved by adding the "unix_socket" param in pymysql connect function. See answer here: pymysql can't connect to MySQL on localhost

import pymysql

print("Before")
conn = pymysql.connect(db='w_dev', user='root', passwd='celebrate',
unix_socket="/tmp/mysql.sock")
print("After")

This script worked.


问:
Laravel - Get error message from localized file
I'm creating my own validation and need to retrieve error messages from the localized file(resources/lang/en/validation.php and etc). The main task is to get array of error messages from the appropriate file. Usually, the validator does it and you don't need to worry about it. Does exist a way to get all these messages with no using validator?</p>

答:
You can access your translation files and their contents from anywhere with the global helper function trans

For example: your translations are in the file resources/lang/en/customvalidation.php

```<code>return [
    'customerror' => 'my custom error message',
];
</code>```

Then

```<code>trans('customvalidation.customerror')
</code>```

will return "my custom error message" (depending on the current set language)

Body:
You can access your translation files and their contents from anywhere with the global helper function trans

For example: your translations are in the file resources/lang/en/customvalidation.php

return [
    'customerror' => 'my custom error message',
];

Then

trans('customvalidation.customerror')

will return "my custom error message" (depending on the current set language)


问:
How to build Two Synchronous ListView with Dynamic Contents
I want to create a ScrollView which has a dynamic content with two columns in itself.

And items of right column are connected to items of left column cross-positioned. (Like this first column item y-coordinates:[(0,100),(100,200),(200,300)] -- second column item y-coordinates:[(50,150),(150,250)])

Using one ScrollView or a ListView is impossible because they cannot have two columns like that cross positioned as I know. So, I have two solutions. These solution approaches have different problems.

Here is my first solution:

-A dynamic custom view inside a ScrollView.

-The problem with this approach is I cannot figure out how to update the ScrollView and Dynamic Custom View, so it does not scroll.

My second solution:

-Two seperate connected listview (If you slide one, other one slides automatically to the same position synchronously).

-This solutions problem is I cant find out a way to connect them to each other.

Any help will be appreciated.

答:
For any person who might need the answer, I've found the solution in here. I improved this with that (which is incorrect)(actually I fixed it). And here is my final solution:

MyScrollView.java

```<code>public class MyScrollView extends ScrollView implements IScrollListener {

    private static final String TAG = "MyScrollView";
    private IScrollListener listener;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setScrollViewListener(IScrollListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (listener != null) {
            listener.onScrollChanged(this, x, y, oldX, oldY);
        } else {
            Log.i(TAG, "asdasd");
        }
    }

    @Override
    public void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (listener != null) {
            listener.onScrollChanged(this, x, y, oldX, oldY);
        } else {
            Log.i(TAG, "asdasd");
        }
    }
}
</code>```

MyActivity.java

```<code>public class MyActivity extends AppCompatActivity implements IScrollListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_position);

        .
        .
        .

        scrollViewLeft = (MyScrollView) this.findViewById(R.id.scrollViewLeft);
        scrollViewRight = (MyScrollView) this.findViewById(R.id.scrollViewRight);

        .
        .

        scrollViewLeft.setScrollViewListener(this);
        scrollViewRight.setScrollViewListener(this);

        .
        .
        LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View viewLeft = vi.inflate(R.layout.target_item, null);
        View viewRight = vi.inflate(R.layout.target_item_right, null);

        // insert into left view
        ViewGroup insertPointLeft = (ViewGroup) findViewById(R.id.leftLinearLayout);
        insertPointLeft.addView(viewLeft, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        // insert into right view
        ViewGroup insertPointRight = (ViewGroup) findViewById(R.id.rightLinearLayout);
        insertPointRight.addView(viewRight, targets.size(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        // fill in any details dynamically here
        TextView number = (TextView) viewLeft.findViewById(R.id.number);
        number.setText("1");
        TextView name = (TextView) viewLeft.findViewById(R.id.name);
        name.setText("Muhammed Aydogan");

        // fill in any details dynamically here
        TextView number2 = (TextView) viewRight.findViewById(R.id.number);
        number2.setText("2");
        TextView name2 = (TextView) viewRight.findViewById(R.id.name);
        name2.setText("Muhammed Aydogan");*/
    }

    @Override
    public void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY) {
        if (scrollViewLeft.equals(scrollView)) {
            scrollViewRight.scrollTo(x, y);
        } else if (scrollViewRight.equals(scrollView)) {
            scrollViewLeft.scrollTo(x, y);
        }
    }
}
</code>```

IScrollListener.java

```<code>public interface IScrollListener {
    void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY);
}

</code>```

Body:
For any person who might need the answer, I've found the solution in here. I improved this with that (which is incorrect)(actually I fixed it). And here is my final solution:

MyScrollView.java

public class MyScrollView extends ScrollView implements IScrollListener {

    private static final String TAG = "MyScrollView";
    private IScrollListener listener;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setScrollViewListener(IScrollListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (listener != null) {
            listener.onScrollChanged(this, x, y, oldX, oldY);
        } else {
            Log.i(TAG, "asdasd");
        }
    }

    @Override
    public void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (listener != null) {
            listener.onScrollChanged(this, x, y, oldX, oldY);
        } else {
            Log.i(TAG, "asdasd");
        }
    }
}

MyActivity.java

public class MyActivity extends AppCompatActivity implements IScrollListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_position);

        .
        .
        .

        scrollViewLeft = (MyScrollView) this.findViewById(R.id.scrollViewLeft);
        scrollViewRight = (MyScrollView) this.findViewById(R.id.scrollViewRight);

        .
        .

        scrollViewLeft.setScrollViewListener(this);
        scrollViewRight.setScrollViewListener(this);

        .
        .
        LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View viewLeft = vi.inflate(R.layout.target_item, null);
        View viewRight = vi.inflate(R.layout.target_item_right, null);

        // insert into left view
        ViewGroup insertPointLeft = (ViewGroup) findViewById(R.id.leftLinearLayout);
        insertPointLeft.addView(viewLeft, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        // insert into right view
        ViewGroup insertPointRight = (ViewGroup) findViewById(R.id.rightLinearLayout);
        insertPointRight.addView(viewRight, targets.size(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        // fill in any details dynamically here
        TextView number = (TextView) viewLeft.findViewById(R.id.number);
        number.setText("1");
        TextView name = (TextView) viewLeft.findViewById(R.id.name);
        name.setText("Muhammed Aydogan");

        // fill in any details dynamically here
        TextView number2 = (TextView) viewRight.findViewById(R.id.number);
        number2.setText("2");
        TextView name2 = (TextView) viewRight.findViewById(R.id.name);
        name2.setText("Muhammed Aydogan");*/
    }

    @Override
    public void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY) {
        if (scrollViewLeft.equals(scrollView)) {
            scrollViewRight.scrollTo(x, y);
        } else if (scrollViewRight.equals(scrollView)) {
            scrollViewLeft.scrollTo(x, y);
        }
    }
}

IScrollListener.java

public interface IScrollListener {
    void onScrollChanged(IScrollListener scrollView, int x, int y, int oldX, int oldY);
}


问:
Differences between Ant and Maven
Could someone tell me the differences between Ant and Maven? I have never used either. I understand that they are used to automate the building of Java projects, but I do not know where to start from.</p>

答: Maven also houses a large repository of commonly used open source projects.  During the build Maven can download these dependencies for you (as well as your dependencies dependencies :))  to make this part of building a project a little more manageable.</p>

OwnerDisplayName: rtacconi

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 2.5

Title: Differences between Ant and Maven

OwnerDisplayName: markt


问:
Android Leaks while testing in Eclipse Memory Analyzer
i am testing leaks in my first android App..i have exp to in Iphone development iam struggling to detect leaks with memory Analyzer tool in Eclipse these are the issues in App

```<code>2,371 instances of "java.lang.Class", loaded by "<system class loader>" occupy 807,856 (31.82%) bytes.
 class android.text.Html$HtmlParser @ 0x40104b90 - 126,632 (4.99%) bytes.
class org.apache.harmony.security.fortress.Services @ 0x400afe18 - 47,056 (1.85%) bytes.
class com.android.internal.R$styleable @ 0x400735c8 - 38,048 (1.50%) bytes.
class android.R$styleable @ 0x40051910 - 37,640 (1.48%) bytes.
class libcore.icu.TimeZones$CachedTimeZones @ 0x404a7480 - 37,624 (1.48%) bytes.
class android.content.res.Resources @ 0x40064e50 - 34,528 (1.36%) bytes.
class android.text.AutoText @ 0x40107880 - 31,656 (1.25%) bytes.
</code>```

And..Second One Is.

```<code>    6,669 instances of "java.lang.String", loaded by "<system class loader>" occupy 15,152  (16.35%) bytes.
</code>```

can any one explain or any suggestions regarding where there problems coming from

答: You have not demonstrated that there is a problem. Everything there seems fairly normal.</p>

Body:
i am testing leaks in my first android App..i have exp to in Iphone development iam struggling to detect leaks with memory Analyzer tool in Eclipse these are the issues in App

2,371 instances of "java.lang.Class", loaded by "<system class loader>" occupy 807,856 (31.82%) bytes.
 class android.text.Html$HtmlParser @ 0x40104b90 - 126,632 (4.99%) bytes.
class org.apache.harmony.security.fortress.Services @ 0x400afe18 - 47,056 (1.85%) bytes.
class com.android.internal.R$styleable @ 0x400735c8 - 38,048 (1.50%) bytes.
class android.R$styleable @ 0x40051910 - 37,640 (1.48%) bytes.
class libcore.icu.TimeZones$CachedTimeZones @ 0x404a7480 - 37,624 (1.48%) bytes.
class android.content.res.Resources @ 0x40064e50 - 34,528 (1.36%) bytes.
class android.text.AutoText @ 0x40107880 - 31,656 (1.25%) bytes.

And..Second One Is.

    6,669 instances of "java.lang.String", loaded by "<system class loader>" occupy 15,152  (16.35%) bytes.

can any one explain or any suggestions regarding where there problems coming from


问:
Extract property values from nested array of objects and arrays
I have the following nested array of objects:

```<code>[
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 036,
                        "name": "john",
                    },
                    {
                        "id": 037,
                        "name": "inna",
                    }
                ]
            }
        ]
    },
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 045,
                        "name": "carl",
                    },
                    {
                        "id": 056,
                        "name": "tina",
                    }
                ]
            }
        ]
    }]
</code>```

I want to extract all the values of the "name" property and put them in an array.

Output: ["john", "inna", "carl", "tina"].

答:
Try with this code:

```<code>const userNames = [];

data.map(item => {
    return item.info.map(registry => {
        return registry.info.map(user => userNames.push(user.name));
    })
})
</code>```

Output: ["john", "inna", "carl", "tina"]

Body:
I have the following nested array of objects:

[
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 036,
                        "name": "john",
                    },
                    {
                        "id": 037,
                        "name": "inna",
                    }
                ]
            }
        ]
    },
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 045,
                        "name": "carl",
                    },
                    {
                        "id": 056,
                        "name": "tina",
                    }
                ]
            }
        ]
    }]

I want to extract all the values of the "name" property and put them in an array.

Output: ["john", "inna", "carl", "tina"].

Body:
Try with this code:

const userNames = [];

data.map(item => {
    return item.info.map(registry => {
        return registry.info.map(user => userNames.push(user.name));
    })
})

Output: ["john", "inna", "carl", "tina"]


问:
How can i code the Title of a UIButton to change across two View Controllers?
This is what i have but it does not work. I want the bbutton on vc3 to change title depending on what image is displayed on VC2</p>

```<code>@IBAction func buttonPressed(_ sender: UIButton) {

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
            vc3.buttonTitle.titleLabel?.text = "no"
    }
else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
let vc3 = segue.destination as! ThirdViewController
    vc3.buttonTitle.titleLabel?.text = "happy"

} }
</code>```

答:
First of all, create a property named text in your ThirdViewController and set it as buttonTitle's title in viewDidLoad() like so,

```<code>class ThirdViewController: UIViewController {
    @IBOutlet weak var buttonTitle: UIButton!
    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.buttonTitle.setTitle(self.text, for: .normal)
    }
}
</code>```

This is because, the IBOutlet won't be set until viewDidLoad() is called. So, accessing the button in vc2 will result in runtime exception.

Next, your SecondViewController should look like,

```<code>class SecondViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc3 = segue.destination as? ThirdViewController {
            var buttonTitle: String?
            switch self.imageView.image {
            case UIImage(named: "sad"): buttonTitle = "no"
            case UIImage(named: "happy"): buttonTitle = "happy"
            default: break
            }
            vc3.text = buttonTitle
        }
    }
}
</code>```

In the above code,

In prepare(for:sender:), set the text of vc3 as per the imageView's image.

There is no need to create buttonPressed(_:) IBAction. All that will be handled in prepare(for:sender:) itself.

Body:
This is what i have but it does not work. I want the bbutton on vc3 to change title depending on what image is displayed on VC2

@IBAction func buttonPressed(_ sender: UIButton) {

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
            vc3.buttonTitle.titleLabel?.text = "no"
    }
else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
let vc3 = segue.destination as! ThirdViewController
    vc3.buttonTitle.titleLabel?.text = "happy"

} }

Body:
First of all, create a property named text in your ThirdViewController and set it as buttonTitle's title in viewDidLoad() like so,

class ThirdViewController: UIViewController {
    @IBOutlet weak var buttonTitle: UIButton!
    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.buttonTitle.setTitle(self.text, for: .normal)
    }
}

This is because, the IBOutlet won't be set until viewDidLoad() is called. So, accessing the button in vc2 will result in runtime exception.

Next, your SecondViewController should look like,

class SecondViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc3 = segue.destination as? ThirdViewController {
            var buttonTitle: String?
            switch self.imageView.image {
            case UIImage(named: "sad"): buttonTitle = "no"
            case UIImage(named: "happy"): buttonTitle = "happy"
            default: break
            }
            vc3.text = buttonTitle
        }
    }
}

In the above code,

In prepare(for:sender:), set the text of vc3 as per the imageView's image.

There is no need to create buttonPressed(_:) IBAction. All that will be handled in prepare(for:sender:) itself.


问:
check if image exists with fetch (function does not return response)
I have the following function to check if an image (avatar) exists on the server. If so, the avatar is displayed. If not, a default avatar is displayed.

```<code>export const Avatar = props => {

    const userId = props.userId

    const size = props.size ? props.size : 25

    fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
        if (res.status === 404) {
            return (
                <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        } else {
            return (
                <Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        }
    }).catch(err => {
        return (
            <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                width: size,
                height: size,
                borderRadius: size / 2
            }} />
        )
    })

}
</code>```

However, this function does not work. I get the error "nothing was returned from render", because the function thinks a return-statement (at the end) is missing. However, when I put some console.logs in it, the fetch itself is working. The URLs are correct, because when I put a return at the end with an Image-component, it works.

Anyone knows what the problem could be? Has it anything to do with async?

答:
It seems like you don't have an actual return statement for this function. I'm not sure what your request response looks like if the image doesn't exist, but what happens if you set the default outside of the fetch?

Something like this:

export const Avatar = props => {

    const userId = props.userId

    const size = props.size ? props.size : 25

    fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
        if (res.status === 404) {
            return (
                <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        } else {
            return (
                <Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        }
    }).catch(err => {
        // Handle actual errors here
    })

    return (
        <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
            width: size,
            height: size,
            borderRadius: size / 2
        }} />
    )
}
```

Body:
I have the following function to check if an image (avatar) exists on the server. If so, the avatar is displayed. If not, a default avatar is displayed.

export const Avatar = props => {

    const userId = props.userId

    const size = props.size ? props.size : 25

    fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
        if (res.status === 404) {
            return (
                <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        } else {
            return (
                <Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        }
    }).catch(err => {
        return (
            <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                width: size,
                height: size,
                borderRadius: size / 2
            }} />
        )
    })

}

However, this function does not work. I get the error "nothing was returned from render", because the function thinks a return-statement (at the end) is missing. However, when I put some console.logs in it, the fetch itself is working. The URLs are correct, because when I put a return at the end with an Image-component, it works.

Anyone knows what the problem could be? Has it anything to do with async?


问:
Submit HTML forms that contain dynamic IDs
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

```<code> <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
    <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...
            <div class="row" style="margin-bottom: 5%;">
                <div class="col-xl-2 col-lg-3 col-md-3">
                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
                </div>
            </div>
     </form>
</code>```

Form with ID="surveyImage18"

```<code><form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
      <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

            </div>
        </div>

    <div class="row" style="margin-bottom: 5%;">
        <div class="col-xl-2 col-lg-3 col-md-3">
             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
        </div>
    </div>
</form>
</code>```

AJAX call

```<code><script type="text/javascript">
 $("#surveyImage13").validate({
                    rules: {
                         'responses[]': {
                            required:true
                        }
                    },
                     // change name of error class that is assigned to input fields
    errorClass: 'error_validate',

    errorPlacement: function (label, element) {

        // default
        if (element.is(':radio')) {
            label.insertAfter(element.parent('.form-check-inline'));
        }
        else {
            label.insertAfter(element);
        }
    }

     });
</script>

<script type="text/javascript">

     $("#surveyImage13").submit(function(e) {
        e.preventDefault();

        var route=$('#surveyImage13').attr('action');
        var pivot_id = $("#questionnaire_pivot_id").val();

        // Get values of checked checkboxes
        var responses = $('.form-check-inline input').filter(':checked').map(function() {
          return this.value;
        }).get();

     var isFormValid = $("#surveyImage13").valid();

    if(isFormValid){

        $.ajax({
          type: "POST",
          url: route,
          data: {'responses': responses, 'pivot_id': pivot_id},
          success: function(response){

            $("#surveyImageForm").css("display", "none");
            $("#surveyImageAjax").css("display", "block");

            $('#SurveyTableAjaxColumn1').append(response[1]);
            $('#SurveyTableAjaxColumn2').append(response[0]);
          },
          error: function(){
            console.log('Error');
          }
        })
        }
     });

</script>
</code>```

答:
Why not give your forms a common class

```<code>$('.myClass').validate({ ...
})

$('.myClass').submit(...
</code>```

Body:
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

 <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...

                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

     </form>

Form with ID="surveyImage18"

<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

</form>

AJAX call

Body:
Why not give your forms a common class

$('.myClass').validate({ ...
})

$('.myClass').submit(...


问:
How can i post image with dio in flutter
i want to send image to server by jpg format by dio package ,
how can i do this ?

choose image method :

```<code>  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});
</code>```

upload image method :

```<code>  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});
</code>```

Anyone help me ?

thanks

答:
You can also use http for this purpose

```<code>Future<String> uploadImage(Asset asset,String orderId) async {

  // String to uri
  Uri uri = Uri.parse('Your URL');

  // create multipart request
  http.MultipartRequest request = http.MultipartRequest("POST", uri);

  ByteData byteData = await asset.getByteData();
  List<int> imageData = byteData.buffer.asUint8List();

  http.MultipartFile multipartFile =  http.MultipartFile.fromBytes(
   'image',
   imageData,
   filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
   contentType: MediaType("image", "jpg"),
  );

  // Add field to your request
  request.fields['FieldName'] = fieldValue;

  // add file to multipart
  request.files.add(multipartFile);
  // send
  var response = await request.send();

  // Decode response
  final respStr = await response.stream.bytesToString();

  return respStr;
</code>```

}

Body:
i want to send image to server by jpg format by dio package ,
how can i do this ?

choose image method :

  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});

upload image method :

  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});

Anyone help me ?

thanks

Body:
You can also use http for this purpose

Future<String> uploadImage(Asset asset,String orderId) async {

  // String to uri
  Uri uri = Uri.parse('Your URL');

  // create multipart request
  http.MultipartRequest request = http.MultipartRequest("POST", uri);

  ByteData byteData = await asset.getByteData();
  List<int> imageData = byteData.buffer.asUint8List();

  http.MultipartFile multipartFile =  http.MultipartFile.fromBytes(
   'image',
   imageData,
   filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
   contentType: MediaType("image", "jpg"),
  );

  // Add field to your request
  request.fields['FieldName'] = fieldValue;

  // add file to multipart
  request.files.add(multipartFile);
  // send
  var response = await request.send();

  // Decode response
  final respStr = await response.stream.bytesToString();

  return respStr;

}


问:
Entity Framework Core Parent Child items in the same model, children node returns null
I have a parent and child property inside one domain model.

```<code>public class TestModel
{
    public int ParentID { get; set; }
    public int ID{ get; set; }
    public string Name{ get; set; }
    public virtual TestModel parent { get; set; }
    public virtual List<TestModel> children { get; set; }
}
</code>```

When I write OnModelCreating event as below:

```<code>builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ID);
</code>```

In debug mode children node returns hierarchical same and I get 'Self referencing loop detected for property 'parent' with type TestModel' error on JsonConvert.SerializeObject.

When I change OnModelCreating event as below:

```<code>builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ParentID);
</code>```

Then children property returns null. How can I solve this problem? How can I load children property correctly?

I hope somebody can help me.

PS: TestModel not in any context so I cant Include. I create a sql query and get using FromSql()

答:
The second is the right one, but I suspect that when loading, you are not eagerly fetching the children. Try this:

```<code>var one = context.Set<TestModel>().Include(x => x.children).FirstOrDefault();
</code>```

Another option is to use lazy loading. See more here: https://learn.microsoft.com/en-us/ef/core/querying/related-data.

Body:
I have a parent and child property inside one domain model.

public class TestModel
{
    public int ParentID { get; set; }
    public int ID{ get; set; }
    public string Name{ get; set; }
    public virtual TestModel parent { get; set; }
    public virtual List<TestModel> children { get; set; }
}

When I write OnModelCreating event as below:

builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ID);

In debug mode children node returns hierarchical same and I get 'Self referencing loop detected for property 'parent' with type TestModel' error on JsonConvert.SerializeObject.

When I change OnModelCreating event as below:

builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ParentID);

Then children property returns null. How can I solve this problem? How can I load children property correctly?

I hope somebody can help me.

PS: TestModel not in any context so I cant Include. I create a sql query and get using FromSql()

Body:
The second is the right one, but I suspect that when loading, you are not eagerly fetching the children. Try this:

var one = context.Set<TestModel>().Include(x => x.children).FirstOrDefault();

Another option is to use lazy loading. See more here: https://learn.microsoft.com/en-us/ef/core/querying/related-data.


问:
Navigator PushReplacementName gives back button in flutter
This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.

First line below is for dismissing the dialog box. second one is to go to home screen.

 Navigator.of(context, rootNavigator: true).pop();
 Navigator.of(context).pushReplacementNamed(HomeScreen.id);
```

This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?

答:
That won't give the required result as you have already even popped the context away before calling another Navigator class. I tried the function Navigator.of(context).pushNamedAndRemoveUntil() but still got my HomeScreen pushed on stack twice with the back button on screen 1. Hence, I finally got this with the inbuilt function Navigator.of(context).popUntil(). You can run this dartpad code https://dartpad.dev/a10ed43452736b5c6b3d1abe6a7eda45 to view the desired effect or view the code below. Below is part of the code from the gist:

```<code>...
class ThirdPage extends StatelessWidget{
  static const routeName = '/third';
  @override
  Widget build(BuildContext context){
    void _nextPage(){
      //Logic here - ***************************
   Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
  }
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page'),
      ),
      body: Center(
        child: Text('Third Page'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _nextPage,
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Happy coding D:)

Body:
This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.

First line below is for dismissing the dialog box. second one is to go to home screen.

 Navigator.of(context, rootNavigator: true).pop();
 Navigator.of(context).pushReplacementNamed(HomeScreen.id);

This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?

Body:
That won't give the required result as you have already even popped the context away before calling another Navigator class. I tried the function Navigator.of(context).pushNamedAndRemoveUntil() but still got my HomeScreen pushed on stack twice with the back button on screen 1. Hence, I finally got this with the inbuilt function Navigator.of(context).popUntil(). You can run this dartpad code https://dartpad.dev/a10ed43452736b5c6b3d1abe6a7eda45 to view the desired effect or view the code below. Below is part of the code from the gist:

...
class ThirdPage extends StatelessWidget{
  static const routeName = '/third';
  @override
  Widget build(BuildContext context){
    void _nextPage(){
      //Logic here - ***************************
   Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
  }
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page'),
      ),
      body: Center(
        child: Text('Third Page'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _nextPage,
        child: Icon(Icons.add),
      ),
    );
  }
}

Happy coding D:)


问:
AWS API Gateway: error Invalid mapping expression parameter specified: method.response.header.access-control-allow-origin
For the first time in the last years with AWS API Gateway I got this strange blocking error, that can kills production environment: in one day many of my responses (not all) lost their Access-Control-Allow-Origin header. In web UI I also see that they are not exists. But they are still exists in exported Swagger file. And more than that - I cannot set any value, for '*' or 'https://example.com' I am getting error:

Invalid mapping expression specified: Validation Result: warnings :
  [], errors : [Invalid mapping expression parameter specified:
  method.response.header.access-control-allow-origin]

This is from yesterday (I did not change anything to get this defect), looks like horrible bug of AWS that blocks our development (main product is no longer available without CORS headers). And now I am afraid to use AWS API Gateway for production environment...

I tried to remove header in Method Response and add again, through the same web UI.

This is exported Swagger - for the same part as in screenshot. Here you can see my method.response.header.Access-Control-Allow-Origin. So in browser UI and exported file are not the same!

```<code>paths:
  /lineupmaps:
    get:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
      security:
      - cognito: []
      x-amazon-apigateway-integration:
        uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:988646599334:function:getLineUpMap/invocations"
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.access-control-allow-origin: "'https://happy-marketer.gms-ai.com'"
            responseTemplates:
              application/json: "$input.body"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        requestTemplates:
          application/json: "{\n    \"specs\": $input.params('specs'),\n    \"competitors\"\
            : $input.params('competitors'),\n    \"numberOfModels\": $input.params('numberOfModels')\n\
            }"
        contentHandling: "CONVERT_TO_TEXT"
        type: "aws"
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Max-Age:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Max-Age: "'86400'"
              method.response.header.Access-Control-Allow-Headers: "'Authorization'"
              method.response.header.Access-Control-Allow-Origin: "'https://happy-marketer.gms-ai.com'"
        passthroughBehavior: "when_no_match"
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        type: "mock"
</code>```

Tried to import exported Swagger, also with commented/removed responseParameters block: still the same error:

答: Thank you nachary: helped importing of my Swagger with removed method.response.header.access-control-allow-origin in the GET of one endpoint...

Body:
For the first time in the last years with AWS API Gateway I got this strange blocking error, that can kills production environment: in one day many of my responses (not all) lost their Access-Control-Allow-Origin header. In web UI I also see that they are not exists. But they are still exists in exported Swagger file. And more than that - I cannot set any value, for '*' or 'https://example.com' I am getting error:

Invalid mapping expression specified: Validation Result: warnings :
  [], errors : [Invalid mapping expression parameter specified:
  method.response.header.access-control-allow-origin]

This is from yesterday (I did not change anything to get this defect), looks like horrible bug of AWS that blocks our development (main product is no longer available without CORS headers). And now I am afraid to use AWS API Gateway for production environment...

I tried to remove header in Method Response and add again, through the same web UI.

This is exported Swagger - for the same part as in screenshot. Here you can see my method.response.header.Access-Control-Allow-Origin. So in browser UI and exported file are not the same!

paths:
  /lineupmaps:
    get:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
      security:
      - cognito: []
      x-amazon-apigateway-integration:
        uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:988646599334:function:getLineUpMap/invocations"
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.access-control-allow-origin: "'https://happy-marketer.gms-ai.com'"
            responseTemplates:
              application/json: "$input.body"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        requestTemplates:
          application/json: "{\n    \"specs\": $input.params('specs'),\n    \"competitors\"\
            : $input.params('competitors'),\n    \"numberOfModels\": $input.params('numberOfModels')\n\
            }"
        contentHandling: "CONVERT_TO_TEXT"
        type: "aws"
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Max-Age:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Max-Age: "'86400'"
              method.response.header.Access-Control-Allow-Headers: "'Authorization'"
              method.response.header.Access-Control-Allow-Origin: "'https://happy-marketer.gms-ai.com'"
        passthroughBehavior: "when_no_match"
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        type: "mock"

Tried to import exported Swagger, also with commented/removed responseParameters block: still the same error:


问:
Print Matching line and one line before from the matched line
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

```<code>[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

What i have tried:

I have tried following with grep and sed which somehow works..

```<code>$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

答:
It can be done with awk alone:

```<code>awk ' /Timed|failed/ { print previous, $0; }; {previous = $0;}' /var/log/samba/smbd.log.old
</code>```

Body:
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out

What i have tried:

I have tried following with grep and sed which somehow works..

$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

Body:
It can be done with awk alone:

awk ' /Timed|failed/ { print previous, $0; }; {previous = $0;}' /var/log/samba/smbd.log.old


问:
C# access string value from class inside another class
I am trying to access a string that's in a Class accessed through another Class, from a third Class.

In this case the SelectedCar is the SelectedItem in a ListView
&
and the SelectedModel is the SelectedItem in a ListView

Car

```<code>public class Car : ViewModelBase
{
    private string _name;
    private ObservableCollection<CarModel> _models;

    public Car()
    {

    }
    public Car(string name, ObservableCollection<CarModel> models)
    {
        Name = name;
        Models = models;
    }

    public Car(string name)
    {
        Name = name;
    }

    public static Car Create(string name, ObservableCollection<CarModel> models)
        => new Car(name, models);

    public static Car Create(string name)
        => new Car(name);

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public ObservableCollection<CarModel> Models
    {
        get => _models;
        set => SetProperty(ref _models, value);
    }
}
</code>```

CarViewModel

```<code>  public class CarViewModel : ViewModelBase, ICarViewModel
{
    private string _enteredModel;
    private string _enteredCar;

    private Car _selectedCar;
    private CarModel _selectedModel;

    private ObservableCollection<CarModel> _carModels;
    private ObservableCollection<Car> _cars;

    [DesignOnly(true)]
    public CarViewModel()
    {
        Cars = new ObservableCollection<Car>
        {
            Car.Create("Audi",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("A1"),
                    CarModel.Create("A2"),
                    CarModel.Create("A3"),
                    CarModel.Create("A4"),
                    CarModel.Create("A5")
                }),

            Car.Create("Mercedes",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("A-Class"),
                    CarModel.Create("B-Class"),
                    CarModel.Create("C-Class"),
                    CarModel.Create("E-Class"),
                    CarModel.Create("S-Class")
                }),

            Car.Create("BMW",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("1-Serie"),
                    CarModel.Create("2-Serie"),
                    CarModel.Create("3-Serie"),
                    CarModel.Create("4-Serie"),
                    CarModel.Create("5-Serie")
                }),

            Car.Create("Volkswagen",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("Golf"),
                    CarModel.Create("Passat"),
                    CarModel.Create("Arteon"),
                    CarModel.Create("T-Cross"),
                    CarModel.Create("Up!")
                }),

            Car.Create("Volvo",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("V60"),
                    CarModel.Create("V70"),
                    CarModel.Create("XC60"),
                    CarModel.Create("XC90"),
                    CarModel.Create("S90")
                }),
        };

        DeleteModelCommand = new DelegateCommand(DeleteModelExecuted, DeleteModelCanExecute);
        DeleteCarCommand = new DelegateCommand(DeleteCarExecuted, DeleteCarCanExecute);

        AddCarCommand = new DelegateCommand(AddCarExecuted, AddCarCanExecute);
        AddModelCommand = new DelegateCommand(AddModelExecuted, AddModelCanExecute);
    }

    public string EnteredModel
    {
        get => _enteredModel;
        set => SetProperty(ref _enteredModel, value);
    }

    public string EnteredCar
    {
        get => _enteredCar;
        set => SetProperty(ref _enteredCar, value);
    }

    public Car SelectedCar
    {
        get => _selectedCar;
        set => SetProperty(ref _selectedCar, value);
    }

    public CarModel SelectedModel
    {
        get => _selectedModel;
        set => SetProperty(ref _selectedModel, value);
    }

    public ObservableCollection<Car> Cars
    {
        get => _cars;
        set => SetProperty(ref _cars, value);
    }

    public ObservableCollection<CarModel> CarModels
    {
        get => _carModels;
        set => SetProperty(ref _carModels, value);
    }
}
</code>```

CarModifierViewModel

```<code> public class CarModifierViewModel : ViewModelBase, ICarModifierViewModel
{
    private CarColorModel _selectedColor;
    private CarModifierModel _selectedYear;

    private string _previouslySelectedCar;
    private string _previouslySelectedModel;

    private ObservableCollection<CarModifierModel> _modifierModels;

    private CarViewModel _carViewModelClass;

    [DesignOnly(true)]
    public CarModifierViewModel()
    {
        ModifierModels = new ObservableCollection<CarModifierModel>
        {
           CarModifierModel.Create(2000, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black")
           }),
           CarModifierModel.Create(2005, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White")
           }),
           CarModifierModel.Create(2010, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue")
           }),
           CarModifierModel.Create(2015, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue"),
               CarColorModel.Create("Red")
           }),
           CarModifierModel.Create(2020, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue"),
               CarColorModel.Create("Red"),
               CarColorModel.Create("Purple")
           })
        };
    }

    public CarColorModel SelectedColor
    {
        get => _selectedColor;
        set => SetProperty(ref _selectedColor, value);
    }

    public CarModifierModel SelectedYear
    {
        get => _selectedYear;
        set
        {
            SetProperty(ref _selectedYear, value);
            LoadCarAndModel();
        }
    }

    public string PreviouslySelectedCar
    {
        get => _previouslySelectedCar;
        set => SetProperty(ref _previouslySelectedCar, value);
    }

    public string PreviouslySelectedModel
    {
        get => _previouslySelectedModel;
        set => SetProperty(ref _previouslySelectedModel, value);
    }

    public ObservableCollection<CarModifierModel> ModifierModels
    {
        get => _modifierModels;
        set => SetProperty(ref _modifierModels, value);
    }

    public CarViewModel CarViewModelClass
    {
        get => _carViewModelClass;
        set => SetProperty(ref _carViewModelClass, value);
    }

    public void LoadCarAndModel()
    {
        CarViewModelClass = new CarViewModel();
        CarViewModelClass.SelectedCar = new Car();
        CarViewModelClass.SelectedCar.Name = new string(CarViewModelClass.SelectedCar.Name);

        PreviouslySelectedCar = CarViewModelClass?.SelectedCar?.Name;
        PreviouslySelectedModel = CarViewModelClass.SelectedModel.Name;

    }
}
</code>```

I hope I did not miss anything crucial, but how do I access the SelectedItem from another view? In CarModifierViewModel I tried instantiating the class to access but it does not load the SelectedItem..

答:
The solution is to use composition. You usually create a MainViewModel which has properties to expose all other view models to the views. The MainViewModel injects the required classes into the related view models using a constructor.

MainViewModel.cs

```<code>class MainViewModel
{
  public CarViewModel CarViewModel { get; set; }
  public CarModifierViewModel CarModifierViewModel { get; set; }

  public MainViewModel()
  {
    this.CarViewModel = new CarViewModel();
    this.CarModifierViewModel = new CarModifierViewModel(this.CarViewModel);
  }
}
</code>```

CarViewModel.cs

```<code>public class CarViewModel
{
  ...
}
</code>```

CarModifierViewModel.cs

```<code>public class CarModifierViewModel
{
  private CarViewModel CarViewModel { get; set; }

  public CarModifierViewModel(CarViewModel carViewModel)
  {
    this.CarViewModel = carViewModel;
  }

  public void LoadCarAndModel()
  {
    // Now 'CarViewModel' won't be null,
    // as long as you don't pass null to the constructor
    // or set the 'MainViewModel.CarViewModel' property to null
    PreviouslySelectedCar = this.CarViewModel.SelectedCar.Name;
    PreviouslySelectedModel = this.CarViewModel.SelectedModel.Name;
  }
}
</code>```

App.xaml

```<code><Application>
  <Application.Resources>
    <MainViewModel />
  </Application.Resources>
</Application>
</code>```

View1.xaml

```<code><UserControl DataContext="{StaticResource MainViewModel.CarViewModel}" />
</code>```

View2.xaml

```<code><UserControl DataContext="{StaticResource MainViewModel.CarModifierViewModel}" />
</code>```

Body:
I am trying to access a string that's in a Class accessed through another Class, from a third Class.

In this case the SelectedCar is the SelectedItem in a ListView
&
and the SelectedModel is the SelectedItem in a ListView

Car

public class Car : ViewModelBase
{
    private string _name;
    private ObservableCollection<CarModel> _models;

    public Car()
    {

    }
    public Car(string name, ObservableCollection<CarModel> models)
    {
        Name = name;
        Models = models;
    }

    public Car(string name)
    {
        Name = name;
    }

    public static Car Create(string name, ObservableCollection<CarModel> models)
        => new Car(name, models);

    public static Car Create(string name)
        => new Car(name);

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public ObservableCollection<CarModel> Models
    {
        get => _models;
        set => SetProperty(ref _models, value);
    }
}

CarViewModel

  public class CarViewModel : ViewModelBase, ICarViewModel
{
    private string _enteredModel;
    private string _enteredCar;

    private Car _selectedCar;
    private CarModel _selectedModel;

    private ObservableCollection<CarModel> _carModels;
    private ObservableCollection<Car> _cars;

    [DesignOnly(true)]
    public CarViewModel()
    {
        Cars = new ObservableCollection<Car>
        {
            Car.Create("Audi",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("A1"),
                    CarModel.Create("A2"),
                    CarModel.Create("A3"),
                    CarModel.Create("A4"),
                    CarModel.Create("A5")
                }),

            Car.Create("Mercedes",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("A-Class"),
                    CarModel.Create("B-Class"),
                    CarModel.Create("C-Class"),
                    CarModel.Create("E-Class"),
                    CarModel.Create("S-Class")
                }),

            Car.Create("BMW",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("1-Serie"),
                    CarModel.Create("2-Serie"),
                    CarModel.Create("3-Serie"),
                    CarModel.Create("4-Serie"),
                    CarModel.Create("5-Serie")
                }),

            Car.Create("Volkswagen",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("Golf"),
                    CarModel.Create("Passat"),
                    CarModel.Create("Arteon"),
                    CarModel.Create("T-Cross"),
                    CarModel.Create("Up!")
                }),

            Car.Create("Volvo",
                new ObservableCollection<CarModel>()
                {
                    CarModel.Create("V60"),
                    CarModel.Create("V70"),
                    CarModel.Create("XC60"),
                    CarModel.Create("XC90"),
                    CarModel.Create("S90")
                }),
        };

        DeleteModelCommand = new DelegateCommand(DeleteModelExecuted, DeleteModelCanExecute);
        DeleteCarCommand = new DelegateCommand(DeleteCarExecuted, DeleteCarCanExecute);

        AddCarCommand = new DelegateCommand(AddCarExecuted, AddCarCanExecute);
        AddModelCommand = new DelegateCommand(AddModelExecuted, AddModelCanExecute);
    }

    public string EnteredModel
    {
        get => _enteredModel;
        set => SetProperty(ref _enteredModel, value);
    }

    public string EnteredCar
    {
        get => _enteredCar;
        set => SetProperty(ref _enteredCar, value);
    }

    public Car SelectedCar
    {
        get => _selectedCar;
        set => SetProperty(ref _selectedCar, value);
    }

    public CarModel SelectedModel
    {
        get => _selectedModel;
        set => SetProperty(ref _selectedModel, value);
    }

    public ObservableCollection<Car> Cars
    {
        get => _cars;
        set => SetProperty(ref _cars, value);
    }

    public ObservableCollection<CarModel> CarModels
    {
        get => _carModels;
        set => SetProperty(ref _carModels, value);
    }
}

CarModifierViewModel

 public class CarModifierViewModel : ViewModelBase, ICarModifierViewModel
{
    private CarColorModel _selectedColor;
    private CarModifierModel _selectedYear;

    private string _previouslySelectedCar;
    private string _previouslySelectedModel;

    private ObservableCollection<CarModifierModel> _modifierModels;

    private CarViewModel _carViewModelClass;

    [DesignOnly(true)]
    public CarModifierViewModel()
    {
        ModifierModels = new ObservableCollection<CarModifierModel>
        {
           CarModifierModel.Create(2000, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black")
           }),
           CarModifierModel.Create(2005, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White")
           }),
           CarModifierModel.Create(2010, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue")
           }),
           CarModifierModel.Create(2015, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue"),
               CarColorModel.Create("Red")
           }),
           CarModifierModel.Create(2020, new ObservableCollection<CarColorModel>()
           {
               CarColorModel.Create("Silver"),
               CarColorModel.Create("Black"),
               CarColorModel.Create("White"),
               CarColorModel.Create("Blue"),
               CarColorModel.Create("Red"),
               CarColorModel.Create("Purple")
           })
        };
    }

    public CarColorModel SelectedColor
    {
        get => _selectedColor;
        set => SetProperty(ref _selectedColor, value);
    }

    public CarModifierModel SelectedYear
    {
        get => _selectedYear;
        set
        {
            SetProperty(ref _selectedYear, value);
            LoadCarAndModel();
        }
    }

    public string PreviouslySelectedCar
    {
        get => _previouslySelectedCar;
        set => SetProperty(ref _previouslySelectedCar, value);
    }

    public string PreviouslySelectedModel
    {
        get => _previouslySelectedModel;
        set => SetProperty(ref _previouslySelectedModel, value);
    }

    public ObservableCollection<CarModifierModel> ModifierModels
    {
        get => _modifierModels;
        set => SetProperty(ref _modifierModels, value);
    }

    public CarViewModel CarViewModelClass
    {
        get => _carViewModelClass;
        set => SetProperty(ref _carViewModelClass, value);
    }

    public void LoadCarAndModel()
    {
        CarViewModelClass = new CarViewModel();
        CarViewModelClass.SelectedCar = new Car();
        CarViewModelClass.SelectedCar.Name = new string(CarViewModelClass.SelectedCar.Name);

        PreviouslySelectedCar = CarViewModelClass?.SelectedCar?.Name;
        PreviouslySelectedModel = CarViewModelClass.SelectedModel.Name;

    }
}

I hope I did not miss anything crucial, but how do I access the SelectedItem from another view? In CarModifierViewModel I tried instantiating the class to access but it does not load the SelectedItem..

Body:
The solution is to use composition. You usually create a MainViewModel which has properties to expose all other view models to the views. The MainViewModel injects the required classes into the related view models using a constructor.

MainViewModel.cs

class MainViewModel
{
  public CarViewModel CarViewModel { get; set; }
  public CarModifierViewModel CarModifierViewModel { get; set; }

  public MainViewModel()
  {
    this.CarViewModel = new CarViewModel();
    this.CarModifierViewModel = new CarModifierViewModel(this.CarViewModel);
  }
}

CarViewModel.cs

public class CarViewModel
{
  ...
}

CarModifierViewModel.cs

public class CarModifierViewModel
{
  private CarViewModel CarViewModel { get; set; }

  public CarModifierViewModel(CarViewModel carViewModel)
  {
    this.CarViewModel = carViewModel;
  }

  public void LoadCarAndModel()
  {
    // Now 'CarViewModel' won't be null,
    // as long as you don't pass null to the constructor
    // or set the 'MainViewModel.CarViewModel' property to null
    PreviouslySelectedCar = this.CarViewModel.SelectedCar.Name;
    PreviouslySelectedModel = this.CarViewModel.SelectedModel.Name;
  }
}

App.xaml

<Application>
  <Application.Resources>
    <MainViewModel />
  </Application.Resources>
</Application>

View1.xaml

<UserControl DataContext="{StaticResource MainViewModel.CarViewModel}" />

View2.xaml

<UserControl DataContext="{StaticResource MainViewModel.CarModifierViewModel}" />


问:
Loop over files in directory with if statement (batch file)
I'm trying to create a bat file to compile all of the .java files in a directory and to run the class called Main (and output to tulemused.txt) I was able to do this for a single .java file with a set name but I don't know how to use batch scripting well enough to loop over all of the files.

```<code>@ECHO on

FOR /d %%f DO IF NOT %%f=="compile.bat" javac -encoding utf-8 %%f

java -Dfile.encoding=UTF8 Main > tulemused.txt

@ECHO off
</code>```

This is how far I got

答:
Found that this works even better since java wants to compile all of the classes at once but credit to Wasif for fixing the original loop</p>

```<code>@ECHO on
set string=javac -encoding utf-8
 FOR /r %%f In (*.java) DO call :concat %%~nf
%string%
set /P name="What is the name of the class with the main method? "
java -Dfile.encoding=UTF8 %name% >result.txt
pause

:concat
set string=%string% %1.java
</code>```

Body:
I'm trying to create a bat file to compile all of the .java files in a directory and to run the class called Main (and output to tulemused.txt) I was able to do this for a single .java file with a set name but I don't know how to use batch scripting well enough to loop over all of the files.

@ECHO on

FOR /d %%f DO IF NOT %%f=="compile.bat" javac -encoding utf-8 %%f

java -Dfile.encoding=UTF8 Main > tulemused.txt

@ECHO off

This is how far I got

Body:
Found that this works even better since java wants to compile all of the classes at once but credit to Wasif for fixing the original loop

@ECHO on
set string=javac -encoding utf-8
 FOR /r %%f In (*.java) DO call :concat %%~nf
%string%
set /P name="What is the name of the class with the main method? "
java -Dfile.encoding=UTF8 %name% >result.txt
pause

:concat
set string=%string% %1.java