问:
How to check the login functionality is work or not in ruby on rails?
I'm new in ruby on rails. I create simple login function.

But the login page is didnot go sucess page even the credential is valid.

I didnot know why this is happen. Please any one help what mistake i done.

I enclose my code is below,

Controller userlists_controller.rb

```<code>  def login
  end

  def login_action
      user = Userlist.find_by(email: params[:email])
      if user and user.authenticate(params[:password])
        session[:user_id] = user.id
        session[:user_name] = user.name
        redirect_to user, alert: "User logged in successfully"
      else
        redirect_to login_url, alert: "Invalid user/password combination"
      end
  end
</code>```

View login.html.erb

```<code><h1>Login</h1>
<% if flash[:alert] %>
    <div id="error_explanation">
        <p id="notice"><%= flash[:alert] %></p>
    </div>
<% end %>

<%= form_tag do %>
    <div class="field">
        <%= label_tag :email, 'Email' %>
        <%= email_field_tag :email, params[:email] %>
    </div>
    <div class="field">
        <%= label_tag :password, 'Password' %>
        <%= password_field_tag :password, params[:password] %>
    </div>
    <div class="actions">
        <%=submit_tag "Login" %>
    </div>
<% end %>
</code>```

route routes.rb

```<code>  get 'login' => 'userlists#login'
  post 'login' => 'userlists#login_action'
</code>```

答:
Try like this in  login.html.erb

```<code><h1>Login</h1>
<% if flash[:alert] %>
    <div id="error_explanation">
        <p id="notice"><%= flash[:alert] %></p>
    </div>
<% end %>

<%= form_tag '/login', {:method => :post } do  %>
<div class="field">
    <%= label_tag :email, 'Email' %>
    <%= email_field_tag :email, params[:email] %>
</div>
<div class="field">
    <%= label_tag :password, 'Password' %>
    <%= password_field_tag :password, params[:password] %>
</div>
<div class="actions">
    <%=submit_tag "Login" %>
</div>
<% end %>
</code>```

Try like this in userlists_controller.rb for login_action method

```<code>def login_action
  user = Userlist.find_by(email: params[:email])
  if user and user.authenticate(params[:password])
    session[:user_id] = user.id
    session[:user_name] = user.name
    redirect_to root_url, alert: "User logged in successfully"
  else
    redirect_to login_url, alert: "Invalid user/password combination"
  end
end
</code>```

And finally check user = Userlist.find_by(email: params[:email]) object. You are getting any values or not.

Body:
I'm new in ruby on rails. I create simple login function.

But the login page is didnot go sucess page even the credential is valid.

I didnot know why this is happen. Please any one help what mistake i done.

I enclose my code is below,

Controller userlists_controller.rb

  def login
  end

  def login_action
      user = Userlist.find_by(email: params[:email])
      if user and user.authenticate(params[:password])
        session[:user_id] = user.id
        session[:user_name] = user.name
        redirect_to user, alert: "User logged in successfully"
      else
        redirect_to login_url, alert: "Invalid user/password combination"
      end
  end

View login.html.erb

Login

<% if flash[:alert] %>

<%= flash[:alert] %>

<% end %>

<%= form_tag do %>

        <%= label_tag :email, 'Email' %>
        <%= email_field_tag :email, params[:email] %>

        <%= label_tag :password, 'Password' %>
        <%= password_field_tag :password, params[:password] %>

        <%=submit_tag "Login" %>

<% end %>

route routes.rb

  get 'login' => 'userlists#login'
  post 'login' => 'userlists#login_action'

Body:
Try like this in  login.html.erb

<h1>Login</h1>
<% if flash[:alert] %>
    <div id="error_explanation">
        <p id="notice"><%= flash[:alert] %></p>
    </div>
<% end %>

<%= form_tag '/login', {:method => :post } do  %>
<div class="field">
    <%= label_tag :email, 'Email' %>
    <%= email_field_tag :email, params[:email] %>
</div>
<div class="field">
    <%= label_tag :password, 'Password' %>
    <%= password_field_tag :password, params[:password] %>
</div>
<div class="actions">
    <%=submit_tag "Login" %>
</div>
<% end %>

Try like this in userlists_controller.rb for login_action method

def login_action
  user = Userlist.find_by(email: params[:email])
  if user and user.authenticate(params[:password])
    session[:user_id] = user.id
    session[:user_name] = user.name
    redirect_to root_url, alert: "User logged in successfully"
  else
    redirect_to login_url, alert: "Invalid user/password combination"
  end
end

And finally check user = Userlist.find_by(email: params[:email]) object. You are getting any values or not.


来源: stackexchange

问:
URL Rewrites are not generated after product import
I am trying to import products into my store however the rewrites are not generated in the database at all so the long default url remains. Anyone faced this issue and solved it before without using an external module?
The URL key is correctly set at the product page.

incorrect url

答:
The issue is with the importer. When there are no images available however they are defined in the feed file the importer will stop processing further information. For example it won't create the rewrites in the database and won't process stock related information. Won't create the relevant stock related records in the database neither. Database tables impacted ( the ones I actually found so far ):

url_rewrite
cataloginventory_stock_status
cataloginventory_stock_item

ContentLicense: CC BY-SA 4.0


问:
How to delete a value from the CSV json object?
I have a JSON response as :

```<code>xxx: ["fsd,das"]
</code>```

So I need to delete the value "fsd" from the json object but the problem is the response inside json is not the array , it is csv , so how do I delete it.
If anyone can come with the response.

Thanks

答:
You can flatten, split and join the array with a comma, and splice out the value you don't want using indexOf():

var obj = {xxx: ["a,b","c,d","e","f,g,h","i,j,k"]}

var letter = prompt()
obj.xxx = obj.xxx.flat().join(',').split(',')

var index = obj.xxx.indexOf(letter)
obj.xxx.splice(index, 1)

console.log(obj)```

Body:
I have a JSON response as :

xxx: ["fsd,das"]

So I need to delete the value "fsd" from the json object but the problem is the response inside json is not the array , it is csv , so how do I delete it.
If anyone can come with the response.

Thanks


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答:
I've had two systems that stored files in folders - both scaled poorly when we got to about 20K files in a folder.  Can be solved by using subfolders (2008-01, 2008-02 for example) but as said by others, you have synching issues.

Database allows you to archive/delete old resumes and no synching problems. You can compress/uncompress the text when storing/retrieving as long as you don't want to full text search the data.  Assuming a 10-20K file, you could compress to 1-2K probably.  Not that big.

OwnerDisplayName: Patrick

ContentLicense: CC BY-SA 2.5

Title: Storing word documents

OwnerDisplayName: MikeW


问:
How do I allow users to submit issues to my public repository?
I have a public repository on Azure DevOps.
When I enter in incognito I can see that users can only view work items, but cannot create them.

What is the proper way to allow issue submittion? Like the "Issues" section in GitHub repositories...

Thanks in advance.

答:
Unfortunately,there is currently no submit issues to my public repository this function.
You can submit issue in this forum： https://developercommunity.visualstudio.com。

When I enter in incognito I can see that users can only view work
  items, but cannot create them.

For this issue ,this is a normal situation.The function is designed like this.


问:
Generic interface and implementation - type cannot be converted
I have a generic interface defined as:

```<code>public interface ItemService<T extends Slicer, E extends ItemSlice> {
    E getItemHistory(final String id, final T slicer);
}
</code>```

And an implementation:

```<code>public class DynamoDbItemService implements ItemService<DynamoDbSlicer, DynamoDbItemSlice> {
    public DynamoDbItemSlice getItemHistory(final String id, final DynamoDbSlicer slicer) {
    }
}
</code>```

Here are the definitions of the four classes referenced above:

```<code>public interface Slicer {
    Map<String, ? extends Serializable> pointer();
}

public class DynamoDbSlicer implements Slicer {
    public Map<String, AttributeValue> pointer() {
    }
}

public interface ItemSlice extends Slice<Item> {
}

public interface Slice<T> {
    List<T> data();
    Slicer next();
}

public class DynamoDbItemSlice implements ItemSlice {
    publi ImmutableList<Item> data() {}
    public DynamoDbSlicer next() {}
}
</code>```

I would like to reference the ItemService interface but for it to be bound to the DynamoDbItemService implementation so I can swap it out if necessary which I can do like so:

```<code>ItemService<? extends Slicer, ? extends ItemSlice> itemService = new DynamoDbItemService itemService();
</code>```

but if I try to use itemService like this:

```<code>ItemSlice slice = itemService.getItemHistory(itemId, DynamoDbSlicer.first(1));
slice = itemService.getItemHistory(itemId, slice.next());
</code>```

I get these two compilation errors:

```<code>Error:(231, 82) java: incompatible types: item.pagination.DynamoDbSlicer cannot be converted to capture#1 of ? extends pagination.Slicer

Error:(238, 62) java: incompatible types: pagination.Slicer cannot be converted to capture#2 of ? extends pagination.Slicer
</code>```

I understand from this question that ? wildcards cannot be identical so my question is - can I do what I want - work with the interface? If so, how? Or am I approaching this incorrectly?

I have asked two previous questions related to this which have helped along the way (first and second)

答:
I don't see a reason why the following wouldn't work for you:

```<code>ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("",  new DynamoDbSlicer());
</code>```

But if you would like to make the code as modular as possible you can use this method to perform an unchecked cast (pure evil some say) and get the result you want:

```<code>public static void main(String[] args) {

    ItemSlice slice = getMySlice(new DynamoDbItemService());
}

