问:
Laravel Form Request Array Validation Custom Rules
I want to create a Form Request validation and don't know how-to.

I have a form:

```<code><form>
  <input type="text" name="fullname[0]">
  <input type="text" name="document_num[0]">

  <input type="text" name="fullname[1]">
  <input type="text" name="document_num[1]">

  <input type="text" name="fullname[2]">
  <input type="text" name="document_num[2]">

   .....

  <input type="text" name="fullname[n]">
  <input type="text" name="document_num[n]">

  <input type="submit">
</form>
</code>```

table 'users':

```<code>  id | fullname | document_num
  1  | John     | 111
  2  | Jane     | 112
 ..  | ...      | ...
</code>```

when user clicks submit a request is sent to controller method where it’s first being validated by Form Request (or it can be a regular Validator).
So I want to write a rule which checks:

```<code>for (i=0; i<numberOfUsersToAdd; i++)

    if  (‘document_num[$i]’ exists in ‘users’ in field ‘document_num’ ) {

       $user = Users::find(id of user in DB having this ‘document_num[$i]’) ;

       check if (fullname[$i] == $user->fullname) {

                return true} // input-ed users name match his/her name in DB.

        else {return false}  // input-ed users name doesn't match his/her name in DB.

        }

    else return true; // document_num[$i] doesn't exists in the database which's ok
</code>```

if in words: check if any input-ed document_num[$i] exists in the table users, if yes, get the user having this document_nubmer from DB and compare his/her fullname value to fullname[$i] from input.

How to do it?:)

Appreciate any help!:)

答:
Ok. Logic of this validation in YourFormRequest is next:

Let mark all fields as required and document_num field additionaly as integer. You can add other additional constraints - it dont matter.

In rules method of YourFormRequest check in loop "is user exists for given document_num?".

If it not exists then ok - validation of this field is success.

If it exists then check "is user fullname equals for given fullname. If equals then ok - validation of this field is success. Otherwise if it fails then attach to this field your custom rule that always fails.

Let see this approach on a working example.

YourFormRequest.php

```<code>public function rules()
{
    $rules = [
        'fullname.*' => 'required',
        'document_num.*' => 'required|integer',
    ];

    $documentNums = request()->get('document_num');
    $fullnames = request()->get('fullname');

    for ($i = 0; $i < count($documentNums); $i++) {
        $user = User::where('document_num', $documentNums[$i])->first();
        if ($user && ($user->fullname != $fullnames[$i]) {
            $rules['document_num.' . $i] = "document_num_fail:$i"; //some rule that always fails. As argument we pass a row number of field that fails
        }
    }
    return $rules;
}
</code>```

CustomValidator.php (place it for example in App\Services folder)

```<code>namespace App\Services;

class CustomValidator {

    public function documentNumFailValidate($attribute, $value, $parameters, $validator) {
        return false;
    }

    public function documentNumFailReplacer($message, $attribute, $rule, $parameters) {
        return str_replace([':index'], $parameters[0], $message);
    }
}
</code>```

Here you can see two functions. First - to validate rule (we always pass false cause we need it). Second - it just a replacer for error message. You want to know on what field line was this error (for example on third line and fields: fullname[2] and document_num[2] respectively). As i wrote above in comment for attaching fail rule we give the number of row that fails to the validation method (documentNumFailReplacer method will replace placeholder :index in error message with the given value)

Next step - register this methods in AppServiceProvider.php

```<code>public function boot()
{
    Validator::extend('document_num_fail',  'App\Services\CustomValidator@documentNumFailValidate');
    Validator::replacer('document_num_fail', 'App\Services\CustomValidator@documentNumFailReplacer');
}
</code>```

And final step - define your custom messages in validation.php

```<code>'custom' => [
        'document_num.*' => [
            'document_num_fail' => 'Input-ed user name doesn`t match his/her name in DB for specified :attribute (field position/number: :index)',
        ]
    ],

'attributes' => [
    'document_num.*' => 'document number',
],
</code>```

Body:
I want to create a Form Request validation and don't know how-to.

I have a form:

<form>
  <input type="text" name="fullname[0]">
  <input type="text" name="document_num[0]">

  <input type="text" name="fullname[1]">
  <input type="text" name="document_num[1]">

  <input type="text" name="fullname[2]">
  <input type="text" name="document_num[2]">

   .....

  <input type="text" name="fullname[n]">
  <input type="text" name="document_num[n]">

  <input type="submit">
</form>

table 'users':

  id | fullname | document_num
  1  | John     | 111
  2  | Jane     | 112
 ..  | ...      | ...

when user clicks submit a request is sent to controller method where it’s first being validated by Form Request (or it can be a regular Validator).
So I want to write a rule which checks:

for (i=0; i<numberOfUsersToAdd; i++)

    if  (‘document_num[$i]’ exists in ‘users’ in field ‘document_num’ ) {

       $user = Users::find(id of user in DB having this ‘document_num[$i]’) ;

       check if (fullname[$i] == $user->fullname) {

                return true} // input-ed users name match his/her name in DB.

        else {return false}  // input-ed users name doesn't match his/her name in DB.

        }

    else return true; // document_num[$i] doesn't exists in the database which's ok

if in words: check if any input-ed document_num[$i] exists in the table users, if yes, get the user having this document_nubmer from DB and compare his/her fullname value to fullname[$i] from input.

How to do it?:)

Appreciate any help!:)

Body:
Ok. Logic of this validation in YourFormRequest is next:

Let mark all fields as required and document_num field additionaly as integer. You can add other additional constraints - it dont matter.

In rules method of YourFormRequest check in loop "is user exists for given document_num?".

If it not exists then ok - validation of this field is success.

If it exists then check "is user fullname equals for given fullname. If equals then ok - validation of this field is success. Otherwise if it fails then attach to this field your custom rule that always fails.

Let see this approach on a working example.

YourFormRequest.php

public function rules()
{
    $rules = [
        'fullname.*' => 'required',
        'document_num.*' => 'required|integer',
    ];

    $documentNums = request()->get('document_num');
    $fullnames = request()->get('fullname');

    for ($i = 0; $i < count($documentNums); $i++) {
        $user = User::where('document_num', $documentNums[$i])->first();
        if ($user && ($user->fullname != $fullnames[$i]) {
            $rules['document_num.' . $i] = "document_num_fail:$i"; //some rule that always fails. As argument we pass a row number of field that fails
        }
    }
    return $rules;
}

CustomValidator.php (place it for example in App\Services folder)

namespace App\Services;

class CustomValidator {

    public function documentNumFailValidate($attribute, $value, $parameters, $validator) {
        return false;
    }

    public function documentNumFailReplacer($message, $attribute, $rule, $parameters) {
        return str_replace([':index'], $parameters[0], $message);
    }
}

Here you can see two functions. First - to validate rule (we always pass false cause we need it). Second - it just a replacer for error message. You want to know on what field line was this error (for example on third line and fields: fullname[2] and document_num[2] respectively). As i wrote above in comment for attaching fail rule we give the number of row that fails to the validation method (documentNumFailReplacer method will replace placeholder :index in error message with the given value)

Next step - register this methods in AppServiceProvider.php

public function boot()
{
    Validator::extend('document_num_fail',  'App\Services\CustomValidator@documentNumFailValidate');
    Validator::replacer('document_num_fail', 'App\Services\CustomValidator@documentNumFailReplacer');
}

And final step - define your custom messages in validation.php

'custom' => [
        'document_num.*' => [
            'document_num_fail' => 'Input-ed user name doesn`t match his/her name in DB for specified :attribute (field position/number: :index)',
        ]
    ],