@SuppressWarnings("unchecked")
public static <T extends Slicer, E extends ItemSlice> E getMySlice(ItemService<T, E> service) {
    return service.getItemHistory("", (T) new DynamoDbSlicer());
}
</code>```

And then of course there is the solution of passing the type inference responsibility to the actual field that is storing the value. I myself would go for this solution, as I think it offers the most flexibility:

```<code>public class DynamoDbItemService<T extends Slicer, E extends ItemSlice> implements ItemService<T, E>

ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("", new DynamoDbSlicer());
</code>```

Body:
I have a generic interface defined as:

public interface ItemService<T extends Slicer, E extends ItemSlice> {
    E getItemHistory(final String id, final T slicer);
}

And an implementation:

public class DynamoDbItemService implements ItemService<DynamoDbSlicer, DynamoDbItemSlice> {
    public DynamoDbItemSlice getItemHistory(final String id, final DynamoDbSlicer slicer) {
    }
}

Here are the definitions of the four classes referenced above:

public interface Slicer {
    Map<String, ? extends Serializable> pointer();
}

public class DynamoDbSlicer implements Slicer {
    public Map<String, AttributeValue> pointer() {
    }
}

public interface ItemSlice extends Slice<Item> {
}

public interface Slice<T> {
    List<T> data();
    Slicer next();
}

public class DynamoDbItemSlice implements ItemSlice {
    publi ImmutableList<Item> data() {}
    public DynamoDbSlicer next() {}
}

I would like to reference the ItemService interface but for it to be bound to the DynamoDbItemService implementation so I can swap it out if necessary which I can do like so:

ItemService<? extends Slicer, ? extends ItemSlice> itemService = new DynamoDbItemService itemService();

but if I try to use itemService like this:

ItemSlice slice = itemService.getItemHistory(itemId, DynamoDbSlicer.first(1));
slice = itemService.getItemHistory(itemId, slice.next());

I get these two compilation errors:

Error:(231, 82) java: incompatible types: item.pagination.DynamoDbSlicer cannot be converted to capture#1 of ? extends pagination.Slicer

Error:(238, 62) java: incompatible types: pagination.Slicer cannot be converted to capture#2 of ? extends pagination.Slicer

I understand from this question that ? wildcards cannot be identical so my question is - can I do what I want - work with the interface? If so, how? Or am I approaching this incorrectly?

I have asked two previous questions related to this which have helped along the way (first and second)

Body:
I don't see a reason why the following wouldn't work for you:

ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("",  new DynamoDbSlicer());

But if you would like to make the code as modular as possible you can use this method to perform an unchecked cast (pure evil some say) and get the result you want:

public static void main(String[] args) {

    ItemSlice slice = getMySlice(new DynamoDbItemService());
}

@SuppressWarnings("unchecked")
public static <T extends Slicer, E extends ItemSlice> E getMySlice(ItemService<T, E> service) {
    return service.getItemHistory("", (T) new DynamoDbSlicer());
}

And then of course there is the solution of passing the type inference responsibility to the actual field that is storing the value. I myself would go for this solution, as I think it offers the most flexibility:

public class DynamoDbItemService<T extends Slicer, E extends ItemSlice> implements ItemService<T, E>

ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("", new DynamoDbSlicer());


问:
why C++ std::min_element library function accepts functor that takes function object of bool return type rather than int like in C?
The C++ standard library function std::min_element() accepts a function object as is last argument, and that object's return type is bool. Why is it not int?

With true or false, we have only two options: < or >, but what if two entries are the same i.e. ==?

In C, this situation is handled by choosing the return type as int. But this is not done for std::min_element() in C++.

What is the reason for this?

答:
I'll point out that this is consistent with other parts of std, such as sort and map, which all order things based on a functor which satisfies Compare. The same question can be extended to all these things.

What is the reason?

The original author, and the standards committee, thought that it was a more natural way of expressing ordering.

There are some problems with using three way compare via int.

int has more than three values. You therefore have to do further arithmetic on the return value.

It's easier to fall into undefined behaviour

```<code>struct three_way_compare
{
     int operator()(int lhs, int rhs) { return lhs - rhs; }
     // Undefined behaviour when rhs is a large positive value and lhs is a large negative value
}
</code>```

You can synthesize three way comparison by calling your functor twice. The reference defines the requirements using

equiv(a, b), an expression equivalent to !comp(a, b) && !comp(b, a)

Note that for C++20, three way comparison is being added to the language with operator <=>. I'm not sure if existing algorithms are being changed to utilise it, when available.

Body:
I'll point out that this is consistent with other parts of std, such as sort and map, which all order things based on a functor which satisfies Compare. The same question can be extended to all these things.

What is the reason?

The original author, and the standards committee, thought that it was a more natural way of expressing ordering.

There are some problems with using three way compare via int.

int has more than three values. You therefore have to do further arithmetic on the return value.

It's easier to fall into undefined behaviour

struct three_way_compare
{
     int operator()(int lhs, int rhs) { return lhs - rhs; }
     // Undefined behaviour when rhs is a large positive value and lhs is a large negative value
}

You can synthesize three way comparison by calling your functor twice. The reference defines the requirements using

equiv(a, b), an expression equivalent to !comp(a, b) && !comp(b, a)

Note that for C++20, three way comparison is being added to the language with operator <=>. I'm not sure if existing algorithms are being changed to utilise it, when available.


问:
No values from JSON
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.

Here's the code

Utils class

```<code>public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
        JSONArray array = reader.getJSONArray("list");
        for (int i = 0; i<array.length(); i++){

            JSONObject secondReader = array.getJSONObject(i);
            JSONObject dataObject = secondReader.getJSONObject("main");
            for (int j = 0; j<dataObject.length(); j++){
                currentTemp = dataObject.getDouble("temp");
                minTemp = dataObject.getDouble("temp_min");
                maxTemp = dataObject.getDouble("temp_max");
                airPressure = dataObject.getDouble("pressure");
            }
            weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }
}
</code>```

MainActivity
       Double a,b,c,d;

```<code>    a = 0.0;
    b = 0.0;
    c = 0.0;
    d = 0.0;

    ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
    System.out.println(weathers);
</code>```

JSON structure

```<code> {
  "cod": "200",
  "message": 0.0074,
  "cnt": 40,
  "list": [
    {
      "dt": 1559131200,
      "main": {
        "temp": 22.1,
        "temp_min": 21.32,
        "temp_max": 22.1,
        "pressure": 1012.31,
        "sea_level": 1012.31,
        "grnd_level": 976.84,
        "humidity": 92,
        "temp_kf": 0.78
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 89
      },
      "wind": {
        "speed": 3.08,
        "deg": 213.025
      },
      "rain": {
        "3h": 0.875
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2019-05-29 12:00:00"
    },
    {
</code>```

Of course, there are more data. I've posted one "block"

How I may fix that?

答:
You're not getting the response from the server, you're trying to initialize a JSONObject with the URL.

To retrieve it you should replace this line:

```<code>JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
</code>```

with this code:

```<code>HttpURLConnection conn = null;
String data = null;
try {
   conn = (HttpURLConnection) new URL("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...").openConnection();
   conn.setRequestMethod("GET");
   conn.connect();

   BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = br.readLine()) != null) {
      sb.append(line + "\n");
   }
   br.close();
   data = sb.toString();
} catch (Exception e) {
   // do something
} finally {
   if (conn != null) {
      try {
         conn.disconnect();
      } catch (Exception ex) {
         // do something
      }
   }
}

JSONObject reader = new JSONObject(data);
</code>```

This code will retrieve the JSON object from the endpoint and convert it to a String object. Then you can create a JSONObject with it.

Title: No values from JSON

Body:
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.

Here's the code

Utils class

public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
        JSONArray array = reader.getJSONArray("list");
        for (int i = 0; i<array.length(); i++){

            JSONObject secondReader = array.getJSONObject(i);
            JSONObject dataObject = secondReader.getJSONObject("main");
            for (int j = 0; j<dataObject.length(); j++){
                currentTemp = dataObject.getDouble("temp");
                minTemp = dataObject.getDouble("temp_min");
                maxTemp = dataObject.getDouble("temp_max");
                airPressure = dataObject.getDouble("pressure");
            }
            weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }
}

MainActivity
       Double a,b,c,d;

    a = 0.0;
    b = 0.0;
    c = 0.0;
    d = 0.0;

    ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
    System.out.println(weathers);

JSON structure

 {
  "cod": "200",
  "message": 0.0074,
  "cnt": 40,
  "list": [
    {
      "dt": 1559131200,
      "main": {
        "temp": 22.1,
        "temp_min": 21.32,
        "temp_max": 22.1,
        "pressure": 1012.31,
        "sea_level": 1012.31,
        "grnd_level": 976.84,
        "humidity": 92,
        "temp_kf": 0.78
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 89
      },
      "wind": {
        "speed": 3.08,
        "deg": 213.025
      },
      "rain": {
        "3h": 0.875
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2019-05-29 12:00:00"
    },
    {

Of course, there are more data. I've posted one "block"

How I may fix that?

Body:
You're not getting the response from the server, you're trying to initialize a JSONObject with the URL.

To retrieve it you should replace this line:

JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");

with this code:

HttpURLConnection conn = null;
String data = null;
try {
   conn = (HttpURLConnection) new URL("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...").openConnection();
   conn.setRequestMethod("GET");
   conn.connect();

   BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = br.readLine()) != null) {
      sb.append(line + "\n");
   }
   br.close();
   data = sb.toString();
} catch (Exception e) {
   // do something
} finally {
   if (conn != null) {
      try {
         conn.disconnect();
      } catch (Exception ex) {
         // do something
      }
   }
}

JSONObject reader = new JSONObject(data);

This code will retrieve the JSON object from the endpoint and convert it to a String object. Then you can create a JSONObject with it.


问:
SMS using built in android messaging system which uses the Mobile Carrier
i'm working on an android application to send sms to other mobile numbers using android built in messaging system.....can anyone guide me how to do it???</p>

答:
You could use SmsManager.sendTextMessage

Hope this helps,

Phil Lello

ContentLicense: CC BY-SA 3.0


问:
How to reset filter values in react admin framework?
I have a filter component:

```<code>export const PostsFilter = (props) => (
  <Filter {...props}>
    <TextInput label='Post ID' source='id' alwaysOn />
    <TextInput label='User ID' source='user_id' alwaysOn />
  </Filter>
);
</code>```

I need to add a reset button that will clear input values. I understand that in should be done via dispatching smth to redux. So maybe somebody already solved this problem? Thanks!

答:
Unfortunately, setFilters does nothing for me.
Here is the solution to the problem:

<FormDataConsumer form={'filterForm'} alwaysOn source='stateId'>
      {({ formData, dispatch, ...rest }) => (
        <ReferenceInput
          resource={props.resource}
          source='stateId'
          reference='states'
          onChange={value => {
            dispatch(change('filterForm', 'districtId', null));
          }}
          allowEmpty>
          <SelectInput optionText='name' />
        </ReferenceInput>
      )}
    </FormDataConsumer>

    {(props.filterValues.stateId || props.filterValues.districtId) && (
      <ReferenceInput
        key={props.filterValues.stateId}
        source='districtId'
        reference='districts'
        filter={{ stateId: props.filterValues.stateId }}
        alwaysOn>
        <SelectInput optionText='name' />
      </ReferenceInput>
    )}
```

Body:
I have a filter component:

export const PostsFilter = (props) => (
  <Filter {...props}>
    <TextInput label='Post ID' source='id' alwaysOn />
    <TextInput label='User ID' source='user_id' alwaysOn />
  </Filter>
);

I need to add a reset button that will clear input values. I understand that in should be done via dispatching smth to redux. So maybe somebody already solved this problem? Thanks!


问:
Simple Spring Java @Configuration to @Autowire without @Bean
I want to make use of spring @Autowired in a java rest project. For the last days, I am trying to set up a simple spring java project with java configuration without explicit bean configuration to check that functionality out. But I can't get it to work. I may be missing something fundamental.

None of the approaches I found in the web and on this site solved my problem so far. I couldn't find a sample for exactly what I'm trying to achieve too. This is mainly due to the amount of different spring versions and approaches spread over the web.

Here is an as easy as I could come up with Java Spring rest sample. I added a few comments with how I interpret spring annotations, as I may err here too:

App base class

```<code>package restoverflow;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class App extends Application {

}
</code>```

Config class

```<code>package restoverflow;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //this is a configuration class and also found by spring scan
@ComponentScan  //this package and its subpackages are being checked for components and its subtypes
public class AppConfig {

}
</code>```

Some Pojo

```<code>package restoverflow;

public class Pojo {
    private String name;

    public String getName() {
        return name;
    }

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

}
</code>```

A service

```<code>package restoverflow;

import org.springframework.stereotype.Service;

@Service //this is a subtype of component and found by the componentscan
public class PojoService {
    public Pojo getPojo(){
        Pojo pojo = new Pojo();
        pojo.setName("pojoName");
        return pojo;
    }
}
</code>```

And finally a resource where the autowiring of the service should be done

```<code>package restoverflow;

import javax.ws.rs.GET;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/resource")
@Controller //this is a subtype of component and found by the componentscan
public class Resource {

    @Autowired //this tells to automatically instantiate PojoService with a default contructor instance of PojoService
    private PojoService pojoService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Pojo getPojo() {
        return pojoService.getPojo();
    }
}
</code>```

Pom:

```<code>...
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
...
</code>```

I want the pojoService to be instantiated. But I get a NullPointerException.

答:
It looks like you are using Field level injection.

Please go through below link to understand all types of injections:
https://www.vojtechruzicka.com/field-dependency-injection-considered-harmful/

Can't see any clear reason why pojoService is coming null.
Please check whether pojoService bean is being initialized properly. It might be due to pojoService bean has not been initialized and you are getting null in your controller.

Body:
I want to make use of spring @Autowired in a java rest project. For the last days, I am trying to set up a simple spring java project with java configuration without explicit bean configuration to check that functionality out. But I can't get it to work. I may be missing something fundamental.

None of the approaches I found in the web and on this site solved my problem so far. I couldn't find a sample for exactly what I'm trying to achieve too. This is mainly due to the amount of different spring versions and approaches spread over the web.

Here is an as easy as I could come up with Java Spring rest sample. I added a few comments with how I interpret spring annotations, as I may err here too:

App base class

package restoverflow;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class App extends Application {

}

Config class

package restoverflow;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //this is a configuration class and also found by spring scan
@ComponentScan  //this package and its subpackages are being checked for components and its subtypes
public class AppConfig {

}

Some Pojo

package restoverflow;

public class Pojo {
    private String name;

    public String getName() {
        return name;
    }

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

}

A service

package restoverflow;

import org.springframework.stereotype.Service;

@Service //this is a subtype of component and found by the componentscan
public class PojoService {
    public Pojo getPojo(){
        Pojo pojo = new Pojo();
        pojo.setName("pojoName");
        return pojo;
    }
}

And finally a resource where the autowiring of the service should be done

package restoverflow;

import javax.ws.rs.GET;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/resource")
@Controller //this is a subtype of component and found by the componentscan
public class Resource {

    @Autowired //this tells to automatically instantiate PojoService with a default contructor instance of PojoService
    private PojoService pojoService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Pojo getPojo() {
        return pojoService.getPojo();
    }
}

Pom:

...
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
...

I want the pojoService to be instantiated. But I get a NullPointerException.


问:
onChange event for HTML5 range
Currently the onChange event on my range inputs is firing at each step.

Is there a way to stop this event from firing until the user has let go of the slider?

I'm using the range to create a search query. I want to be able to run the search every time the form is changed but issuing a search request at each step of the slider's movement is too much.

Here's the code as it stands:

HTML:

```<code><div id="page">
    <p>Currently viewing page <span>1</span>.</p>
    <input class="slider" type="range" min="1" max="100" step="1" value="1" name="page" />
</div>
</code>```

JavaScript:

```<code>$(".slider").change(function() {
    $("#query").text($("form").serialize());
});
</code>```

Does that help?

答:
Let's add a simple ES6 alternative to the collection:

let timer;

const debounceChange = (value, callback) => {
    clearTimeout(timer);
    timer = setTimeout(() => callback(value), 500);
};
```

<p>When used in JSX it would look like this:</p>

```<input type="range" onChange={e => debounceChange(e.target.value, props.onChange)}/>
```

Title: onChange event for HTML5 range

Body:
Currently the onChange event on my range inputs is firing at each step.

Is there a way to stop this event from firing until the user has let go of the slider?

I'm using the range to create a search query. I want to be able to run the search every time the form is changed but issuing a search request at each step of the slider's movement is too much.

Here's the code as it stands:

HTML:

Currently viewing page 1.

    <input class="slider" type="range" min="1" max="100" step="1" value="1" name="page" />

JavaScript:

$(".slider").change(function() {
    $("#query").text($("form").serialize());
});

Does that help?

Body:
Let's add a simple ES6 alternative to the collection:

let timer;

const debounceChange = (value, callback) => {
    clearTimeout(timer);
    timer = setTimeout(() => callback(value), 500);
};

When used in JSX it would look like this:

<input type="range" onChange={e => debounceChange(e.target.value, props.onChange)}/>


问:
How do I properly encode a form in php
On my site users can add content to the database via a form. I want the users to be able to type anything in the form and for it all to be added to the database how they have entered it. At the moment I'm getting problems with a number of characters, namely slashes, &, ? etc.

What is the best way to allow all characters to be added to the database correctly?

Also, do you have to decode them when displaying them for it to work correctly? If so, how do I do that?

答:
htmlentities() may help you encode and decode html characters:

You can also use nl2br() to preserve line breaks from textarea elements:

Also you should use PDO for your database needs as it is much more secure than the old method of escaping data, mysql_real_escape_string()

Title: How do I properly encode a form in php


问:
PHP MySQL Insert not working without error
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

```<code><?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>
</code>```

答:
```<code>"INSERT INTO products(name, price, type, des, img) VALUES('$name', '$price', '$type', '$des', '$img')";

OR
"INSERT INTO products(name, price, type, des, img) VALUES(?, ?, ?, ?, ?)";
</code>```

Body:
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

<?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>


问:
PDO get the last ID inserted
I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.

I know that I have to use this statement:

```<code>LAST_INSERT_ID()
</code>```

That statement works with a query like this:

```<code>$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
</code>```

But if I want to get the ID using this statement:

```<code>$ID = LAST_INSERT_ID();
</code>```

I get this error:

```<code>Fatal error: Call to undefined function LAST_INSERT_ID()
</code>```

What am I doing wrong?

答:
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs  https://www.php.net/manual/en/language.oop5.basic.php

Title: PDO get the last ID inserted

Body:
I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.

I know that I have to use this statement:

LAST_INSERT_ID()

That statement works with a query like this:

$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";

But if I want to get the ID using this statement:

$ID = LAST_INSERT_ID();

I get this error:

Fatal error: Call to undefined function LAST_INSERT_ID()

What am I doing wrong?


问:
How can 'a' view the stream while 'b' is recording it with RecordRTC
Using RecordRTC how can I have one or more clients view the stream while it is being recorded. So for example, when user 'a' is recording their camera, how can 'b' view it. A meaningful answer will include a working example.

Almost as good would be a working example with something else than RecordRTC, as long as its focused on html/javascript.

答:
As i think you can use Broadcast Process. Means you can broadcast a's camera and also record that running stream with RecordRTC and other one can see that camera stream.
You can also make your stream private for a particular user.  </p>


问:
Drop-Down Lists with Conditional Data JS
I have a website and I want to include 2 drop down boxes.  The values in the second drop down box depend on the first.

For instance if option A in drop down 1 is chosen then the available choices in dropdown box 2 would be 1,2,3

And if option 2 is chosen then drop down box 2 will show 5,6,7.

I've tried using JavaScript to receive the result of the first box as an argument and then use an 'if statement' to select what array of answers should be used by drop box 2 however this has been to no avail

''' I don't have any reasonable code to show '''

From what I've tried I can receive the index of the first drop down box choice however I cannot get the second box to show my array for that choice

答:
```<code><html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<select id="ddl1">
<option selected value="1">A</option>
<option value="2">B</option>
</select>
<select id="ddl2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>

<script>
$("#ddl1").change(function(){
$('#ddl2 option').remove();
if($("#ddl1 option:selected").val()==1){
    $('#ddl2').append('<option value="1">1</option>');
    $('#ddl2').append('<option value="2">2</option>');
    $('#ddl2').append('<option value="3">3</option>');
    }
else if($("#ddl1 option:selected").val()==2){
    $('#ddl2').append('<option value="5">5</option>');
    $('#ddl2').append('<option value="6">6</option>');
    $('#ddl2').append('<option value="7">7</option>');
    }
});
</script>
</html>
</code>```


问:
How to show ProgressBar in centre of screen regardless layout types
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

```<code>Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
</code>```

答:
As ProgressDialog is deprecated, You can use Dialog(which by default appears in center of the screen) for showing progressbar in center.

layout_loading_progress_bar.xml :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="85dp">

<ProgressBar
    android:id="@+id/progress_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@id/progress_text"
    android:layout_margin="@dimen/dimen_10dp"
    android:theme="@style/AppTheme.WhiteAccent" />

<TextView
    android:id="@+id/progress_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="@dimen/dimen_10dp"
    android:text="Loading..."
    android:textColor="@color/textYellow"
    android:textSize="17sp" />
</code>```

LoadingProgressBar.java

```<code>public void showProgress(Context context, String message, boolean cancelable) {
    mDialog = new Dialog(context);
    mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mDialog.setContentView(R.layout.layout_loading_progress_bar);
    WindowManager.LayoutParams params = mDialog.getWindow().getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    mDialog.getWindow().setAttributes(params);
    ProgressBar mProgressBar = mDialog.findViewById(R.id.progress_bar);
    TextView progressText = mDialog.findViewById(R.id.progress_text);
    progressText.setText(message);
    progressText.setVisibility(View.VISIBLE);
    mProgressBar.setVisibility(View.VISIBLE);
    mProgressBar.setIndeterminate(true);
    mDialog.setCancelable(cancelable);
    mDialog.setCanceledOnTouchOutside(cancelable);
    mDialog.show();
}

public void hideProgress() {
    if (mDialog != null) {
        mDialog.dismiss();
        mDialog = null;
    }
}
</code>```

Body:
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Body:
As ProgressDialog is deprecated, You can use Dialog(which by default appears in center of the screen) for showing progressbar in center.

layout_loading_progress_bar.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="85dp">

<ProgressBar
    android:id="@+id/progress_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@id/progress_text"
    android:layout_margin="@dimen/dimen_10dp"
    android:theme="@style/AppTheme.WhiteAccent" />

<TextView
    android:id="@+id/progress_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="@dimen/dimen_10dp"
    android:text="Loading..."
    android:textColor="@color/textYellow"
    android:textSize="17sp" />

LoadingProgressBar.java

public void showProgress(Context context, String message, boolean cancelable) {
    mDialog = new Dialog(context);
    mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mDialog.setContentView(R.layout.layout_loading_progress_bar);
    WindowManager.LayoutParams params = mDialog.getWindow().getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    mDialog.getWindow().setAttributes(params);
    ProgressBar mProgressBar = mDialog.findViewById(R.id.progress_bar);
    TextView progressText = mDialog.findViewById(R.id.progress_text);
    progressText.setText(message);
    progressText.setVisibility(View.VISIBLE);
    mProgressBar.setVisibility(View.VISIBLE);
    mProgressBar.setIndeterminate(true);
    mDialog.setCancelable(cancelable);
    mDialog.setCanceledOnTouchOutside(cancelable);
    mDialog.show();
}

public void hideProgress() {
    if (mDialog != null) {
        mDialog.dismiss();
        mDialog = null;
    }
}


问:
How can I make webpack treeshake my ES6 module?
I have followed every guide out there for turning on tree shaking in webpack 4 but webpack still bundles code from a NPM module that I have set up to be treeshaken. How can I enable treeshaking and not include particular code in my web app?

Full source code in GitHub repo

I have a CRA (create-react-app) that imports a NPM module I created to test it that looks like this:

```<code>package
  index.mjs
  dist
    esm
      components
        image
          index.js
        index.js
      index.js
</code>```

with package.json like this:

```<code>  "main": "index",
  "module": "index.jsm",
  "sideEffects": false,
</code>```

that transpiles using babel with babelrc like:

```<code>{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false
      }
    ],
    "@babel/react",
    "@babel/flow"
  ]
}
</code>```

I have 3 React components: image, avatar (that imports image) and login-button that has this es6 code:

```<code>import React from 'react'

document.body.innerHTML = document.body.innerHTML + "<div>This is a side effect and should never have happened</div>"

export default () => <button>Login</button>
</code>```

The index file for the NPM es6 module:

```<code>import * as lib from './dist/esm'

export default lib
</code>```

In the CRA's app.js I have:

```<code>import TreeshakingTestModule from 'treeshaking-test-module'

function App() {
  return (
    <div className="App">
      <TreeshakingTestModule.Avatar />
    </div>
  );
}
</code>```

When I npm start it builds and renders the avatar but I also see the message.

Note that login-button is never used however the default export of my NPM package which does export the component is imported, however I read tutorials that explained that even default exports and re-exports should still work with tree shaking if what is exported is never used.

What is happening? What am I doing wrong?

Full source code in GitHub repo

答:
As far as I know, webpack three shakes by analysing imports statically, not by reading your code. You cannot expect webpack to realize you're only using Avatar from TreeshakingTestModule.

So you need to declare what you want to use at import level, by using named imports and exports:

```<code>import {Avatar} from 'treeshaking-test-module'

function App() {
  return (
    <div className="App">
      <Avatar />
    </div>
  );
}
</code>```

So webpack knows you're only using the Avatar export.

This means that Avatar needs to be a named export in your treeshaking-test-module module.

Body:
I have followed every guide out there for turning on tree shaking in webpack 4 but webpack still bundles code from a NPM module that I have set up to be treeshaken. How can I enable treeshaking and not include particular code in my web app?

Full source code in GitHub repo

I have a CRA (create-react-app) that imports a NPM module I created to test it that looks like this:

package
  index.mjs
  dist
    esm
      components
        image
          index.js
        index.js
      index.js

with package.json like this:

  "main": "index",
  "module": "index.jsm",
  "sideEffects": false,

that transpiles using babel with babelrc like:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false
      }
    ],
    "@babel/react",
    "@babel/flow"
  ]
}