'attributes' => [
    'document_num.*' => 'document number',
],


来源: stackexchange

问:
How to block hardware Back button and re-login again
I have implemented below navigation for my app which has login and logout feature.
How to block hardware Back button and re-login again. Below is the flow:

1) Login page is the MainPage when App launch

MainPage = new Login();

2)  After successfully login, user will be navigated to MainMenu Page

NavigationPage NP = new NavigationPage(new MainMenu());

 App.current.MainPage = Np;

In MainMenu:

1) How to I override the Hardware button for iOS and Android (but iOS has no Back Button in current ipad and iphone).

```<code>This is what I got so far to stop back button.

protected override bool OnBackButtonPressed()
{
     base.OnBackButtonPressed();

     return false

}
</code>```

1a) How to detect if device is iOS and Android phone? Since iOS has no back Button, will onBackButtonPressed() apply to it?

1b)  will putting return false before or after base.OnBackButtonPressed(), make a difference?

2) User logout

in the beginning: Login -> MainMenu:   in MainMenu page, user click Logout button

```<code> void LogoutButton()
 {
   Navigate.PopModalAsync(new Login());
 }
</code>```

will this cause any problem since the first time login, MainPage is App.current.MainPage = Np;

Now what is the Mainpage = ??  when user click Logout button?

What happen when user login again? Which Navigation method I should use to go back to Login Page?

Thanks

答:
Let me start by saying that asking multiple questions at once isn't really according to the StackOverflow guidelines. To answer your questions:

1) How to I override the Hardware button for iOS and Android (but iOS
  has no Back Button in current ipad and iphone).

The method you're overriding does indeed stop the hardware back button. It does not however stop every method a user has to go back. What you could do instead is create a separate Activity for your login and decorate that with the following:

```<code>[Activity(Label = "MyApp",
          Icon = "@drawable/ic_launcher",
          MainLauncher = true,
          NoHistory = true,
          ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
          ScreenOrientation = ScreenOrientation.Portrait)]
public class LoginActivity : FormsAppCompatActivity { }
</code>```

The NoHistory = true part is the interesting one. This means it won't be included in the Android navigation stack so you can't go back to it using the back buttons.

1a) How to detect if device is iOS and Android phone? Since iOS has no
  back Button, will onBackButtonPressed() apply to it?

No. OnBackButtonPressed does nothing on iOS. It will not be called.

2) User logout in the beginning: Login -> MainMenu: in MainMenu page,
  user click Logout button will this cause any problem since the first
  time login, Now what is the Mainpage?? when user click Logout button?
  What happen when user login again? Which Navigation method I should
  use to go back to Login Page?

You can swap out the MainPage as needed. This will also help you when it comes to the back button. On app startup you can check if the user is logged in already. If he is, you set the Current.MainPage to your main menu page. If not you set it to the login page. When the user has successfully logged in you set the Current.MainPage to the main menu page. Since you set the main page, you get a completely new navigation stack, so the back button will not make the app go back to the login page.

ContentLicense: CC BY-SA 3.0

Body:
I have implemented below navigation for my app which has login and logout feature.
How to block hardware Back button and re-login again. Below is the flow:

1) Login page is the MainPage when App launch

MainPage = new Login();

2)  After successfully login, user will be navigated to MainMenu Page

NavigationPage NP = new NavigationPage(new MainMenu());

 App.current.MainPage = Np;

In MainMenu:

1) How to I override the Hardware button for iOS and Android (but iOS has no Back Button in current ipad and iphone).

This is what I got so far to stop back button.

protected override bool OnBackButtonPressed()
{
     base.OnBackButtonPressed();

     return false

}

1a) How to detect if device is iOS and Android phone? Since iOS has no back Button, will onBackButtonPressed() apply to it?

1b)  will putting return false before or after base.OnBackButtonPressed(), make a difference?

2) User logout

in the beginning: Login -> MainMenu:   in MainMenu page, user click Logout button

 void LogoutButton()
 {
   Navigate.PopModalAsync(new Login());
 }

will this cause any problem since the first time login, MainPage is App.current.MainPage = Np;

Now what is the Mainpage = ??  when user click Logout button?

What happen when user login again? Which Navigation method I should use to go back to Login Page?

Thanks

Body:
Let me start by saying that asking multiple questions at once isn't really according to the StackOverflow guidelines. To answer your questions:

1) How to I override the Hardware button for iOS and Android (but iOS
  has no Back Button in current ipad and iphone).

The method you're overriding does indeed stop the hardware back button. It does not however stop every method a user has to go back. What you could do instead is create a separate Activity for your login and decorate that with the following:

[Activity(Label = "MyApp",
          Icon = "@drawable/ic_launcher",
          MainLauncher = true,
          NoHistory = true,
          ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
          ScreenOrientation = ScreenOrientation.Portrait)]
public class LoginActivity : FormsAppCompatActivity { }

The NoHistory = true part is the interesting one. This means it won't be included in the Android navigation stack so you can't go back to it using the back buttons.

1a) How to detect if device is iOS and Android phone? Since iOS has no
  back Button, will onBackButtonPressed() apply to it?

No. OnBackButtonPressed does nothing on iOS. It will not be called.

2) User logout in the beginning: Login -> MainMenu: in MainMenu page,
  user click Logout button will this cause any problem since the first
  time login, Now what is the Mainpage?? when user click Logout button?
  What happen when user login again? Which Navigation method I should
  use to go back to Login Page?

You can swap out the MainPage as needed. This will also help you when it comes to the back button. On app startup you can check if the user is logged in already. If he is, you set the Current.MainPage to your main menu page. If not you set it to the login page. When the user has successfully logged in you set the Current.MainPage to the main menu page. Since you set the main page, you get a completely new navigation stack, so the back button will not make the app go back to the login page.


问:
Ruby/RoR - Count occurrence of an element in an array
I'v a hash

{1=>true, 7=>false, 6=>true, 4=>false}

or an array like

[1, true], [7, false], [6, true], [4, false]]

or

[true, false, true, false].

How can I find the number of trues in the array?

答:
In order to count the elements, you obviously have to iterate over the collection. Since iterating over a Hash yields two-element Arrays, the first two are actually exactly the same:

```<code>{ 1 => true, 7 => false, 6 => true, 4 => false }.count(&:last)
[[1, true], [7, false], [6, true], [4, false]].count(&:last)
</code>```

For the simple Array case, you could do something like this:

```<code>[true, false, true, false].count(true)
</code>```

This Array is of course also the same as the Hash#values from your Hash above, so you could use the same method on that:

```<code>{ 1 => true, 7 => false, 6 => true, 4 => false }.values.count(true)
</code>```

If you don't know which one of three you will get, you could use something like this:

```<code>{ 1 => true, 7 => false, 6 => true, 4 => false }.flatten.count(true)
[[1, true], [7, false], [6, true], [4, false]].flatten.count(true)
[true, false, true, false].flatten.count(true)
</code>```

Body:
In order to count the elements, you obviously have to iterate over the collection. Since iterating over a Hash yields two-element Arrays, the first two are actually exactly the same:

{ 1 => true, 7 => false, 6 => true, 4 => false }.count(&:last)
[[1, true], [7, false], [6, true], [4, false]].count(&:last)

For the simple Array case, you could do something like this:

[true, false, true, false].count(true)

This Array is of course also the same as the Hash#values from your Hash above, so you could use the same method on that:

{ 1 => true, 7 => false, 6 => true, 4 => false }.values.count(true)

If you don't know which one of three you will get, you could use something like this:

{ 1 => true, 7 => false, 6 => true, 4 => false }.flatten.count(true)
[[1, true], [7, false], [6, true], [4, false]].flatten.count(true)
[true, false, true, false].flatten.count(true)

ContentLicense: CC BY-SA 2.5


问:
How to get Youtube Live Stream by Channel Id in Youtube API V3 in android?
I am able to get the list of live stream: https://developers.google.com/youtube/v3/live/docs/liveStreams/list#examples
But how to get the live stream status and live stream link or id for particular channel using youtube v3 api in android?</p>

答:
This will return live stream ID

```<code>https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&eventType=live&type=video&key={YOUR_API_KEY}
</code>```

You can also pass Query to YouTube so YouTube give you all live stream events

```<code>https://www.googleapis.com/youtube/v3/search?part=snippet&q={YOUR_SEARCH_QuERY}&eventType=live&type=video&key={YOUR_YOUTUBE_API}
</code>```

This how i get live stream videos in my app

```<code>    private void initVolley(String[] urls) {

        for (String url : urls) {

            if (url.startsWith("https://www.googleapis.com/youtube/v3/")) {
                jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("items");
                            if (jsonArray.length() > 0) {
                                for (int getItem = 0; getItem < jsonArray.length(); getItem++) {

                                    JSONObject jsonObject = jsonArray.getJSONObject(getItem).getJSONObject("id");
                                    String videoID = jsonObject.getString("videoId");

                                    Log.d(TAG, "void id " + videoID);

                                    mUrlList.add(new video(jsonArray.getJSONObject(getItem).getJSONObject("snippet").getString("title"), jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"), " ", "https://www.youtube.com/watch?v=" + videoID, true));

                                    if (mAdapter != null)
                                        mAdapter.notifyDataSetChanged();
                                    Log.d(TAG, videoID + jsonArray.length() + jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url"));

                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(jsonObjectRequest);
            }
        }
}
</code>```

And if you have YouTube links maybe you store  your in database then this will return you some usefull info with out API key

```<code>https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=lUOhCtXPN40&format=json
</code>```

and below code for this

```<code>     JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL, null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // mVideo = new video(response.getString("title"), response.getString("thumbnail_url"), response.getString("author_name"));
                                //  mVideoDataSet.add(mVideo);

                                mVideo = new video(url);
                                mVideo.setVideoTitle(response.getString("title"));
                                mVideo.setVideoThimailUrl(response.getString("thumbnail_url"));
                                mVideo.setVideoChannalName(response.getString("author_name"));
                                mVideo.setLiveNow(false);
                                mVideoDataSet.add( mVideo);
                                Log.d(TAG, "inside the volly" + mVideo.getVideoTitle());
                               // Log.d(TAG, mVideoDataSet.get(i).getVideoStreemUrl());

                                if (mAdapter != null) {
                                    mAdapter.notifyDataSetChanged();
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);

                                } else {
                                    Log.d(TAG, "setingAdupter");
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);
                                   mAdapter = new CustomAdapter(mVideoDataSet);
                                    mRecyclerView.setAdapter(mAdapter);

                                }
                                i++;
                                if (i != mUrlList.size())
                                    initVolly();

                            } catch (JSONException e) {

                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           // if(error)
                          i++;
                            initVolly();
                            Log.e("Volley", "Error");
                        }
                    }
            );
            // Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
</code>```

and last if you want to see source code here is link

Body:
This will return live stream ID

https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&eventType=live&type=video&key={YOUR_API_KEY}

You can also pass Query to YouTube so YouTube give you all live stream events

https://www.googleapis.com/youtube/v3/search?part=snippet&q={YOUR_SEARCH_QuERY}&eventType=live&type=video&key={YOUR_YOUTUBE_API}

This how i get live stream videos in my app

    private void initVolley(String[] urls) {

        for (String url : urls) {

            if (url.startsWith("https://www.googleapis.com/youtube/v3/")) {
                jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("items");
                            if (jsonArray.length() > 0) {
                                for (int getItem = 0; getItem < jsonArray.length(); getItem++) {

                                    JSONObject jsonObject = jsonArray.getJSONObject(getItem).getJSONObject("id");
                                    String videoID = jsonObject.getString("videoId");

                                    Log.d(TAG, "void id " + videoID);

                                    mUrlList.add(new video(jsonArray.getJSONObject(getItem).getJSONObject("snippet").getString("title"), jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"), " ", "https://www.youtube.com/watch?v=" + videoID, true));

                                    if (mAdapter != null)
                                        mAdapter.notifyDataSetChanged();
                                    Log.d(TAG, videoID + jsonArray.length() + jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url"));

                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(jsonObjectRequest);
            }
        }
}

And if you have YouTube links maybe you store  your in database then this will return you some usefull info with out API key

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=lUOhCtXPN40&format=json

and below code for this

     JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL, null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // mVideo = new video(response.getString("title"), response.getString("thumbnail_url"), response.getString("author_name"));
                                //  mVideoDataSet.add(mVideo);

                                mVideo = new video(url);
                                mVideo.setVideoTitle(response.getString("title"));
                                mVideo.setVideoThimailUrl(response.getString("thumbnail_url"));
                                mVideo.setVideoChannalName(response.getString("author_name"));
                                mVideo.setLiveNow(false);
                                mVideoDataSet.add( mVideo);
                                Log.d(TAG, "inside the volly" + mVideo.getVideoTitle());
                               // Log.d(TAG, mVideoDataSet.get(i).getVideoStreemUrl());

                                if (mAdapter != null) {
                                    mAdapter.notifyDataSetChanged();
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);

                                } else {
                                    Log.d(TAG, "setingAdupter");
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);
                                   mAdapter = new CustomAdapter(mVideoDataSet);
                                    mRecyclerView.setAdapter(mAdapter);

                                }
                                i++;
                                if (i != mUrlList.size())
                                    initVolly();

                            } catch (JSONException e) {

                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           // if(error)
                          i++;
                            initVolly();
                            Log.e("Volley", "Error");
                        }
                    }
            );
            // Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);