I have 3 React components: image, avatar (that imports image) and login-button that has this es6 code:

import React from 'react'

document.body.innerHTML = document.body.innerHTML + "
This is a side effect and should never have happened
"

export default () => <button>Login</button>

The index file for the NPM es6 module:

import * as lib from './dist/esm'

export default lib

In the CRA's app.js I have:

import TreeshakingTestModule from 'treeshaking-test-module'

function App() {
  return (

      <TreeshakingTestModule.Avatar />

  );
}

When I npm start it builds and renders the avatar but I also see the message.

Note that login-button is never used however the default export of my NPM package which does export the component is imported, however I read tutorials that explained that even default exports and re-exports should still work with tree shaking if what is exported is never used.

What is happening? What am I doing wrong?

Full source code in GitHub repo

Body:
As far as I know, webpack three shakes by analysing imports statically, not by reading your code. You cannot expect webpack to realize you're only using Avatar from TreeshakingTestModule.

So you need to declare what you want to use at import level, by using named imports and exports:

import {Avatar} from 'treeshaking-test-module'

function App() {
  return (
    <div className="App">
      <Avatar />
    </div>
  );
}

So webpack knows you're only using the Avatar export.

This means that Avatar needs to be a named export in your treeshaking-test-module module.


问:
How to show each of the selected value from single select option in input tag
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value=""></code>```

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

答:
Im not entirely sure I understand you 100%, but if I do i think you want to be able to see all of the selected values in the input box? That you have selected, ever! If so:

var values = []

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  if (values.indexOf(selectedValue) === -1) { //prevents duplicate values
    values.push(selectedValue)
  }
  document.getElementById("myValues").setAttribute('value', values.join(' '))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValues" value=""></code>```