and last if you want to see source code here is link


问:
Google analytics API v4 max results
Can someone please help me for Google analytic API V4:
how to pass: max-result parameter with this class:
Google_Service_AnalyticsReporting
I am unable to find relevant function to assign max-result parameter value.</p>

答: You can use parameter page_size: 10000. Hope this helps.

Title: Google analytics API v4 max results


问:
Menu action items goes to overflow menu
You will have to forgive me, because I am still pretty new to android development. For my android app, I am staying to create a custom menu and place on the tool bar with the java code in a base activity that is extended by the other activities. But for some reason, the menu buttons are hiding in the overflow menu even though there is more than enough room for them to be showing. I feel like my code is correct, but I need to add a reference to something somewhere else that I am missing. Thanks in advance!

Current toolbar appearance

BaseActivity.java

```<code>public abstract class BaseActivity extends AppCompatActivity {

    private Toolbar toolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResource());

        toolBar = (Toolbar) this.findViewById(R.id.toolbar);

        if (toolBar != null) {
            setSupportActionBar(toolBar);
            if (getSupportActionBar() != null) {
                setDisplayHomeEnabled(true);
            }
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    protected abstract int getLayoutResource();

    public void setDisplayHomeEnabled(boolean b) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(b);
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        toolBar.setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        toolBar.setTitle(titleId);
    }

    public Toolbar getToolBar() {
        return toolBar;
    }
}
</code>```

toolbar.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:titleTextColor="@android:color/white"
        android:background="?attr/colorPrimary">
    </android.support.v7.widget.Toolbar>

</LinearLayout>
</code>```

main_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@android:drawable/ic_menu_preferences"
        android:showAsAction="always"/>

    <item
        android:id="@+id/menu_search"
        android:title="Search"
        android:showAsAction="always"
        android:icon="@android:drawable/ic_menu_search"
        android:actionViewClass="android.widget.SearchView"/>

</menu>
</code>```

答:
In your main_menu.xml file, add an 'app' tag for showAsAction as I have done below. It worked for me. See if that works for you too.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@android:drawable/ic_menu_preferences"
        app:showAsAction="always"/>

    <item
        android:id="@+id/menu_search"
        android:title="Search"
        app:showAsAction="always"
        android:icon="@android:drawable/ic_menu_search"
        android:actionViewClass="android.widget.SearchView"/>
</menu>
</code>```

Title: Menu action items goes to overflow menu

Body:
You will have to forgive me, because I am still pretty new to android development. For my android app, I am staying to create a custom menu and place on the tool bar with the java code in a base activity that is extended by the other activities. But for some reason, the menu buttons are hiding in the overflow menu even though there is more than enough room for them to be showing. I feel like my code is correct, but I need to add a reference to something somewhere else that I am missing. Thanks in advance!

Current toolbar appearance

BaseActivity.java

public abstract class BaseActivity extends AppCompatActivity {

    private Toolbar toolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResource());

        toolBar = (Toolbar) this.findViewById(R.id.toolbar);

        if (toolBar != null) {
            setSupportActionBar(toolBar);
            if (getSupportActionBar() != null) {
                setDisplayHomeEnabled(true);
            }
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    protected abstract int getLayoutResource();

    public void setDisplayHomeEnabled(boolean b) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(b);
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        toolBar.setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        toolBar.setTitle(titleId);
    }

    public Toolbar getToolBar() {
        return toolBar;
    }
}

toolbar.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:titleTextColor="@android:color/white"
        android:background="?attr/colorPrimary">
    </android.support.v7.widget.Toolbar>

</LinearLayout>

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@android:drawable/ic_menu_preferences"
        android:showAsAction="always"/>

    <item
        android:id="@+id/menu_search"
        android:title="Search"
        android:showAsAction="always"
        android:icon="@android:drawable/ic_menu_search"
        android:actionViewClass="android.widget.SearchView"/>

</menu>

Body:
In your main_menu.xml file, add an 'app' tag for showAsAction as I have done below. It worked for me. See if that works for you too.

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@android:drawable/ic_menu_preferences"
        app:showAsAction="always"/>

    <item
        android:id="@+id/menu_search"
        android:title="Search"
        app:showAsAction="always"
        android:icon="@android:drawable/ic_menu_search"
        android:actionViewClass="android.widget.SearchView"/>
</menu>


问:
"bower install" exited with code 9009. in ASP.NET core application
I am facing an issue of

The command "bower install" exited with code 9009

while publishing the ASP.NET core-MVC application with entity framework. I am using VS-2017.

I got many suggestions in your portal of downloading node.js globally, but as I am very new to this system I don't know how to do so. Or
if there is any other solution for that please let me know.

答:
Make sure to install Node.js.

Install bower globally by executing the following command in cmd:

npm install -g bower

Close Visual Studio, then open it and try again.


问:
How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message
I know this question has been asked a couple of times already but most of the time, the solution is to handle this in the parent, as the flow of responsibility is only descending. However, sometimes, you need to kill a component from one of its methods.
I know I can't modify its props, and If I start adding booleans as the state, it's gonna start to be really messy for a simple component. Here is what I'm trying to achieve :
A small error box component, with an "x" to dismiss it. Receiving an error through its props will display it but I'd like a way to close it from its own code.

```<code>class ErrorBoxComponent extends React.Component {

  dismiss() {
    // What should I put here?
  }

  render() {
    if (!this.props.error) {
      return null;
    }

    return (
      <div data-alert className="alert-box error-box">
        {this.props.error}
        <a href="#" className="close" onClick={this.dismiss.bind(this)}>×</a>
      </div>
    );
  }
}

export default ErrorBoxComponent;
</code>```

And I would use it like this in the parent component :

```<code><ErrorBox error={this.state.error}/>
</code>```

In the section  What should I put here ?, I already tried :

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
Which throws a nice error in the console :

Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.

Should I copy the incoming props in the ErrorBox state, and manipulate it only internally?

答:
instead of using

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);

try using

```<code>ReactDOM.unmountComponentAtNode(document.getElementById('root'));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know this question has been asked a couple of times already but most of the time, the solution is to handle this in the parent, as the flow of responsibility is only descending. However, sometimes, you need to kill a component from one of its methods.
I know I can't modify its props, and If I start adding booleans as the state, it's gonna start to be really messy for a simple component. Here is what I'm trying to achieve :
A small error box component, with an "x" to dismiss it. Receiving an error through its props will display it but I'd like a way to close it from its own code.

class ErrorBoxComponent extends React.Component {

  dismiss() {
    // What should I put here?
  }

  render() {
    if (!this.props.error) {
      return null;
    }

    return (

        {this.props.error}
        ×

    );
  }
}

export default ErrorBoxComponent;

And I would use it like this in the parent component :

<ErrorBox error={this.state.error}/>

In the section  What should I put here ?, I already tried :

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
Which throws a nice error in the console :

Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.

Should I copy the incoming props in the ErrorBox state, and manipulate it only internally?

Body:
instead of using

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);

try using

ReactDOM.unmountComponentAtNode(document.getElementById('root'));


问:
Sort list while in a loop using groupby
I have a loop with linq like this:

```<code>foreach (var group in part.Profiles.Skip(ixstart).
             GroupBy(b => new { b.Number, b.X }).
             OrderBy(g => g.Key.Number).ThenBy(g => g.Key.X))
{
     // .... code
}
</code>```

Is it safe to somewhere in the ... code sort the list
part.Profiles.Sort()?

I do not get exceptions.

答:
I suspect it turns out to be safe because GroupBy doesn't stream results - it consumes all of the input before it returns any values. (It's lazy in that it doesn't do any work until you ask it for its first element, but then it consumes all of the input.)

However, I would definitely not rely on that. It's going to ring alarm bells for many readers, and a seemingly-innocent change could mess everything up. I'd also say it's a confusing thing to do at all, sorting a collection within a loop that's iterating over that collection. Options:

Sort beforehand

Sort afterwards

Materialize the collection you're iterating over so it's independent of the original collection (e.g. by calling ToList() and using the result)

Title: Sort list while in a loop using groupby

Body:
I have a loop with linq like this:

foreach (var group in part.Profiles.Skip(ixstart).
             GroupBy(b => new { b.Number, b.X }).
             OrderBy(g => g.Key.Number).ThenBy(g => g.Key.X))
{
     // .... code
}

Is it safe to somewhere in the ... code sort the list
part.Profiles.Sort()?

I do not get exceptions.


问:
Ionic 3 - Scroll issue
I am doing an Ionic 3 app and on some pages there is no scroll, like this page :

History.html

```<code> <ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage">
    <ion-card-header>
         <span class="title">{{h.nom_commun}}</span>
         <span class="date">{{h.date_signalement}}</span>
         <button (click)="openPage()" class="edit">
             <ion-icon large name="create" color="mainColor" class="edit"></ion-icon>
         </button>
    </ion-card-header>
    <ion-card-content>

        <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon>
        <br />
        <div *ngIf="isGroupShown(i)">
            <div class="up">
                <ion-slides class="Pictures" slidesPerView="3">
                    <ion-slide>
                        <img src="{{h.image}}" />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol3.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol4.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="{{h.pictures}}"  />
                    </ion-slide>
                </ion-slides>

                <ion-list>
                        <p><strong>Nom codifié :</strong> {{h.nom_codifie}}</p>
                        <p><strong>Etat actuel :</strong> {{h.etat_actuel}}</p>
                        <p><strong>Date de réception :</strong> {{h.date_reception}}</p>
                        <p *ngIf="h.date_renvoi"><strong>Date de renvoi en liberté :</strong> {{h.date_renvoi}}</p>
                        <p><strong>Pays :</strong> {{h.pays}}</p>
                        <p><strong>Lieu de signalement :</strong> {{h.lieu_signalement}}</p>
                        <p><strong>Condition du signalement :</strong> {{h.condition_signalement}}</p>
                        <p><strong>Numéro d'immatriculation :</strong> {{h.immatriculation}}</p>
                </ion-list>

            </div>
        </div>

    </ion-card-content>
</ion-card>
</code>```

History.ts :

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EditBirdPage } from '../EditBird/EditBird';
import { BirdService } from '../../providers/bird-service';
import { jQuery } from 'jquery';

@Component({
  selector: 'page-History',
  templateUrl: 'History.html'
})

export class HistoryPage {

    History:any =[];

    constructor(public navCtrl: NavController, public serviceOne: BirdService) {
        this.serviceOne.getData().subscribe(
            data => this.History = data
        );
    }

    openPage() {
        this.navCtrl.push(EditBirdPage);
    }

    shownGroup = null;

    toggleGroup(group) {
        if (this.isGroupShown(group)) {
            this.shownGroup = null;
        } else {
            this.shownGroup = group;
        }
    };

    isGroupShown(group) {
        return this.shownGroup === group;
    };
}
</code>```

The scroll work only on page with basic text but with content which is generate or open manually ( like an accordion ) it's not working.

Thanks for your help !

答:
If you want your content to be scrolled, you need to wrap it inside ion-content like this,

```<code><ion-content>
--your scrolling content goes here--
</ion-content>
</code>```

in your case if you want History.html contents to be scrolled, then wrap it inside ion-content like this,

```<code><ion-content>
<ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage">
    <ion-card-header>
         <span class="title">{{h.nom_commun}}</span>
         <span class="date">{{h.date_signalement}}</span>
         <button (click)="openPage()" class="edit">
             <ion-icon large name="create" color="mainColor" class="edit"></ion-icon>
         </button>
    </ion-card-header>
    <ion-card-content>

        <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon>
        <br />
        <div *ngIf="isGroupShown(i)">
            <div class="up">
                <ion-slides class="Pictures" slidesPerView="3">
                    <ion-slide>
                        <img src="{{h.image}}" />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol3.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol4.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="{{h.pictures}}"  />
                    </ion-slide>
                </ion-slides>

                <ion-list>
                        <p><strong>Nom codifié :</strong> {{h.nom_codifie}}</p>
                        <p><strong>Etat actuel :</strong> {{h.etat_actuel}}</p>
                        <p><strong>Date de réception :</strong> {{h.date_reception}}</p>
                        <p *ngIf="h.date_renvoi"><strong>Date de renvoi en liberté :</strong> {{h.date_renvoi}}</p>
                        <p><strong>Pays :</strong> {{h.pays}}</p>
                        <p><strong>Lieu de signalement :</strong> {{h.lieu_signalement}}</p>
                        <p><strong>Condition du signalement :</strong> {{h.condition_signalement}}</p>
                        <p><strong>Numéro d'immatriculation :</strong> {{h.immatriculation}}</p>
                </ion-list>

            </div>
        </div>

    </ion-card-content>