Body:
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}

<select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value="">

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

Body:
Im not entirely sure I understand you 100%, but if I do i think you want to be able to see all of the selected values in the input box? That you have selected, ever! If so:

var values = []

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  if (values.indexOf(selectedValue) === -1) { //prevents duplicate values
    values.push(selectedValue)
  }
  document.getElementById("myValues").setAttribute('value', values.join(' '))
}

<select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValues" value="">


问:
Set custom filter on Tomcat 8 using web.xml
I want to enable CORS Tomcat 8 using this method (custom filter)
Tomcat CORS filter

I'm confused on step making custom filter to be called in web.xml.

How to set the .java file? Where is the directory of this file (SimpleCORSFilter)?

```<code>public class SimpleCORSFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
      chain.doFilter(req, res);
  }
}
</code>```

答:
Define filter as example connected to URL:

```<code><filter>
    <filter-name>cors</filter-name>
    <filter-class>com.robin.filters.SimpleCORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Define filter as example connected to servlet:

```<code><filter>
    <filter-name>MyFilter</filter-name>
    <display-name>MyFilter</display-name>
    <filter-class>com.xxx.yyy.zzz.MyFilter</filter-class>
</filter>

<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <servlet-name>MyAction</servlet-name>
</filter-mapping>
</code>```

Body:
I want to enable CORS Tomcat 8 using this method (custom filter)
Tomcat CORS filter

I'm confused on step making custom filter to be called in web.xml.

How to set the .java file? Where is the directory of this file (SimpleCORSFilter)?

public class SimpleCORSFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
      chain.doFilter(req, res);
  }
}

Body:
Define filter as example connected to URL:

<filter>
    <filter-name>cors</filter-name>
    <filter-class>com.robin.filters.SimpleCORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Define filter as example connected to servlet:

<filter>
    <filter-name>MyFilter</filter-name>
    <display-name>MyFilter</display-name>
    <filter-class>com.xxx.yyy.zzz.MyFilter</filter-class>
</filter>

<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <servlet-name>MyAction</servlet-name>
</filter-mapping>


问:
Error linking libboost_system in Visual C++
I have a problem using boost.asio. I use Windows XP and Visual Studio 2005

I followed these steps:

I downloaded the latest version (http://sourceforge.net/projects/boost/files/boost/1.46.1/) of W: \boost_1_46_1

I set the environment variable INCLUDE : W:\boost_1_46_1

In the properties of my project (VS->tools->Options project&solutions->vcc++directories) I added $(INCLUDE)

I added in my file. h this:

I get the following error:

LINK : fatal error LNK1104: cannot open file 'libboost_system-vc80-mt-gd-1_46_1.lib

答: This is a linker error. Find the lib, and go to linker input, and add it there. Be sure to set the libpath as well. This picture should guide you:


问:
How do I implement the overflow code? I do not know what's wrong
How do I implement the overflow code?

I do not know what's wrong. A result is a negative number in the middle.Below is the code snippet

```<code>module fibonacci(input clk, input rst, output [7:0]out, output reg overflow);

reg [7:0]a,b;

always@(posedge rst)
begin
    a =8'b0;
    b =8'b1;