</ion-card>
</ion-content>
</code>```

Title: Ionic 3 - Scroll issue

Body:
I am doing an Ionic 3 app and on some pages there is no scroll, like this page :

History.html

 <ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage">
    <ion-card-header>
         {{h.nom_commun}}
         {{h.date_signalement}}
         <button (click)="openPage()" class="edit">
             <ion-icon large name="create" color="mainColor" class="edit"></ion-icon>
         </button>
    </ion-card-header>
    <ion-card-content>

        <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon>

                <ion-slides class="Pictures" slidesPerView="3">
                    <ion-slide>

                    </ion-slide>
                    <ion-slide>

                    </ion-slide>
                    <ion-slide>

                    </ion-slide>
                    <ion-slide>

                    </ion-slide>
                </ion-slides>

                <ion-list>

Nom codifié : {{h.nom_codifie}}

Etat actuel : {{h.etat_actuel}}

Date de réception : {{h.date_reception}}

Date de renvoi en liberté : {{h.date_renvoi}}

Pays : {{h.pays}}

Lieu de signalement : {{h.lieu_signalement}}

Condition du signalement : {{h.condition_signalement}}

Numéro d'immatriculation : {{h.immatriculation}}

                </ion-list>

    </ion-card-content>
</ion-card>

History.ts :

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EditBirdPage } from '../EditBird/EditBird';
import { BirdService } from '../../providers/bird-service';
import { jQuery } from 'jquery';

@Component({
  selector: 'page-History',
  templateUrl: 'History.html'
})

export class HistoryPage {

    History:any =[];

    constructor(public navCtrl: NavController, public serviceOne: BirdService) {
        this.serviceOne.getData().subscribe(
            data => this.History = data
        );
    }

    openPage() {
        this.navCtrl.push(EditBirdPage);
    }

    shownGroup = null;

    toggleGroup(group) {
        if (this.isGroupShown(group)) {
            this.shownGroup = null;
        } else {
            this.shownGroup = group;
        }
    };

    isGroupShown(group) {
        return this.shownGroup === group;
    };
}

The scroll work only on page with basic text but with content which is generate or open manually ( like an accordion ) it's not working.

Thanks for your help !

Body:
If you want your content to be scrolled, you need to wrap it inside ion-content like this,

<ion-content>
--your scrolling content goes here--
</ion-content>

in your case if you want History.html contents to be scrolled, then wrap it inside ion-content like this,

<ion-content>
<ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage">
    <ion-card-header>
         <span class="title">{{h.nom_commun}}</span>
         <span class="date">{{h.date_signalement}}</span>
         <button (click)="openPage()" class="edit">
             <ion-icon large name="create" color="mainColor" class="edit"></ion-icon>
         </button>
    </ion-card-header>
    <ion-card-content>

        <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon>
        <br />
        <div *ngIf="isGroupShown(i)">
            <div class="up">
                <ion-slides class="Pictures" slidesPerView="3">
                    <ion-slide>
                        <img src="{{h.image}}" />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol3.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="../assets/img/rossignol4.jpg"  />
                    </ion-slide>
                    <ion-slide>
                        <img src="{{h.pictures}}"  />
                    </ion-slide>
                </ion-slides>

                <ion-list>
                        <p><strong>Nom codifié :</strong> {{h.nom_codifie}}</p>
                        <p><strong>Etat actuel :</strong> {{h.etat_actuel}}</p>
                        <p><strong>Date de réception :</strong> {{h.date_reception}}</p>
                        <p *ngIf="h.date_renvoi"><strong>Date de renvoi en liberté :</strong> {{h.date_renvoi}}</p>
                        <p><strong>Pays :</strong> {{h.pays}}</p>
                        <p><strong>Lieu de signalement :</strong> {{h.lieu_signalement}}</p>
                        <p><strong>Condition du signalement :</strong> {{h.condition_signalement}}</p>
                        <p><strong>Numéro d'immatriculation :</strong> {{h.immatriculation}}</p>
                </ion-list>

            </div>
        </div>

    </ion-card-content>
</ion-card>
</ion-content>


问:
failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2
I installed ALL Extra and SDK API 21-22 including changed

compileSdkVersion 22 to 21 and buildToolsVersion '22.0.1' to 21.1.2.

I'm having Rendering Problems for API 22.
I have tried changing the version to <= 21 but I'm still getting an error.

答: I solved the problem updating all packages from Android SDK Manager and also, I had to install Extras -> Android Support Repository.


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
Yiu can try this working code:

function fuelList(_this){
  var value=$(_this).attr("value");

  $("#TwoWheeler").hide();
  $("#FourWheeler").hide();

  if(value=="1"){
    $("#TwoWheeler").show();
  }
  else  if(value=="2"){
    $("#FourWheeler").show();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
                        <label>
                            <input type="radio" name="vehicleList" id="two" onclick="fuelList(this)" value="1" />Two Wheeler
                        </label>
                        <label>
                            <input type="radio" name="vehicleList" id="four" onclick="fuelList(this)" value="2" />Four Wheeler
                        </label>
                    </div>

<div id="TwoWheeler" style="display:none">
                        <label>
                            <input type="radio" name="TwoWheeler" value="6" />Electric
                        </label>
                        <label>
                            <input type="radio" name="TwoWheeler" value="7" />Petrol
                        </label>
                    </div>

                    <div id="FourWheeler" style="display:none">
                        <label>
                            <input type="radio" name="FourWheeler" value="1" />Electric
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="2" />Petrol
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="3" />Diesel
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="4" />CNG
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="5" />LPG
                        </label>
                    </div></code>```

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
Yiu can try this working code:

function fuelList(_this){
  var value=$(_this).attr("value");

  $("#TwoWheeler").hide();
  $("#FourWheeler").hide();

  if(value=="1"){
    $("#TwoWheeler").show();
  }
  else  if(value=="2"){
    $("#FourWheeler").show();
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
                        <label>
                            <input type="radio" name="vehicleList" id="two" onclick="fuelList(this)" value="1" />Two Wheeler
                        </label>
                        <label>
                            <input type="radio" name="vehicleList" id="four" onclick="fuelList(this)" value="2" />Four Wheeler
                        </label>
                    </div>

<div id="TwoWheeler" style="display:none">
                        <label>
                            <input type="radio" name="TwoWheeler" value="6" />Electric
                        </label>
                        <label>
                            <input type="radio" name="TwoWheeler" value="7" />Petrol
                        </label>
                    </div>

                    <div id="FourWheeler" style="display:none">
                        <label>
                            <input type="radio" name="FourWheeler" value="1" />Electric
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="2" />Petrol
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="3" />Diesel
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="4" />CNG
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="5" />LPG
                        </label>
                    </div>


问:
Create SQL table with the data from another table
How do I create a table using data which is already present in another table (copy of table)?</p>

答:
For Sql server:

Create new table from existing table :

```<code>CREATE TABLE new_table_name AS
SELECT [col1,col2,...coln] FROM existing_table_name [WHERE condition];
</code>```

Insert values into existing table form another existing table using  Select  command :

```<code>SELECT * INTO destination_table FROM source_table [WHERE conditions];

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
[ WHERE condition ];
</code>```

Insert values into existing table form another existing table using
 Insert  command :

```<code>INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1,column2, column3, ... FROM table1 [WHERE condition];
</code>```

Body:
For Sql server:

Create new table from existing table :

CREATE TABLE new_table_name AS
SELECT [col1,col2,...coln] FROM existing_table_name [WHERE condition];

Insert values into existing table form another existing table using  Select  command :

SELECT * INTO destination_table FROM source_table [WHERE conditions];

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
[ WHERE condition ];

Insert values into existing table form another existing table using
 Insert  command :

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1,column2, column3, ... FROM table1 [WHERE condition];


问:
How to delete additional days added by pandas resample?
I have a pandas df with tick data, with index as datetime64[ns] I want to resample this data into 5 minute intervals like this: price_5min = price.price.resample('5T').ohlc().between_time('09:00:00, '16:20:00')

It works, however it adds weekends and holidays to the new timeseries, which I need to remove. I'm not following US (or any other standard holiday calendar). I just want to remove days not in the original price df.

Index is not unique, many cases of same timestamp. Pandas version 0.20.1

What I have tried:

1) dropna(): I have rows with NANs that I need to ffill, so this will not work.

2) price.index.difference(price_5min.index): Gives me all the tick dates, not the day dates.

3) price.index.date.difference(price_5min.index.date): Does not work as index.date is a numpy.ndarray

4) price != price_5min: Error: Can only compare identically-labeled DataFrame objects

5) price.index != price_4min.index: Error: Lengths must match to compare

Suggested logic to solve my problem:

a) Somehow compare the day dates in the two dataframes and delete based on this, but how?

b) Remove days with no variance, but how?

c) The obvious that I have not thought of (most likely..)

df price looks like this:

```<code>                     price  quantity
time
2016-06-15 16:19:20  29.85     429.6
2016-06-15 16:19:20  29.85      65.6
2016-06-15 16:19:20  29.85    1351.4
2016-06-15 16:19:30  29.70     729.4
2016-06-15 16:19:30  29.70     287.0
2016-06-15 16:19:30  29.70     219.4
2016-06-15 16:19:49  29.70      47.4
2016-06-15 16:19:52  29.70      11.8
2016-06-16 09:01:42  29.05     350.0
2016-06-16 09:01:42  29.10     189.4
2016-06-16 09:01:45  29.05      33.6
2016-06-16 09:01:54  29.05      33.6
...
</code>```

答:
I think you can use np.setdiff1d and numpy.in1d and filter by boolean indexing:

```<code>diffs = np.setdiff1d(price_5min.index.date, price.index.date))
df = price_5min[~np.in1d(price_5min.index.date, diffs]
</code>```

Another solutions with DatetimeIndex.floor orto_period:

```<code>dates = price.index.floor('D')
dates_5min = price_5min.index.floor('D')
df = price_5min[~dates_5min.isin(dates_5min.difference(dates))]
</code>```

```<code>dates = price.index.to_period('D')
dates_5min = price_5min.index.to_period('D')
df = price_5min[~dates_5min.isin(dates_5min.difference(dates))]
</code>```

Body:
I have a pandas df with tick data, with index as datetime64[ns] I want to resample this data into 5 minute intervals like this: price_5min = price.price.resample('5T').ohlc().between_time('09:00:00, '16:20:00')

It works, however it adds weekends and holidays to the new timeseries, which I need to remove. I'm not following US (or any other standard holiday calendar). I just want to remove days not in the original price df.

Index is not unique, many cases of same timestamp. Pandas version 0.20.1

What I have tried:

1) dropna(): I have rows with NANs that I need to ffill, so this will not work.

2) price.index.difference(price_5min.index): Gives me all the tick dates, not the day dates.

3) price.index.date.difference(price_5min.index.date): Does not work as index.date is a numpy.ndarray

4) price != price_5min: Error: Can only compare identically-labeled DataFrame objects

5) price.index != price_4min.index: Error: Lengths must match to compare

Suggested logic to solve my problem:

a) Somehow compare the day dates in the two dataframes and delete based on this, but how?

b) Remove days with no variance, but how?

c) The obvious that I have not thought of (most likely..)

df price looks like this:

                     price  quantity
time
2016-06-15 16:19:20  29.85     429.6
2016-06-15 16:19:20  29.85      65.6
2016-06-15 16:19:20  29.85    1351.4
2016-06-15 16:19:30  29.70     729.4
2016-06-15 16:19:30  29.70     287.0
2016-06-15 16:19:30  29.70     219.4
2016-06-15 16:19:49  29.70      47.4
2016-06-15 16:19:52  29.70      11.8
2016-06-16 09:01:42  29.05     350.0
2016-06-16 09:01:42  29.10     189.4
2016-06-16 09:01:45  29.05      33.6
2016-06-16 09:01:54  29.05      33.6
...

Body:
I think you can use np.setdiff1d and numpy.in1d and filter by boolean indexing:

diffs = np.setdiff1d(price_5min.index.date, price.index.date))
df = price_5min[~np.in1d(price_5min.index.date, diffs]

Another solutions with DatetimeIndex.floor orto_period:

dates = price.index.floor('D')
dates_5min = price_5min.index.floor('D')
df = price_5min[~dates_5min.isin(dates_5min.difference(dates))]

dates = price.index.to_period('D')
dates_5min = price_5min.index.to_period('D')
df = price_5min[~dates_5min.isin(dates_5min.difference(dates))]


问:
Laravel How to register a ServiceProvider within other ServiceProvider
I'm building a modular laravel structure which each module have to register their own resources like controllers, views, translations, etc.

And each Module have their own sub modules which they should be able to register their own resources again. It's a tree like structure.

What I need is to register sub modules ServiceProvider in modules ServiceProvider.

How this can be done?

答:
I solved problem by using Application::registerDeferredProvider method.

Here is an example of how this has done:

```<code>class ModuleServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->registerDeferredProvider(SubModuleServiceProvider::class);
    }
}
</code>```

Good Luck.

Body:
I solved problem by using Application::registerDeferredProvider method.

Here is an example of how this has done:

class ModuleServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->registerDeferredProvider(SubModuleServiceProvider::class);
    }
}

Good Luck.


问:
deleting multiple numbered folders in the terminal
I have directories numbered from 0-1000, for example. I want to delete the directories within the range 400-699, for example, and all their contents on the terminal. Is there a way to do this without me having to do rm -rf XXX where XXX is the directory number?

I have seen this post link but the numbering system we have is a bit different.

答:
It can be done with bash loop like this:

```<code>for i in `seq 400 699`;
do
rm -rf $i
done
</code>```

Please make sure every time you use rm -rf. It cannot be undone in Linux.

Body:
It can be done with bash loop like this:

for i in `seq 400 699`;
do
rm -rf $i
done

Please make sure every time you use rm -rf. It cannot be undone in Linux.


问:
iOS - UICollectionView spacing still there when set to 0 - How to set with no spacing between cells
I have a simple UICollectionView which I have set with 0 spacing in InterfaceBuilder but when I populate the collection view with cells there is still some spacing. Is there something special and not immediately obvious that I need to do in order to actually see a collectionview cell with 0 spacing beyond setting it to have 0 spacing? Thanks.

EDIT* some code:

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor clearColor];

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, cell.frame.size.width -4, cell.frame.size.height -4)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.font = [UIFont boldSystemFontOfSize:20];
    lbl.text = [NSString stringWithFormat:@"$%0.0f", [[amountsArray objectAtIndex:indexPath.row] floatValue]];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.layer.borderWidth = 1;

    [cell addSubview:lbl];
    [lbl release];

    return cell;
}
</code>```

答:
Swift 3 version of @MihirOza 's solution

Worked for both Horizontal and Vertical collection views

Code

```<code>// removing spacing
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
</code>```

Body:
I have a simple UICollectionView which I have set with 0 spacing in InterfaceBuilder but when I populate the collection view with cells there is still some spacing. Is there something special and not immediately obvious that I need to do in order to actually see a collectionview cell with 0 spacing beyond setting it to have 0 spacing? Thanks.

EDIT* some code:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor clearColor];

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, cell.frame.size.width -4, cell.frame.size.height -4)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.font = [UIFont boldSystemFontOfSize:20];
    lbl.text = [NSString stringWithFormat:@"$%0.0f", [[amountsArray objectAtIndex:indexPath.row] floatValue]];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.layer.borderWidth = 1;

    [cell addSubview:lbl];
    [lbl release];

    return cell;
}

Body:
Swift 3 version of @MihirOza 's solution

Worked for both Horizontal and Vertical collection views

Code

// removing spacing
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}


问:
How to add Facebook dependency in offline mode on Android Studio
I am trying to write a program that can make Facebook updates but i have issues adding the Facebook dependency. I already have the sdk but couldn't add to my project because...
even though i have tried adding the gradle.prperties file to the extracted Facebook folder as a comment suggested here

Next i tried adding as suggested on the Facebook official page but i hit this snag...

Now, because if the price of data where I'm from, I'd rather not go online since I already have the sdk locally so my question is how can i manually cache the sdk into my project?

EDIT: For clarity, my question is HOW DO I ADD THE FACEBOOK SDK INTO MY PROJECT WITHOUT GOING ONLINE (i.e. OFFLINE BUILD)?

答:
Download Facebook Android SDK 4.24.0 ARR it from here

Then,
In order to import a .aar library:

Add a .aar file in libs folder.

Use "New Module" option under File menu.

Import the .aar file.

Build gradle and compile the project.


问:
Spring Boot WebSocket with embedded ActiveMQ Broker
I tried to change an web application from simple broker to an embedded ActiveMq Broker with stomp using Spring boot 1.5.4 but always getting an error on start up

```<code>Caused by: java.lang.IllegalArgumentException: No handlers
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.start(SubProtocolWebSocketHandler.java:244) ~[spring-websocket-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 15 common frames omitted
</code>```

I reduced the failure with an simple example

POM File *

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>websocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>websocket</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-stomp</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-net</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.2.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Application Class

```<code>package com.example.websocket;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebsocketApplication.class, args);
    }
}
</code>```

WebSocketConfig Class

```<code>package com.example.websocket;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
@EnableJms
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {

    @Value("${spring.activemq.user}")
    private String mqUser;
    @Value("${spring.activemq.password}")
    private String mqPasword;

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic") //
        .setRelayHost("localhost") //
        .setRelayPort(61613) //
        .setClientLogin(mqUser) //
        .setClientPasscode(mqPasword) //
        ;
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

}
</code>```

application.yml

```<code>spring:
  activemq:
    broker-url: stomp://localhost:61613
    user: user
    password: pass
</code>```

Someone knows my mistake?

答:
I found the solution. My problem was the EnableWebSocketMessageBroker Annotation and missing deployment of ActiveMQ Broker

Remove the application.yml and change WebSocketConfig class to

```<code>package com.example.websocket;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic") //
        .setRelayHost("localhost") //
        .setRelayPort(61613);
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

    @Bean(initMethod = "start", destroyMethod = "stop")
    public BrokerService broker() throws Exception {
        final BrokerService broker = new BrokerService();
        broker.addConnector("stomp://localhost:61613");

        broker.setPersistent(false);
        final ManagementContext managementContext = new ManagementContext();
        managementContext.setCreateConnector(true);
        broker.setManagementContext(managementContext);

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

works for me.

Body:
I tried to change an web application from simple broker to an embedded ActiveMq Broker with stomp using Spring boot 1.5.4 but always getting an error on start up

Caused by: java.lang.IllegalArgumentException: No handlers
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.start(SubProtocolWebSocketHandler.java:244) ~[spring-websocket-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 15 common frames omitted

I reduced the failure with an simple example

POM File *

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>websocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>websocket</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-stomp</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-net</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.2.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Application Class

package com.example.websocket;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebsocketApplication.class, args);
    }
}

WebSocketConfig Class

package com.example.websocket;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
@EnableJms
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {

    @Value("${spring.activemq.user}")
    private String mqUser;
    @Value("${spring.activemq.password}")
    private String mqPasword;

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic") //
        .setRelayHost("localhost") //
        .setRelayPort(61613) //
        .setClientLogin(mqUser) //
        .setClientPasscode(mqPasword) //
        ;
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

}

application.yml

spring:
  activemq:
    broker-url: stomp://localhost:61613
    user: user
    password: pass

Someone knows my mistake?

Body:
I found the solution. My problem was the EnableWebSocketMessageBroker Annotation and missing deployment of ActiveMQ Broker

Remove the application.yml and change WebSocketConfig class to

package com.example.websocket;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic") //
        .setRelayHost("localhost") //
        .setRelayPort(61613);
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

    @Bean(initMethod = "start", destroyMethod = "stop")
    public BrokerService broker() throws Exception {
        final BrokerService broker = new BrokerService();
        broker.addConnector("stomp://localhost:61613");

        broker.setPersistent(false);
        final ManagementContext managementContext = new ManagementContext();
        managementContext.setCreateConnector(true);
        broker.setManagementContext(managementContext);

        return broker;
    }
}

works for me.


问:
How to make a button not show up but still be used by javascript?
I am using a button that has to be invible and should be used by a javascript function.

```<code><asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/
</code>```

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)

答:
How about

```<code>style="display:none"
</code>```

for the button instead of Visible = "true".

Body:
I am using a button that has to be invible and should be used by a javascript function.

<asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)

Body:
How about

style="display:none"

for the button instead of Visible = "true".