end
always@(posedge clk)
begin
    if ( a < 8'b11111111 ) begin
        b = a + b ;
        a = b - a ;

    end

    else begin

    overflow = 1'b1;   //is that wrong??

    end
end

assign out = a ;

endmodule
</code>```

and testbench code here

```<code>initial begin

rst = 1;
clk =0;

#0.5
rst = 0;
end

always begin
#1
clk = !clk;
end

fibonacci fib(clk,rst,out,overflow);
endmodule
</code>```

Let me know what's wrong

答:
The reason for this negative number is that the number is interpreted in the two's complement representation. The actual number you expect after 89 is 144, which is 10010000in binary. In the two's complement representation, however, the most-significant bit is the sign of the number. A '1' indicates that this should be a negative number, which can be calculated as follows:

```<code>~10010000 + 1 = 01101111 + 1 = 01110000 = (-)112
</code>```

There are by the way several other catches to the code you posted. Let me first answer this question:

overflow = 1'b1;   //is that wrong??

Not this particular line, but the way overflow is handled is not completely correct. In your code, overflow can only become xor 1. It will never be 0. You should assign overflow to 0 in the first part of you conditional block and in the reset part.

The second thing is that you should use non-blocking assignments in Verilog to create sequential logic. In your code, you are using blocking assigments, which means that you first update b, and then update a with the already updated value b. If you need to use blocking assignments, you should create a combinational block.

Furthermore, you should combine the clock sensitive part and the reset sensitive part, so that a, b, and overflow are all modified by the same always block.

All these suggestions would roughly translate to:

```<code>always @(*)
begin
    b_next = a + b;
    a_next = b_next - a;
end

always @(posedge clk or negedge rst)
begin
    if (~rst) begin
        a <= 8'b0;
        b <= 8'b1;
        overflow <= 1'b0;
    end
    else if (a < 8'b11111111) begin
        b <= b_next;
        a <= a_next;
        overflow <= 1'b0
    end
    else begin
        overflow <= 1'b1;
    end
end
</code>```

As you can see, I also transformed the reset to an asynchronous, active-low reset. Although this is not mandatory, it is pretty common. The reset-signal is meant to keep all flops in reset-state, even when the power of a device comes up slowly. If the reset-signal is active-high, the signal itself may come up slowly.

Body:
How do I implement the overflow code?

I do not know what's wrong. A result is a negative number in the middle.Below is the code snippet

module fibonacci(input clk, input rst, output [7:0]out, output reg overflow);

reg [7:0]a,b;

always@(posedge rst)
begin
    a =8'b0;
    b =8'b1;
end
always@(posedge clk)
begin
    if ( a < 8'b11111111 ) begin
        b = a + b ;
        a = b - a ;

    end

    else begin

    overflow = 1'b1;   //is that wrong??

    end
end

assign out = a ;

endmodule

and testbench code here

initial begin

rst = 1;
clk =0;

#0.5
rst = 0;
end

always begin
#1
clk = !clk;
end

fibonacci fib(clk,rst,out,overflow);
endmodule

Let me know what's wrong

Body:
The reason for this negative number is that the number is interpreted in the two's complement representation. The actual number you expect after 89 is 144, which is 10010000in binary. In the two's complement representation, however, the most-significant bit is the sign of the number. A '1' indicates that this should be a negative number, which can be calculated as follows:

~10010000 + 1 = 01101111 + 1 = 01110000 = (-)112

There are by the way several other catches to the code you posted. Let me first answer this question:

overflow = 1'b1;   //is that wrong??

Not this particular line, but the way overflow is handled is not completely correct. In your code, overflow can only become xor 1. It will never be 0. You should assign overflow to 0 in the first part of you conditional block and in the reset part.

The second thing is that you should use non-blocking assignments in Verilog to create sequential logic. In your code, you are using blocking assigments, which means that you first update b, and then update a with the already updated value b. If you need to use blocking assignments, you should create a combinational block.

Furthermore, you should combine the clock sensitive part and the reset sensitive part, so that a, b, and overflow are all modified by the same always block.

All these suggestions would roughly translate to:

always @(*)
begin
    b_next = a + b;
    a_next = b_next - a;
end

always @(posedge clk or negedge rst)
begin
    if (~rst) begin
        a <= 8'b0;
        b <= 8'b1;
        overflow <= 1'b0;
    end
    else if (a < 8'b11111111) begin
        b <= b_next;
        a <= a_next;
        overflow <= 1'b0
    end
    else begin
        overflow <= 1'b1;
    end
end

As you can see, I also transformed the reset to an asynchronous, active-low reset. Although this is not mandatory, it is pretty common. The reset-signal is meant to keep all flops in reset-state, even when the power of a device comes up slowly. If the reset-signal is active-high, the signal itself may come up slowly.


问:
Does Java have a native object pool implementation?
I want to use an object pool for managing SMTP server connections, since they are very expensive to create (takes half of the total time of sending an email). So far I found the only options to be:

Use Apache Commons Pool or some other 3rd party library

Write it myself (risky!)

Doesn't the JDK provide an object pool? I rather not depend on a 3rd party and this seems like a pretty generic/basic feature to me.

答:
Doesn't the JDK provide an object pool?

As of Java 11, the Java SE libraries do not provide a general purpose object pool.

But if you look around, you will probably find a range of 3rd party libraries which do.

I rather not depend on a 3rd party.

In the words of the Rolling Stones song:

"No, you can't always get what you want ...."

But seriously, the Sun / Oracle Java developers never saw as it as Java SE's role to provide all of the libraries you could possibly ever need.  If you exclude 3rd party dependencies from your products, then you will end up writing and maintaining a lot more code than is necessary.


问:
How to delete a value from the CSV json object?
I have a JSON response as :

```<code>xxx: ["fsd,das"]
</code>```

So I need to delete the value "fsd" from the json object but the problem is the response inside json is not the array , it is csv , so how do I delete it.
If anyone can come with the response.

Thanks

答:
I can see, inside the json object it is an array of string.
Take that string use str.replace() to delete that part from it and put it back.

Body:
I have a JSON response as :

xxx: ["fsd,das"]

So I need to delete the value "fsd" from the json object but the problem is the response inside json is not the array , it is csv , so how do I delete it.
If anyone can come with the response.

Thanks


问:
Want to add icon on Button, drawableTop is not working Android
I want to add call icon on Button but drawableTop is not working.

```<code><LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp">
        <Button
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</code>```

答:
when using androidx with the material ui library instead of the support library

```<code>implementation 'com.google.android.material:material:1.0.0'
</code>```

you will need to use

```<code><androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_camera"
    android:text="Camera" />
</code>```

Body:
I want to add call icon on Button but drawableTop is not working.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp">
        <Button
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

Body:
when using androidx with the material ui library instead of the support library

implementation 'com.google.android.material:material:1.0.0'

you will need to use

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_camera"
    android:text="Camera" />


问:
What's the right way to create a mosquitto subscription with a device and IoTAgent-UL
I'm currently developing a Fiware based network, in which I have devices that report via HTTP and JSON over MQTT and work fine. The network has increased and now I need to attach some devices that use the UltraLight protocol. Doing so, I encountered some troubles.

I followed (to the best of my knowledge) the official documentation provided by the FIWARE Foundation in different sites (the official github repo, readthedocs, and so on). I tried installing the new agent on the same machine as the JSON agent, and it didn't work -more on that later-. In order to discard any conflicts, I used another VM in which -over Docker this time- I deployed a new instance of Orion CB, Mosquitto CB, mongo and the agent; a new complete stack of Fiware, basically.

After everything was deployed, I created a new service group on the agent via the rest API (POST /iot/devices), gave it an api key and the CB address. In this step I left the resource field empty, because I don´t really know what role does it play in the whole system. The response was 201, as expected.
The next step was to provision a device, which I did by POSTing to agent/iot/devices with the attributes I wanted, and the api key mentioned in last paragraph. Once again, the response was 201.

The problem arises when I try to publish a new measurement using mosquitto_pub. The command runs smoothly but the entity in Orion does not get updated. Accessing Orions DB (mongo) I can check that the entity was created successfully but it has an empty value. Moreover, checking the logs yields the following:

```<code>mosquitto    | 1559157902: New connection from 10.150.150.173 on port 1883.
mosquitto    | 1559157902: New client connected from 10.150.150.173 as mosqpub|28750-mqtt (p1, c1, k60).
fiware-iot-agent | time=2019-05-29T19:25:02.374Z | lvl=DEBUG | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IoTAgentNGSI.MongoDBGroupRegister arams ["resource","apikey"] with queryObj {"resource":"/iot/d","apikey":"apikeymia"} | comp=IoTAgent
fiware-iot-agent | time=2019-05-29T19:25:02.381Z | lvl=DEBUG | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IoTAgentNGSI.MongoDBGroupRegister elds [["resource","apikey"]] not found: [{"resource":"/iot/d","apikey":"apikeymia"}] | comp=IoTAgent
fiware-iot-agent | time=2019-05-29T19:25:02.382Z | lvl=ERROR | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IOTAUL.Common.Binding | srv=n/a | essing device measures [/apikeymia/motion003/attrs] | comp=IoTAgent
mosquitto    | 1559157902: Client mosqpub|28750-mqtt disconnected.
</code>```

after each try of publishing a new meassurment.

Any help would be appreciated

答:
In this step I left the resource field empty, because I don´t really know what role does it play in the whole system

Looking to the logs:

```<code>[...] queryObj {"resource":"/iot/d","apikey":"apikeymia"} | comp=IoTAgent
[...] not found: [{"resource":"/iot/d","apikey":"apikeymia"}] | comp=IoTAgent
</code>```

I'd suggest using "/iot/d" instead of empty for the resource field. Maybe that could solve the problem.

Body:
I'm currently developing a Fiware based network, in which I have devices that report via HTTP and JSON over MQTT and work fine. The network has increased and now I need to attach some devices that use the UltraLight protocol. Doing so, I encountered some troubles.

I followed (to the best of my knowledge) the official documentation provided by the FIWARE Foundation in different sites (the official github repo, readthedocs, and so on). I tried installing the new agent on the same machine as the JSON agent, and it didn't work -more on that later-. In order to discard any conflicts, I used another VM in which -over Docker this time- I deployed a new instance of Orion CB, Mosquitto CB, mongo and the agent; a new complete stack of Fiware, basically.

After everything was deployed, I created a new service group on the agent via the rest API (POST /iot/devices), gave it an api key and the CB address. In this step I left the resource field empty, because I don´t really know what role does it play in the whole system. The response was 201, as expected.
The next step was to provision a device, which I did by POSTing to agent/iot/devices with the attributes I wanted, and the api key mentioned in last paragraph. Once again, the response was 201.

The problem arises when I try to publish a new measurement using mosquitto_pub. The command runs smoothly but the entity in Orion does not get updated. Accessing Orions DB (mongo) I can check that the entity was created successfully but it has an empty value. Moreover, checking the logs yields the following:

mosquitto    | 1559157902: New connection from 10.150.150.173 on port 1883.
mosquitto    | 1559157902: New client connected from 10.150.150.173 as mosqpub|28750-mqtt (p1, c1, k60).
fiware-iot-agent | time=2019-05-29T19:25:02.374Z | lvl=DEBUG | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IoTAgentNGSI.MongoDBGroupRegister arams ["resource","apikey"] with queryObj {"resource":"/iot/d","apikey":"apikeymia"} | comp=IoTAgent
fiware-iot-agent | time=2019-05-29T19:25:02.381Z | lvl=DEBUG | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IoTAgentNGSI.MongoDBGroupRegister elds [["resource","apikey"]] not found: [{"resource":"/iot/d","apikey":"apikeymia"}] | comp=IoTAgent
fiware-iot-agent | time=2019-05-29T19:25:02.382Z | lvl=ERROR | corr=2c8aa6e3-faab-4166-9e20-0b362c165939 | trans=2c8aa6e3-faab-4166-9e20-0b362c165939 | op=IOTAUL.Common.Binding | srv=n/a | essing device measures [/apikeymia/motion003/attrs] | comp=IoTAgent
mosquitto    | 1559157902: Client mosqpub|28750-mqtt disconnected.

after each try of publishing a new meassurment.

Any help would be appreciated

Body:
In this step I left the resource field empty, because I don´t really know what role does it play in the whole system

Looking to the logs:

[...] queryObj {"resource":"/iot/d","apikey":"apikeymia"} | comp=IoTAgent
[...] not found: [{"resource":"/iot/d","apikey":"apikeymia"}] | comp=IoTAgent

I'd suggest using "/iot/d" instead of empty for the resource field. Maybe that could solve the problem.


问:
Hibernate Map an object without relation
I have a situation where i have relations like this:

A person has one or more addresses.
A customer has one or more addresses.

Person,customers and addresses are separate tables.

I used to do this with the @OneToMany relations.
This is giving me problems since our flex client is sending me objects wich are created in the client and have to be created in the DB.

If the client sends me a person and customer which reference to the same address hibernate will create two address objects since the two address object are not the same java objects (not the same pointers).

This is a problem which is caused by BlazeDS and Dozer which will create new objects when they are send to the server.

So what i would like to have is the address id in the person and customer object without an relation so hibernate does not create the objects. But when i read a person object i would like to fill a transient address object based on the stored address id.

Does anyone know if this is possible?

答:
There's two issues here:

Lazy loading of data and

Entity resolution / Single canonical instance of an entity on the client

There are frameworks available to help, but the problem doesn't yet have a great universal solution.

dpHibernate will help with the lazy loading of the data - ie:

when I read a person object I would like to fill a transient address object based on the stored address id

Unfortunately entity resolution is not yet supported across multiple calls in dpHibernate.  ie - If a call returns the same object in two locations within a server call (eg., the same Address entity in both Customer id:1 and Customer id:2 then you'll receive a single instance of Address in both customer objects.

However, if the data is loaded over seperate calls, you'll receive two instances of Address.  This is an issue which is slated for implementation in v3.

I believe the Cairngorm Integration library attempts to address this issue, however the wiki suggests it's LCDS only.  You could investigate what is required to implement this with BlazeDS.  I haven't used this library, so can't speak to how well it will solve your issues.


问:
Remove everything from the master branch
I have two branches - develop and master.
I worked constantly on the dev branch and the master is completely unnecessary code, quite different than on dev branch.

how to transfer everything from dev to master in such a way that nothing is left of the old master ?

答:
There are three options:

First - if you want to destroy every trace of the history of master you can just set master to dev -- similar to the answers of @Krantisinh and @ashishmohite:

```<code>git branch -f master dev
</code>```

If other people have build upon the old state of master they are screwed. So talk to them before you do that.

Second - you want to keep the history of master but swap out the contents: Then you are doing a special merge like this:

```<code>git checkout master

# git merge -s theirs simulation
git merge -s ours dev
git branch temp_THEIRS
git reset --hard dev
git reset --soft temp_THEIRS
git commit --amend
git branch -D temp_THEIRS
</code>```

This merges dev into master but takes all content from dev  -- no conflicts - no questions asked. This comes from https://stackoverflow.com/a/56368650/947357.

Third - (as per comment) if you want to throw away master (as in "First") but also start master without any history:

```<code>git checkout --orphan new-master
git commit -m "start from scratch again"
git branch --force -M new-master master
</code>```

After that dev and master do not share any history.

Body:
There are three options:

First - if you want to destroy every trace of the history of master you can just set master to dev -- similar to the answers of @Krantisinh and @ashishmohite:

git branch -f master dev

If other people have build upon the old state of master they are screwed. So talk to them before you do that.

Second - you want to keep the history of master but swap out the contents: Then you are doing a special merge like this:

git checkout master

# git merge -s theirs simulation
git merge -s ours dev
git branch temp_THEIRS
git reset --hard dev
git reset --soft temp_THEIRS
git commit --amend
git branch -D temp_THEIRS

This merges dev into master but takes all content from dev  -- no conflicts - no questions asked. This comes from https://stackoverflow.com/a/56368650/947357.

Third - (as per comment) if you want to throw away master (as in "First") but also start master without any history:

git checkout --orphan new-master
git commit -m "start from scratch again"
git branch --force -M new-master master

After that dev and master do not share any history.


问:
Can we create local account users with a gmail address?
We are using ADAL.Net to create users in Azure AD. using SinginNames, we can provide any email address (gmail or non-domain emails) as username to create Azure AD Local account.

when we try the same using Microsoft Graph (MSAL.Net), we are not able to create a user:

```<code>Code: Request_BadRequest
Message: Property userPrincipalName is invalid.
</code>```

How can we create gmail address as the username using Microsoft Graph or the Microsoft Graph Client Library?

The newly created account should be local user account, not a guest user.

```<code>var user = new User
{
    AccountEnabled = true,
    DisplayName = "displayName-value",
    MailNickname = "mailNickname-value",
    UserPrincipalName = "vetrivelmp1@gmail.com",
    PasswordProfile = new PasswordProfile
    {
    ForceChangePasswordNextSignIn = true,
    Password = "Test123!@#"
    }
};

var graphClient = await _msGraphHelper.GetMsGraphClientAsync();
var createdUser = await graphClient
    .Users
    .Request()
    .AddAsync(user);
</code>```

答:
No You can not. You must have to request with tenant specific email following sample:

Request URL: https://graph.microsoft.com/v1.0/users

```<code>{
  "accountEnabled": true,
  "displayName": "KironTestDisplayName",
  "mailNickname": "KironTestNickName",
  "userPrincipalName": "KironTestingCreateUserWithMember@MyTenant.onmicrosoft.com",
  "userType":"guest",
  "passwordProfile" : {
    "forceChangePasswordNextSignIn": true,
    "password": "Test@pass420"
  }
}
</code>```

Points to Remember:

Get the proper token in which tenant you are going to create user

Need necessary request permission

userPrincipalName should follow as
UserName@tenant-value.onmicrosoft.com

"userType":"guest" Or "Member" You can add

Note: Mail should be like myUser@Mytenant.onmicrosoft.com Other then you would encounter 400 request error like Property userPrincipalName is invalid

Your Case:

If you wanted to create user using gmail account then request pattern need to be changed You have to request for invitation API like below:

Request Url:  https://graph.microsoft.com/v1.0/invitations

Request Body:

```<code>{
  "invitedUserEmailAddress": "TestGmailUser@gmailUser",
  "inviteRedirectUrl": "https://myapp.com"
}
</code>```

Response:

Note: If go to azure portal you would see you cannot add gmail user as domain member you add as guest user after invitation. So this
  why you need above request pattern. Hope you are clear now.

Gmail User Add SDK:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var invitation = new Invitation
{
    InvitedUserEmailAddress = "TestGmailUser@gmailUser",
    InviteRedirectUrl = "https://myapp.com"
};

await graphClient.Invitations
    .Request()
    .AddAsync(invitation);
```

Azure Portal Verify:

I have successfully added gmail user on my portal using above request. See the screen shot below:

Body:
We are using ADAL.Net to create users in Azure AD. using SinginNames, we can provide any email address (gmail or non-domain emails) as username to create Azure AD Local account.

when we try the same using Microsoft Graph (MSAL.Net), we are not able to create a user:

Code: Request_BadRequest
Message: Property userPrincipalName is invalid.

How can we create gmail address as the username using Microsoft Graph or the Microsoft Graph Client Library?

The newly created account should be local user account, not a guest user.

var user = new User
{
    AccountEnabled = true,
    DisplayName = "displayName-value",
    MailNickname = "mailNickname-value",
    UserPrincipalName = "vetrivelmp1@gmail.com",
    PasswordProfile = new PasswordProfile
    {
    ForceChangePasswordNextSignIn = true,
    Password = "Test123!@#"
    }
};

var graphClient = await _msGraphHelper.GetMsGraphClientAsync();
var createdUser = await graphClient
    .Users
    .Request()
    .AddAsync(user);

Body:
No You can not. You must have to request with tenant specific email following sample:

Request URL: https://graph.microsoft.com/v1.0/users

{
  "accountEnabled": true,
  "displayName": "KironTestDisplayName",
  "mailNickname": "KironTestNickName",
  "userPrincipalName": "KironTestingCreateUserWithMember@MyTenant.onmicrosoft.com",
  "userType":"guest",
  "passwordProfile" : {
    "forceChangePasswordNextSignIn": true,
    "password": "Test@pass420"
  }
}

Points to Remember:

Get the proper token in which tenant you are going to create user

Need necessary request permission

userPrincipalName should follow as
UserName@tenant-value.onmicrosoft.com

"userType":"guest" Or "Member" You can add

Note: Mail should be like myUser@Mytenant.onmicrosoft.com Other then you would encounter 400 request error like Property userPrincipalName is invalid

Your Case:

If you wanted to create user using gmail account then request pattern need to be changed You have to request for invitation API like below:

Request Url:  https://graph.microsoft.com/v1.0/invitations

Request Body:

{
  "invitedUserEmailAddress": "TestGmailUser@gmailUser",
  "inviteRedirectUrl": "https://myapp.com"
}

Response:

Note: If go to azure portal you would see you cannot add gmail user as domain member you add as guest user after invitation. So this
  why you need above request pattern. Hope you are clear now.

Gmail User Add SDK:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var invitation = new Invitation
{
    InvitedUserEmailAddress = "TestGmailUser@gmailUser",
    InviteRedirectUrl = "https://myapp.com"
};

await graphClient.Invitations
    .Request()
    .AddAsync(invitation);

Azure Portal Verify:

I have successfully added gmail user on my portal using above request. See the screen shot below:


问:
Alexa responding before data is returned
I'm new to promises, async/await, and Alexa/lambda so bear with me.

My function is returning prior to the data being returned. I had a similar issue where I was getting an error, but have since edited my function quite a bit and therefore asking a new question. I'm now no longer getting an error, but instead my data is being returned first, then the promise is executing.

I've tried re-writing the promise/function after reading many, many SO, google, and amazon developer forums. Nothing seems to be working for me.

```<code>const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    async handle(handlerInput) {
        const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
        let responseData, promise;

         checkAuthenticationStatus(handlerInput,function(json){
            console.log('waited!')
            if(json.error) {
                return handlerInput.responseBuilder.speak(messages.NO_ACCESS).withSimpleCard('Unauthorized Request', messages.NO_ACCESS).getResponse();
            } else if(json.noerror && json.noerror.okay == 'true'){
                console.log('starting to get intent data')
                const url = new URL(json.noerror.okay.path);
                promise = new Promise((resolve, reject) => {
                    console.log('start promise')
                   return httpsGetIntent(handlerInput, url).then((resultData) => {
                        console.log(resultData)
                        responseData = resultData;
                        resolve(responseData)
                        console.log('inside promise, no error, prior to return data')
                    })

            }).then((result) => { console.log('result', result)})
                return handlerInput.responseBuilder.speak('Test').getResponse();
            }

        });
        console.log('response data', responseData)

        let result = await promise;
        return result;

    },
};
</code>```

Out of my many console.logs() added for debugging, they print as follows:
- 'response data'
- 'waited!'
- 'starting to get intent data'
- 'start promise'
- resultData
- 'inside promise, no error, prior to return data'

答: Your best friend is async/await. Please use something like this or like this to access APIs.</p>

Body:
I'm new to promises, async/await, and Alexa/lambda so bear with me.

My function is returning prior to the data being returned. I had a similar issue where I was getting an error, but have since edited my function quite a bit and therefore asking a new question. I'm now no longer getting an error, but instead my data is being returned first, then the promise is executing.

I've tried re-writing the promise/function after reading many, many SO, google, and amazon developer forums. Nothing seems to be working for me.

const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    async handle(handlerInput) {
        const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
        let responseData, promise;

         checkAuthenticationStatus(handlerInput,function(json){
            console.log('waited!')
            if(json.error) {
                return handlerInput.responseBuilder.speak(messages.NO_ACCESS).withSimpleCard('Unauthorized Request', messages.NO_ACCESS).getResponse();
            } else if(json.noerror && json.noerror.okay == 'true'){
                console.log('starting to get intent data')
                const url = new URL(json.noerror.okay.path);
                promise = new Promise((resolve, reject) => {
                    console.log('start promise')
                   return httpsGetIntent(handlerInput, url).then((resultData) => {
                        console.log(resultData)
                        responseData = resultData;
                        resolve(responseData)
                        console.log('inside promise, no error, prior to return data')
                    })

            }).then((result) => { console.log('result', result)})
                return handlerInput.responseBuilder.speak('Test').getResponse();
            }

        });
        console.log('response data', responseData)

        let result = await promise;
        return result;

    },
};

Out of my many console.logs() added for debugging, they print as follows:
- 'response data'
- 'waited!'
- 'starting to get intent data'
- 'start promise'
- resultData
- 'inside promise, no error, prior to return data'


问:
How can I hide a UITabbarIcon?
I'm currently developing an iOS-App which will have 5 tabbar-icons. One of these should only be visible if you are allowed to see it.
How can I hide this icon?</p>

答:
With the following code, you can remove the specified tab from tab bar:</p>

```<code>let tabIndex = 3
if let tabBarController = self.tabBarController {
    if tabIndex < tabBarController.viewControllers?.count {
        var allViewControllers = tabBarController.viewControllers
        allViewControllers?.remove(at: tabIndex)
        tabBarController.viewControllers = allViewControllers
    }
}
</code>```

Title: How can I hide a UITabbarIcon?

Body:
With the following code, you can remove the specified tab from tab bar:

let tabIndex = 3
if let tabBarController = self.tabBarController {
    if tabIndex < tabBarController.viewControllers?.count {
        var allViewControllers = tabBarController.viewControllers
        allViewControllers?.remove(at: tabIndex)
        tabBarController.viewControllers = allViewControllers
    }
}


问:
How to pass xml file inside of code instead of a folder path?
I'am trying to not create a file, and pass xml document straight to a SkiaSharp method Load. I mean, is there the way to imitate a path? So here is the code:

```<code>public IActionResult svgToPng(string itemId, string mode = "
{
    var svgSrc = new XmlDocument();
    svgSrc.LoadXml(/*Some xml code*/);

    string svgSaveAs = "save file path";
    var quality = 100;

    var svg = new SkiaSharp.Extended.Svg.SKSvg();
    var pict = svg.Load(svgSrc); // HERE, it needs to be a path, not XmlDocument, but i want to pass straight

    var dimen = new SkiaSharp.SKSizeI
    (
        (int) Math.Ceiling(pict.CullRect.Width),
        (int) Math.Ceiling(pict.CullRect.Height)
    );

    var matrix = SKMatrix.MakeScale(1, 1);
    var img = SKImage.FromPicture(pict, dimen, matrix);

    // Convert to PNG
    var skdata = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality);
    using(var stream = System.IO.File.OpenWrite(svgSaveAs))
    {
        skdata.SaveTo(stream);
    }

    ViewData["Content"] = "PNG file was created out of SVG.";

    return View();
}
</code>```

The Load method seems to be this:

```<code>public SKPicture Load(
    using (var stream = File.OpenRead(filename))
    {
        return Load(stream);
    }
}
</code>```

答:
look at the code of that library :

https://github.com/mono/SkiaSharp.Extended/blob/master/SkiaSharp.Extended.Svg/source/SkiaSharp.Extended.Svg.Shared/SKSvg.cs

Look at the Load method, it has multiple implementations :

```<code>public SKPicture Load(string filename)
{
    using (var stream = File.OpenRead(filename))
    {
        return Load(stream);
    }
}

public SKPicture Load(Stream stream)
{
    using (var reader = XmlReader.Create(stream, xmlReaderSettings, CreateSvgXmlContext()))
    {
        return Load(reader);
    }
}

public SKPicture Load(XmlReader reader)
{
    return Load(XDocument.Load(reader));
}
</code>```

You will need to pick one of them and use it. Now, nothing stops you from getting the code and adding one extra Load for an XML string for example, but since this is a library you do not control, I'd stick to what you are given.

You could use the XmlReader version, that's probably the closest one to what you want.

Body:
I'am trying to not create a file, and pass xml document straight to a SkiaSharp method Load. I mean, is there the way to imitate a path? So here is the code:

public IActionResult svgToPng(string itemId, string mode = "
{
    var svgSrc = new XmlDocument();
    svgSrc.LoadXml(/*Some xml code*/);

    string svgSaveAs = "save file path";
    var quality = 100;

    var svg = new SkiaSharp.Extended.Svg.SKSvg();
    var pict = svg.Load(svgSrc); // HERE, it needs to be a path, not XmlDocument, but i want to pass straight

    var dimen = new SkiaSharp.SKSizeI
    (
        (int) Math.Ceiling(pict.CullRect.Width),
        (int) Math.Ceiling(pict.CullRect.Height)
    );

    var matrix = SKMatrix.MakeScale(1, 1);
    var img = SKImage.FromPicture(pict, dimen, matrix);

    // Convert to PNG
    var skdata = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality);
    using(var stream = System.IO.File.OpenWrite(svgSaveAs))
    {
        skdata.SaveTo(stream);
    }

    ViewData["Content"] = "PNG file was created out of SVG.";

    return View();
}

The Load method seems to be this:

public SKPicture Load(
    using (var stream = File.OpenRead(filename))
    {
        return Load(stream);
    }
}

Body:
look at the code of that library :

https://github.com/mono/SkiaSharp.Extended/blob/master/SkiaSharp.Extended.Svg/source/SkiaSharp.Extended.Svg.Shared/SKSvg.cs

Look at the Load method, it has multiple implementations :

public SKPicture Load(string filename)
{
    using (var stream = File.OpenRead(filename))
    {
        return Load(stream);
    }
}

public SKPicture Load(Stream stream)
{
    using (var reader = XmlReader.Create(stream, xmlReaderSettings, CreateSvgXmlContext()))
    {
        return Load(reader);
    }
}

public SKPicture Load(XmlReader reader)
{
    return Load(XDocument.Load(reader));
}

You will need to pick one of them and use it. Now, nothing stops you from getting the code and adding one extra Load for an XML string for example, but since this is a library you do not control, I'd stick to what you are given.

You could use the XmlReader version, that's probably the closest one to what you want.


问:
If statement variable assignment in batch file ignored
I am new to batch file coding and am trying to write a simple If-Else statement.

I have tried to use delayedexpansion as suggested in other questions but still don't seem to get the right value

```<code>@echo off
setlocal ENABLEDELAYEDEXPANSION

SET VAR=portrait
IF %VAR% == portrait do (
    SET /a height=1920;
    set /a width=1080;
) else do(
    set /a height=1080;
    set /a width=1920;
)

echo %height%
</code>```

The code above gives the output as 1080, while I am expecting 1920 based on the logic I wrote. Can someone please help me understand?

答:
You issue is mainly because there's no such thing as an If / Do or Else / Do statement. Also you should try to remember that Set /A is really for arithmetic, and you're not doing math, just setting values to names.

If "%VAR%" == "portrait" (
    Set "height=1920"
    Set "width=1080"
) Else (
    Set "height=1080"
    Set "width=1920"
)
Echo %height%
```

<p>However, you can in this case, still use <code>Set /A</code> to shorten your commands a little; because <code>Set /A</code> allows for multiple names to integer values within the same statement.</p>

<pre class="lang-bat prettyprint-override"><code>If "%VAR%" == "portrait" (
   Set /A height=1920, width=1080
) Else (
   Set /A height=1080, width=1920
)
Echo %height%
</code>```

Body:
I am new to batch file coding and am trying to write a simple If-Else statement.

I have tried to use delayedexpansion as suggested in other questions but still don't seem to get the right value

@echo off
setlocal ENABLEDELAYEDEXPANSION

SET VAR=portrait
IF %VAR% == portrait do (
    SET /a height=1920;
    set /a width=1080;
) else do(
    set /a height=1080;
    set /a width=1920;
)

echo %height%

The code above gives the output as 1080, while I am expecting 1920 based on the logic I wrote. Can someone please help me understand?

Body:
You issue is mainly because there's no such thing as an If / Do or Else / Do statement. Also you should try to remember that Set /A is really for arithmetic, and you're not doing math, just setting values to names.

If "%VAR%" == "portrait" (
    Set "height=1920"
    Set "width=1080"
) Else (
    Set "height=1080"
    Set "width=1920"
)
Echo %height%

However, you can in this case, still use Set /A to shorten your commands a little; because Set /A allows for multiple names to integer values within the same statement.

If "%VAR%" == "portrait" (
   Set /A height=1920, width=1080
) Else (
   Set /A height=1080, width=1920
)
Echo %height%