问:
How to pass the data with AJAX to Controller in Laravel?
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

```<code>$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});
</code>```

And this is the PostsController, where I need to change just one ID:

```<code>public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }
</code>```

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

```<code>$cars = Car::where('manufacturer_id', $sendedID)->get();
</code>```

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

答:
First of all you have to attach the X-CSRF-TOKEN to send data via AJAX Request. check before send ajax request data is coming to your javascript variable and then in the controller dd() the request for data is successfully sent by ajax.

check the route is ok for send data via post. you can check all registered route it with php artisan route:list code in console...

how to attach the X-CSRF-TOKEN in ajax body

```<code>$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '/laravel/public/posts/create',
    type: "post",
    data: 'id=' + id ,
    success: function (res) {
       //response
    }
});
</code>```

then check in the controller for if data receive correctly. if its a request object you can access the id with $request->id

```<code>Public function create(Request $request){
    dd($request); // this will show data receive from request
    $id = $request->id // access request object id
}
</code>```

Body:
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});

And this is the PostsController, where I need to change just one ID:

public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

$cars = Car::where('manufacturer_id', $sendedID)->get();

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

Body:
First of all you have to attach the X-CSRF-TOKEN to send data via AJAX Request. check before send ajax request data is coming to your javascript variable and then in the controller dd() the request for data is successfully sent by ajax.

check the route is ok for send data via post. you can check all registered route it with php artisan route:list code in console...

how to attach the X-CSRF-TOKEN in ajax body

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '/laravel/public/posts/create',
    type: "post",
    data: 'id=' + id ,
    success: function (res) {
       //response
    }
});

then check in the controller for if data receive correctly. if its a request object you can access the id with $request->id

Public function create(Request $request){
    dd($request); // this will show data receive from request
    $id = $request->id // access request object id
}


来源: stackexchange

问:
How to get the image in the xlink:href tag of an svg image to get converted to a png/jpg image using canvas's toDataURL .?
The SVG image's xlink:href tag contains a path to the image,when i load the svg image in the browser,it properly displays the image.

When i convert the svg image using toDataURL,the converted jpg or png is empty.

```<code>`
image.src = data:image/svg+xml;charset=utf-8,<svg%20xmlns="http:

//www.w3.org/2000/svg"%20width="871"%20height="435">  <foreignObject%20x="0"%20y="0"%20width="100%"%20height="100%"><div%20id="networkDiagramViewContainer"%20ng-right-click="show_traffic_events($event)"%20class="geDiagramContainer"%20style="cursor:%20default;%20width:%20251px;%20height:%20261px;%20overflow:%20initial;"%20xmlns="http://www.w3.org/1999/xhtml"><svg%20xmlns="http://www.w3.org/2000/svg"%20style="width:%20100%;%20height:%20100%;%20display:%20block;%20min-width:%20251px;%20min-height:%20261px;%20background-color:%20rgb(255,%20255,%20255);%20background-image:%20none;"><g><g/><g><g%20style="visibility:%20visible;"><image%20x="170"%20y="180"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Tire_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="170"%20y="180"%20width="80"%20height="80"/></g><g%20style="visibility:%20visible;"><image%20x="40"%20y="50"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Suit_Man_Blue_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="40"%20y="50"%20width="80"%20height="80"/></g></g><g/><g/></g></svg></div></foreignObject></svg>

var canvas = newCanvas(domNode);
canvas.getContext('2d').drawImage(image, 0, 0);
canvas.toDataURL('image/jpeg',1)
`
</code>```

I dont know if the path in the xlink:href tag is an issue.

答:
I was able to solve this by parsing each of the images using the toDataURL and then setting it to the href attribute :</p>

```<code>var img = new Image();
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
// draw the loaded image
canvas.getContext('2d').drawImage(this, 0, 0);
// set our <image>'s href attribute to the dataURL of our canvas
image.setAttributeNS(xlinkNS, 'href', canvas.toDataURL());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The SVG image's xlink:href tag contains a path to the image,when i load the svg image in the browser,it properly displays the image.

When i convert the svg image using toDataURL,the converted jpg or png is empty.

`
image.src = data:image/svg+xml;charset=utf-8,<svg%20xmlns="http:

//www.w3.org/2000/svg"%20width="871"%20height="435">  <foreignObject%20x="0"%20y="0"%20width="100%"%20height="100%">
<svg%20xmlns="http://www.w3.org/2000/svg"%20style="width:%20100%;%20height:%20100%;%20display:%20block;%20min-width:%20251px;%20min-height:%20261px;%20background-color:%20rgb(255,%20255,%20255);%20background-image:%20none;"><g><g/><g><g%20style="visibility:%20visible;"><image%20x="170"%20y="180"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Tire_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="170"%20y="180"%20width="80"%20height="80"/></g><g%20style="visibility:%20visible;"><image%20x="40"%20y="50"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Suit_Man_Blue_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="40"%20y="50"%20width="80"%20height="80"/></g></g><g/><g/></g></svg>
</foreignObject></svg>

var canvas = newCanvas(domNode);
canvas.getContext('2d').drawImage(image, 0, 0);
canvas.toDataURL('image/jpeg',1)
`

I dont know if the path in the xlink:href tag is an issue.

Body:
I was able to solve this by parsing each of the images using the toDataURL and then setting it to the href attribute :

var img = new Image();
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
// draw the loaded image
canvas.getContext('2d').drawImage(this, 0, 0);
// set our <image>'s href attribute to the dataURL of our canvas
image.setAttributeNS(xlinkNS, 'href', canvas.toDataURL());


问:
How should I name my CSS classes?
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

```<code>.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
</code>```

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

答:
There's no "right" answer in my opinion. I tend to do what's more readable so I choose (3). In my opinion there's enough word-word-word style text in html/css already. And when styling up e.g. Wordpress I think it's like a mixer full of dashes, hard to navigate.

But it's my opinion, I think you should just get a feel for what you prefer. What you find easy to read, when you look 8 hours per day on these you should choose something you're comfortable with.

ContentLicense: CC BY-SA 2.5

Title: How should I name my CSS classes?

Body:
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?


问:
iPhone UITextField - Change placeholder text color
I'd like to change the color of the placeholder text I set in my UITextField controls, to make it black.

I'd prefer to do this without using normal text as the placeholder and having to override all the methods to imitate the behaviour of a placeholder.

I believe if I override this method:

```<code>- (void)drawPlaceholderInRect:(CGRect)rect
</code>```

then I should be able to do this. But I'm unsure how to access the actual placeholder object from within this method.

答:
In Swift 3

```<code>import UIKit

let TEXTFIELD_BLUE  = UIColor.blue
let TEXTFIELD_GRAY  = UIColor.gray

class DBTextField: UITextField {
    /// Tetxfield Placeholder Color
    @IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAY
    func setupTextField () {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
                                                            attributes:[NSForegroundColorAttributeName: palceHolderColor])
    }
}

class DBLocalizedTextField : UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.placeholder = self.placeholder
    }
}
</code>```

Body:
I'd like to change the color of the placeholder text I set in my UITextField controls, to make it black.

I'd prefer to do this without using normal text as the placeholder and having to override all the methods to imitate the behaviour of a placeholder.

I believe if I override this method:

- (void)drawPlaceholderInRect:(CGRect)rect

then I should be able to do this. But I'm unsure how to access the actual placeholder object from within this method.

Body:
In Swift 3

import UIKit

let TEXTFIELD_BLUE  = UIColor.blue
let TEXTFIELD_GRAY  = UIColor.gray

class DBTextField: UITextField {
    /// Tetxfield Placeholder Color
    @IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAY
    func setupTextField () {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
                                                            attributes:[NSForegroundColorAttributeName: palceHolderColor])
    }
}

class DBLocalizedTextField : UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.placeholder = self.placeholder
    }
}

ContentLicense: CC BY-SA 4.0


问:
Changing url on loading another html file in a div using only javascript
I am trying to load another html file into a div.I successfuly got that.
Now I also need my url to change accordingly.
how to change the url on loading another html file in a div??
I need this only using javascript

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <input id="tab1" type="radio" name="tabs" checked >
          <label for="tab1" onclick="load_tab1()">
            <span>
              <img src="image/idea.svg">
            </span>TAB1</label>

          <input id="tab2" type="radio" name="tabs">
          <label for="tab2" onclick="load_tab2()">
            <span>
              <img src="image/idea.svg">
            </span>TAB2</label>

  <div class="master_content" id="scroll_bar">
          <div class="page_head">Page 1</div>
          <div class="page">
          <section id="content1" id="scroll_bar">

          </section>

          <section id="content2">

          </section>

          <section id="content3">

          </section>

          <section id="content4">

          </section>

          </div>
      </div></code>```

答:
Based on @cdoshi answer we need to do something like below, This will rewrite the url based on the click on the label. But please make note that if we refresh the page the call html file will be obtained.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function load_tab1() {
            var stateObj = { foo: "tab1" };
            history.pushState(stateObj, "page 1", "tab1.html");
            document.getElementById("content1").innerHTML='<object type="text/html" data="http://localhost/my_functions/tab1.html" ></object>';
        }
        function load_tab2() {
            var stateObj = { foo: "tab2" };
            history.pushState(stateObj, "page 2", "tab2.html");
            document.getElementById("content2").innerHTML='<object type="text/html" data="http://localhost/my_functions/tab2.html" ></object>';
        }
</script>
</head>
<body>
    <input id="tab1" type="radio" name="tabs" checked >
    <label for="tab1" onclick="load_tab1()">
        <span><img src="image/idea.svg"></span>
        TAB1
    </label>

    <input id="tab2" type="radio" name="tabs">
    <label for="tab2" onclick="load_tab2()">
        <span><img src="image/idea.svg"></span>
        TAB2
    </label>

    <div class="master_content" id="scroll_bar">
        <div class="page_head">Page 1</div>
        <div class="page">
            <section id="content1" id="scroll_bar"></section>
            <section id="content2"></section>
            <section id="content3"></section>
            <section id="content4"></section>
        </div>
    </div>
</body>
</html>
</code>```

Body:
I am trying to load another html file into a div.I successfuly got that.
Now I also need my url to change accordingly.
how to change the url on loading another html file in a div??
I need this only using javascript

  <input id="tab1" type="radio" name="tabs" checked >

            TAB1

          <input id="tab2" type="radio" name="tabs">

            TAB2

Page 1

Body:
Based on @cdoshi answer we need to do something like below, This will rewrite the url based on the click on the label. But please make note that if we refresh the page the call html file will be obtained.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function load_tab1() {
            var stateObj = { foo: "tab1" };
            history.pushState(stateObj, "page 1", "tab1.html");
            document.getElementById("content1").innerHTML='<object type="text/html" data="http://localhost/my_functions/tab1.html" ></object>';
        }
        function load_tab2() {
            var stateObj = { foo: "tab2" };
            history.pushState(stateObj, "page 2", "tab2.html");
            document.getElementById("content2").innerHTML='<object type="text/html" data="http://localhost/my_functions/tab2.html" ></object>';
        }
</script>
</head>
<body>
    <input id="tab1" type="radio" name="tabs" checked >
    <label for="tab1" onclick="load_tab1()">
        <span><img src="image/idea.svg"></span>
        TAB1
    </label>

    <input id="tab2" type="radio" name="tabs">
    <label for="tab2" onclick="load_tab2()">
        <span><img src="image/idea.svg"></span>
        TAB2
    </label>

    <div class="master_content" id="scroll_bar">
        <div class="page_head">Page 1</div>
        <div class="page">
            <section id="content1" id="scroll_bar"></section>
            <section id="content2"></section>
            <section id="content3"></section>
            <section id="content4"></section>
        </div>
    </div>
</body>
</html>


问:
Gitlab Pages and React Router
I will use Gitlab Pages. It seems that Gitlab Pages doesn't work with React Router. I get an empty page. How can I use gitlab Pages with react Router?
How can I solve this problem?

/src/App.js

```<code>import React from 'react';
import { Route } from 'react-router-dom';
import HomePage from './components/pages/HomePage';
import LoginPage from './components/pages/LoginPage';

const App = () => (
  <div>
    <Route path="/" exact component={HomePage} />
    <Route path="/login" exact component={LoginPage} />
  </div>
);

export default App;
</code>```

src/index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
registerServiceWorker();
</code>```

答:
HashRouter is one solution.
But, you can still use the BrowserRouter

Short Answer

```<code>// In your src/index.js,
<BrowserRouter basename={process.env.PUBLIC_URL}>
    <App />
</BrowserRouter>
</code>```

And for the environment variable, open your .gitlab-ci.yml and add the following.

```<code>variables:
    PUBLIC_URL: "/your-project-name" # slash is important
</code>```

Also in your .gitlab-ci.yml, in the stage where you deploy the page, add the following to the script section:

```<code>- cp public/index.html public/404.html
</code>```

Explanation

If your project name is ABC,
the gitlab page url would be https://{username}.gitlab.io/ABC
But, react router expects the base url to be https://{username}.gitlab.io/.
So, you need to explicitly tell the ReactRouter about the basename.

The 404.html is needed to allow the user to directly navigate to all of your routes. Without it, GitLab has no idea that your client-side routing is located in your index.html, and will serve the default 404 page.

Title: Gitlab Pages and React Router

Body:
I will use Gitlab Pages. It seems that Gitlab Pages doesn't work with React Router. I get an empty page. How can I use gitlab Pages with react Router?
How can I solve this problem?

/src/App.js

import React from 'react';
import { Route } from 'react-router-dom';
import HomePage from './components/pages/HomePage';
import LoginPage from './components/pages/LoginPage';

const App = () => (

    <Route path="/" exact component={HomePage} />
    <Route path="/login" exact component={LoginPage} />

);

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
registerServiceWorker();

Body:
HashRouter is one solution.
But, you can still use the BrowserRouter

Short Answer

// In your src/index.js,
<BrowserRouter basename={process.env.PUBLIC_URL}>
    <App />
</BrowserRouter>

And for the environment variable, open your .gitlab-ci.yml and add the following.

variables:
    PUBLIC_URL: "/your-project-name" # slash is important

Also in your .gitlab-ci.yml, in the stage where you deploy the page, add the following to the script section:

- cp public/index.html public/404.html

Explanation

If your project name is ABC,
the gitlab page url would be https://{username}.gitlab.io/ABC
But, react router expects the base url to be https://{username}.gitlab.io/.
So, you need to explicitly tell the ReactRouter about the basename.

The 404.html is needed to allow the user to directly navigate to all of your routes. Without it, GitLab has no idea that your client-side routing is located in your index.html, and will serve the default 404 page.


问:
react native ios application crash if remote debug is not enabled
Using react-native. If i turn off "Debug js Remotely" the app crash and system logs errors that i cannot understand.

I open system log inside ios simulator and it log following

```<code>ivf[95067]: [] nw_connection_get_connected_socket_block_invoke 44 Connection has no connected handler
com.apple.CoreSimulator.SimDevice.73F03ED5-12AF-41DD-9108-349E09982B56.launchd_sim[76806] (UIKitApplication:com.simplein.ivf[0x8918][76828][95067]): Service exited due to Segmentation fault: 11
SpringBoard[76823]: UNSUserNotificationServerConnectionListener connection invalidated
 backboardd[76824]: [Common] Unable to get short BSD proc info for 95067: No such process
backboardd[76824]: [Common] Unable to get proc info for 95067: Undefined error: 0
SpringBoard[76823]: [KeyboardArbiter] HW kbd: Failed to set (null) as keyboard focus
assertiond[76828]: Deleted job with label: UIKitApplication:com.simplein.ivf[0x8918][76828]
</code>```

I have no clue in ios developement, but the app crash once i try to render a screen that has an InputText and few other Views.

Strange is if i enable Debug Js Remotely it will work just fine and will not even log any errors.

答:
in this case, problem was that console.log was logging a huge objects, for some reason this is fine when running in debug mode cause react-native in debug use v8 of chrome even on ios, while on phone it will use different engine.

so as it seems, recommendation for not logging huge objects with multiple inheritance (i was logging this of a nested component which had props, navigation, redux store, etc all attached) is important in production. don't leave your console.log in code to avoid such crashs.

Body:
Using react-native. If i turn off "Debug js Remotely" the app crash and system logs errors that i cannot understand.

I open system log inside ios simulator and it log following

ivf[95067]: [] nw_connection_get_connected_socket_block_invoke 44 Connection has no connected handler
com.apple.CoreSimulator.SimDevice.73F03ED5-12AF-41DD-9108-349E09982B56.launchd_sim[76806] (UIKitApplication:com.simplein.ivf[0x8918][76828][95067]): Service exited due to Segmentation fault: 11
SpringBoard[76823]: UNSUserNotificationServerConnectionListener connection invalidated
 backboardd[76824]: [Common] Unable to get short BSD proc info for 95067: No such process
backboardd[76824]: [Common] Unable to get proc info for 95067: Undefined error: 0
SpringBoard[76823]: [KeyboardArbiter] HW kbd: Failed to set (null) as keyboard focus
assertiond[76828]: Deleted job with label: UIKitApplication:com.simplein.ivf[0x8918][76828]

I have no clue in ios developement, but the app crash once i try to render a screen that has an InputText and few other Views.

Strange is if i enable Debug Js Remotely it will work just fine and will not even log any errors.


问:
Load an image into a PictureBox on a different thread
I am trying to load a picture that is fetched on-demand from Google's Static Maps based against a (UK) Post Code.

Lets say I have a client and the clients has an address. One of the properties of client is PostCode. I have a form that loads clients. I feed the client ID to this form's constructor and then use LINQ 2 SQL to load all sorts of information including an address.

```<code>private void LoadBranchDetails() {
  Text_Update_BI_Name.Text = Branch.BranchNumber;
  Text_Update_BI_Manager.Text = String.Format("{0} {1}", Branch.PharmacyManager.FirstName, Branch.PharmacyManager.LastName);
  DropDownList_Update_BI_Coordinator.SelectedValue = Branch.CoordinatorID;
  DropDownList_Update_BI_ComputerSystem.SelectedValue = Branch.ComputerSystemID;
  Text_Update_BI_Phone.Text = Branch.PhoneNumber;
  Text_Update_BI_Fax.Text = Branch.FaxNumber;

  Address BranchAddress = Branch.Contact.Addresses.FirstOrDefault();
  Text_Update_AI_House.Text = BranchAddress.HouseNumber;
  Text_Update_AI_Street.Text = BranchAddress.Street;
  Text_Update_AI_Area.Text = BranchAddress.Area;
  Text_Update_AI_Post.Text = BranchAddress.PostCode;
  DropDownList_Update_AI_City.SelectedValue = BranchAddress.City.OID;

  MaskedText_Update_OI_NoPharmacist.Value = Branch.NumberOfPharmacists;
  MaskedText_Update_OI_NoDispensers.Value = Branch.NumberOfDispensers;
  MaskedText_Update_OI_NoMonFri.Value = Branch.NumberOfItemsMondayToFriday;
  MaskedText_Update_OI_NoSat.Value = Branch.NumberOfItemsSaturday;
  MaskedText_Update_OI_NoSun.Value = Branch.NumberOfItemsSunday;
  MaskedText_Update_OI_NoAddicts.Value = Branch.NumberOfAddicts;
  MaskedText_Update_OI_NoSupervised.Value = Branch.Supervised;
  MaskedText_Update_OI_NoUnsupervised.Value = Branch.Unsupervised;

  Check_Update_OI_ConfRoom.Checked = Branch.ConsultationRoom;

  try {
    PictureGoogleMaps.Image = GoogleAddressInfo.FetchMapInfo(Text_Update_AI_Post.Text).GoogleStaticMap;

  } catch (Exception) {
    PictureGoogleMaps.Image = Resources.DefaultGoogleMap;

  }
}
</code>```

The line that loads the image into the PictureGoogleMaps causes a hang in UI as the ".GoogleStaticMap" property generates the Google static image when called.

Upon searching the internet, i found this helpful example:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Declare a list of URLs and their respective picture boxes
        var items = new Dictionary<string, PictureBox>
        {
            { "http://www.google.com/logos/spring09.gif", new PictureBox() { Top = 0, Width = 300, Height = 80  } },
            { "http://www.google.com/logos/stpatricks_d4gwinner_eo09.gif", new PictureBox() { Top = 100, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/schiaparelli09.gif", new PictureBox() { Top = 200, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/drseuss09.gif", new PictureBox() { Top = 300, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/valentines09.gif", new PictureBox() { Top = 400, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/unix1234567890.gif", new PictureBox() { Top = 500, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/charlesdarwin_09.gif", new PictureBox() { Top = 600, Width = 300, Height = 80 } },
        };

        foreach (var item in items)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                // This function will be run on a background thread
                // spawned from the thread pool.
                using (var client = new WebClient())
                {
                    var pair = (KeyValuePair<string, PictureBox>)e.Argument;
                    e.Result = new KeyValuePair<PictureBox, byte[]>(pair.Value, client.DownloadData(pair.Key));
                }
            };
            worker.RunWorkerCompleted += (o, e) =>
            {
                // This function will be run on the main GUI thread
                var pair = (KeyValuePair<PictureBox, byte[]>)e.Result;
                using (var stream = new MemoryStream(pair.Value))
                {
                    pair.Key.Image = new Bitmap(stream);
                }
                Controls.Add(pair.Key);
            };
            worker.RunWorkerAsync(item);
        }
    }
}
</code>```

Now I just need to figure out how to remove the for loop and use this in my scenario. Any ideas?

The sample code comes from this link.

Thanks.

答:
```<code>public partial class Form1 : Form
    {
        private BackgroundWorker imageLoader;

        public Form1()
        {
            InitializeComponent();

            this.imageLoader = new BackgroundWorker();
            this.imageLoader.DoWork += HandleOnImageLoaderDoWork;
            this.imageLoader.RunWorkerCompleted += HandleImageLoaderOnRunWorkerCompleted;

            this.LoadUserDetails(1);
        }

        private void LoadUserDetails(Int32 userID)
        {
            this.imageLoader.RunWorkerAsync(userID.ToString());
            // get the user details
            // populate the UI controls with the data....
        }

        private void HandleImageLoaderOnRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
        {
            this.pictureBox1.Image = (Image)e.Result;
        }

        private void HandleOnImageLoaderDoWork(Object sender, DoWorkEventArgs e)
        {
            // simulate a web request for an image;
            Thread.Sleep(3000);
            Image image = Image.FromFile(@"test.jpg");
            e.Result = image;
        }
    }
</code>```

Also make sure that you show some UI notification that a background operation is in process...something like a initial image (loading.gif) in the PictureBox.

Body:
I am trying to load a picture that is fetched on-demand from Google's Static Maps based against a (UK) Post Code.

Lets say I have a client and the clients has an address. One of the properties of client is PostCode. I have a form that loads clients. I feed the client ID to this form's constructor and then use LINQ 2 SQL to load all sorts of information including an address.

private void LoadBranchDetails() {
  Text_Update_BI_Name.Text = Branch.BranchNumber;
  Text_Update_BI_Manager.Text = String.Format("{0} {1}", Branch.PharmacyManager.FirstName, Branch.PharmacyManager.LastName);
  DropDownList_Update_BI_Coordinator.SelectedValue = Branch.CoordinatorID;
  DropDownList_Update_BI_ComputerSystem.SelectedValue = Branch.ComputerSystemID;
  Text_Update_BI_Phone.Text = Branch.PhoneNumber;
  Text_Update_BI_Fax.Text = Branch.FaxNumber;

  Address BranchAddress = Branch.Contact.Addresses.FirstOrDefault();
  Text_Update_AI_House.Text = BranchAddress.HouseNumber;
  Text_Update_AI_Street.Text = BranchAddress.Street;
  Text_Update_AI_Area.Text = BranchAddress.Area;
  Text_Update_AI_Post.Text = BranchAddress.PostCode;
  DropDownList_Update_AI_City.SelectedValue = BranchAddress.City.OID;

  MaskedText_Update_OI_NoPharmacist.Value = Branch.NumberOfPharmacists;
  MaskedText_Update_OI_NoDispensers.Value = Branch.NumberOfDispensers;
  MaskedText_Update_OI_NoMonFri.Value = Branch.NumberOfItemsMondayToFriday;
  MaskedText_Update_OI_NoSat.Value = Branch.NumberOfItemsSaturday;
  MaskedText_Update_OI_NoSun.Value = Branch.NumberOfItemsSunday;
  MaskedText_Update_OI_NoAddicts.Value = Branch.NumberOfAddicts;
  MaskedText_Update_OI_NoSupervised.Value = Branch.Supervised;
  MaskedText_Update_OI_NoUnsupervised.Value = Branch.Unsupervised;

  Check_Update_OI_ConfRoom.Checked = Branch.ConsultationRoom;

  try {
    PictureGoogleMaps.Image = GoogleAddressInfo.FetchMapInfo(Text_Update_AI_Post.Text).GoogleStaticMap;

  } catch (Exception) {
    PictureGoogleMaps.Image = Resources.DefaultGoogleMap;

  }
}

The line that loads the image into the PictureGoogleMaps causes a hang in UI as the ".GoogleStaticMap" property generates the Google static image when called.

Upon searching the internet, i found this helpful example:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Declare a list of URLs and their respective picture boxes
        var items = new Dictionary<string, PictureBox>
        {
            { "http://www.google.com/logos/spring09.gif", new PictureBox() { Top = 0, Width = 300, Height = 80  } },
            { "http://www.google.com/logos/stpatricks_d4gwinner_eo09.gif", new PictureBox() { Top = 100, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/schiaparelli09.gif", new PictureBox() { Top = 200, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/drseuss09.gif", new PictureBox() { Top = 300, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/valentines09.gif", new PictureBox() { Top = 400, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/unix1234567890.gif", new PictureBox() { Top = 500, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/charlesdarwin_09.gif", new PictureBox() { Top = 600, Width = 300, Height = 80 } },
        };

        foreach (var item in items)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                // This function will be run on a background thread
                // spawned from the thread pool.
                using (var client = new WebClient())
                {
                    var pair = (KeyValuePair<string, PictureBox>)e.Argument;
                    e.Result = new KeyValuePair<PictureBox, byte[]>(pair.Value, client.DownloadData(pair.Key));
                }
            };
            worker.RunWorkerCompleted += (o, e) =>
            {
                // This function will be run on the main GUI thread
                var pair = (KeyValuePair<PictureBox, byte[]>)e.Result;
                using (var stream = new MemoryStream(pair.Value))
                {
                    pair.Key.Image = new Bitmap(stream);
                }
                Controls.Add(pair.Key);
            };
            worker.RunWorkerAsync(item);
        }
    }
}

Now I just need to figure out how to remove the for loop and use this in my scenario. Any ideas?

The sample code comes from this link.

Thanks.

Body:
public partial class Form1 : Form
    {
        private BackgroundWorker imageLoader;

        public Form1()
        {
            InitializeComponent();

            this.imageLoader = new BackgroundWorker();
            this.imageLoader.DoWork += HandleOnImageLoaderDoWork;
            this.imageLoader.RunWorkerCompleted += HandleImageLoaderOnRunWorkerCompleted;

            this.LoadUserDetails(1);
        }

        private void LoadUserDetails(Int32 userID)
        {
            this.imageLoader.RunWorkerAsync(userID.ToString());
            // get the user details
            // populate the UI controls with the data....
        }

        private void HandleImageLoaderOnRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
        {
            this.pictureBox1.Image = (Image)e.Result;
        }

        private void HandleOnImageLoaderDoWork(Object sender, DoWorkEventArgs e)
        {
            // simulate a web request for an image;
            Thread.Sleep(3000);
            Image image = Image.FromFile(@"test.jpg");
            e.Result = image;
        }
    }

Also make sure that you show some UI notification that a background operation is in process...something like a initial image (loading.gif) in the PictureBox.


问:
I am looking to create instances of a class from user input
I Have this class:

class Bowler:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)
```

<p>I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:</p>

```def getData():
    name, score = input("Please enter your credentails (Name score): ").split()
    B1 = Bowler(name, score)
    print(B1.nameScore())
```

But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.

Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.

答:
This is my code to do what you want:

```<code>class Bowler:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)

def getData():
    try:
        line = input("Please enter your credentails (Name score): ")
    except SyntaxError as e:
        return None
    name, score = line.split()
    score = int(score)
    B = Bowler(name, score)
    print(B.nameScore())
    return B

if __name__ == '__main__':
    bowlers = list()
    while True:
        B = getData()
        if B == None:
            break
        bowlers.append(B)

    for B in bowlers:
        print(B.nameScore())
</code>```

In addition, I recommend you to modify your input for it's inconvenient now

Body:
I Have this class:

class Bowler:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)

I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:

def getData():
    name, score = input("Please enter your credentails (Name score): ").split()
    B1 = Bowler(name, score)
    print(B1.nameScore())

But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.

Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.

Body:
This is my code to do what you want:

class Bowler:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)

def getData():
    try:
        line = input("Please enter your credentails (Name score): ")
    except SyntaxError as e:
        return None
    name, score = line.split()
    score = int(score)
    B = Bowler(name, score)
    print(B.nameScore())
    return B

if __name__ == '__main__':
    bowlers = list()
    while True:
        B = getData()
        if B == None:
            break
        bowlers.append(B)

    for B in bowlers:
        print(B.nameScore())

In addition, I recommend you to modify your input for it's inconvenient now


问:
java.lang.NullPointerException when Zypher is publishing report to JIRA
I use a reportng format to publish the report to the Jira, but I am seeing the nullpointer exception:

```<code>java.lang.NullPointerException
at com.thed.zephyr.jenkins.utils.rest.TestCaseUtil.executeTests(TestCaseUtil.java:424)
at com.thed.zephyr.jenkins.utils.rest.TestCaseUtil.processTestCaseDetails(TestCaseUtil.java:564)
at com.thed.zephyr.jenkins.reporter.ZfjReporter.perform(ZfjReporter.java:99)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
at hudson.model.Build$BuildExecution.post2(Build.java:186)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
at hudson.model.Run.execute(Run.java:1749)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
Build step 'Publish test result to Zephyr for JIRA' marked build as failure
Finished: FAILURE
</code>```

Do you know why? Or how to fix it?

答: It seems like an ongoing issue in the Jenkins community. You can subscribe to their JIRA feed for further updates. </p>

Body:
I use a reportng format to publish the report to the Jira, but I am seeing the nullpointer exception:

java.lang.NullPointerException
at com.thed.zephyr.jenkins.utils.rest.TestCaseUtil.executeTests(TestCaseUtil.java:424)
at com.thed.zephyr.jenkins.utils.rest.TestCaseUtil.processTestCaseDetails(TestCaseUtil.java:564)
at com.thed.zephyr.jenkins.reporter.ZfjReporter.perform(ZfjReporter.java:99)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
at hudson.model.Build$BuildExecution.post2(Build.java:186)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
at hudson.model.Run.execute(Run.java:1749)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
Build step 'Publish test result to Zephyr for JIRA' marked build as failure
Finished: FAILURE

Do you know why? Or how to fix it?


问:
Switch statement in Swift
I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:

```<code>for i in 1...100{

    switch (i){
    case 1:
        Int(i%3) == 0
        println("Fizz")
    case 2:
        Int(i%5) == 0
        println("Buzz")
    default:
        println("\(i)")
    }
}
</code>```

I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing?

Note: I did solve it using the following:

```<code>for ( var i = 0; i < 101; i++){

    if (Int(i%3) == 0){
        println("Fizz")
    }   else if (Int(i%5) == 0){
        println("Buzz")
    }   else {
        println("\(i)")
    }
}
</code>```

I want to know how to solve this using Switch. Thank you.

答:
This is a more general answer for people who come here just wanting to know how to use the switch statement in Swift.

General usage

```<code>switch someValue {
case valueOne:
    // executable code
case valueTwo:
    // executable code
default:
    // executable code
}
</code>```

Example

```<code>let someValue = "horse"

switch someValue {
case "horse":
    print("eats grass")
case "wolf":
    print("eats meat")
default:
    print("no match")
}
</code>```

Notes:

No break statement is necessary. It is the default behavior. Swift switch cases do not "fall through". If you want them to fall through to the code in the next case, you must explicitly use the fallthrough keyword.

Every case must include executable code. If you want to ignore a case, you can add a single break statement.

The cases must be exhaustive. That is, they must cover every possibly value. If it is not feasible to include enough case statements, a default statement can be included last to catch any other values.

The Swift switch statement is very flexible. The following sections include some other ways of using it.

Matching multiple values

You can match multiple values in a single case if you use separate the values with commas. This is called a compound case.

```<code>let someValue = "e"

switch someValue {
case "a", "b", "c":
    // executable code
case "d", "e":
    // executable code
default:
    // executable code
}
</code>```

You can also match whole intervals.

```<code>let someValue = 4

switch someValue {
case 0..<10:
    // executable code
case 10...100:
    // executable code
default:
    // executable code
}
</code>```

You can even use tuples. This example is adapted from the documentation.

```<code>let aPoint = (1, 1)

switch aPoint {
case (0, 0):
    // only catches an exact match for first and second
case (_, 0):
    // any first, exact second
case (-2...2, -2...2):
    // range for first and second
default:
    // catches anything else
}
</code>```

Value Bindings

Sometimes you might want to create a temporary constant or variable from the switch value. You can do this right after the case statement. Anywhere that a value binding is used, it will match any value. This is similar to using _ in the tuple example above. The following two examples are modified from the documentation.

```<code>let anotherPoint = (2, 0)

switch anotherPoint {
case (let x, 0):
    // can use x here
case (0, let y):
    // can use y here
case let (x, y):
    // can use x or y here, matches anything so no "default" case is necessary
}
</code>```

You can further refine the matching by using the where keyword.

```<code>let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
    // executable code
case let (x, y) where x == -y:
    // executable code
case let (x, y):
    // executable code
}
</code>```

Further study

This answer was meant to be a quick reference. Please read the full documentation for more. It isn't difficult to understand.

Title: Switch statement in Swift

Body:
I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:

for i in 1...100{

    switch (i){
    case 1:
        Int(i%3) == 0
        println("Fizz")
    case 2:
        Int(i%5) == 0
        println("Buzz")
    default:
        println("\(i)")
    }
}

I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing?

Note: I did solve it using the following:

for ( var i = 0; i < 101; i++){

    if (Int(i%3) == 0){
        println("Fizz")
    }   else if (Int(i%5) == 0){
        println("Buzz")
    }   else {
        println("\(i)")
    }
}

I want to know how to solve this using Switch. Thank you.

Body:
This is a more general answer for people who come here just wanting to know how to use the switch statement in Swift.

General usage

switch someValue {
case valueOne:
    // executable code
case valueTwo:
    // executable code
default:
    // executable code
}

Example

let someValue = "horse"

switch someValue {
case "horse":
    print("eats grass")
case "wolf":
    print("eats meat")
default:
    print("no match")
}

Notes:

No break statement is necessary. It is the default behavior. Swift switch cases do not "fall through". If you want them to fall through to the code in the next case, you must explicitly use the fallthrough keyword.

Every case must include executable code. If you want to ignore a case, you can add a single break statement.

The cases must be exhaustive. That is, they must cover every possibly value. If it is not feasible to include enough case statements, a default statement can be included last to catch any other values.

The Swift switch statement is very flexible. The following sections include some other ways of using it.

Matching multiple values

You can match multiple values in a single case if you use separate the values with commas. This is called a compound case.

let someValue = "e"

switch someValue {
case "a", "b", "c":
    // executable code
case "d", "e":
    // executable code
default:
    // executable code
}

You can also match whole intervals.

let someValue = 4

switch someValue {
case 0..<10:
    // executable code
case 10...100:
    // executable code
default:
    // executable code
}

You can even use tuples. This example is adapted from the documentation.

let aPoint = (1, 1)

switch aPoint {
case (0, 0):
    // only catches an exact match for first and second
case (_, 0):
    // any first, exact second
case (-2...2, -2...2):
    // range for first and second
default:
    // catches anything else
}

Value Bindings

Sometimes you might want to create a temporary constant or variable from the switch value. You can do this right after the case statement. Anywhere that a value binding is used, it will match any value. This is similar to using _ in the tuple example above. The following two examples are modified from the documentation.

let anotherPoint = (2, 0)

switch anotherPoint {
case (let x, 0):
    // can use x here
case (0, let y):
    // can use y here
case let (x, y):
    // can use x or y here, matches anything so no "default" case is necessary
}

You can further refine the matching by using the where keyword.

let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
    // executable code
case let (x, y) where x == -y:
    // executable code
case let (x, y):
    // executable code
}

Further study

This answer was meant to be a quick reference. Please read the full documentation for more. It isn't difficult to understand.


问:
Vim whole word search - but faster
I know that to search for a whole word in vim you need to type:

```<code>/\<word\><CR>
</code>```

Now, what I would like to do is to map this behaviour to ? (as I never search backwards, and if needed I could search forward and then NN). I.e. I'd like to type:

```<code>?word<CR>
</code>```

and have the same result as above (vim searches the whole word). I've been fiddling around with vim commands and mappings for some weeks now, but I'm not sure about how to accomplish this one. Thank you for any help.

Update: (insead of ? I use \ now).

答:
I tend to use * and # (as suggested by Brian Agnew), but if you want a method that involves typing

```<code>?word<CR>
</code>```

you could do something like this:

```<code>function! SearchWord(word)
    let @/ = '\<' . a:word . '\>'
    normal n
endfunction
command! -nargs=1 SearchWord call SearchWord(<f-args>)
nmap ? :SearchWord
</code>```

Note there is a space after SearchWord on the last line.

Explanation:

The mapping will make ? open up a command prompt and type SearchWord (including the space).  The command makes SearchWord myword do the equivalent of call SearchWord('myword') (i.e. it puts the quotes round the argument in order to make it into a string).  The function sets the search register @/ equal to your word surrounded by \< and \> and then does a normal-mode n to find the next instance of the contents of the search register.

Of course you lose the benefits of incremental searching if you do this, but hopefully it's useful anyway.

Title: Vim whole word search - but faster

Body:
I know that to search for a whole word in vim you need to type:

/\<word\><CR>

Now, what I would like to do is to map this behaviour to ? (as I never search backwards, and if needed I could search forward and then NN). I.e. I'd like to type:

?word<CR>

and have the same result as above (vim searches the whole word). I've been fiddling around with vim commands and mappings for some weeks now, but I'm not sure about how to accomplish this one. Thank you for any help.

Update: (insead of ? I use \ now).

Body:
I tend to use * and # (as suggested by Brian Agnew), but if you want a method that involves typing

?word<CR>

you could do something like this:

function! SearchWord(word)
    let @/ = '\<' . a:word . '\>'
    normal n
endfunction
command! -nargs=1 SearchWord call SearchWord(<f-args>)
nmap ? :SearchWord

Note there is a space after SearchWord on the last line.

Explanation:

The mapping will make ? open up a command prompt and type SearchWord (including the space).  The command makes SearchWord myword do the equivalent of call SearchWord('myword') (i.e. it puts the quotes round the argument in order to make it into a string).  The function sets the search register @/ equal to your word surrounded by \< and \> and then does a normal-mode n to find the next instance of the contents of the search register.

Of course you lose the benefits of incremental searching if you do this, but hopefully it's useful anyway.


问:
Why won't my click event in Vue.js fire?
I'm trying to use Vue's on-click directive on a div but it does not fire as intended. When I click the .demo class nothing happens; I should get a 'test clicked' in the console. I don't see any errors in the console, so I don't know what am I doing wrong.

var app = new Vue({
  el: '#app',
  data: {
    title: 'This is the first vue app',
    name: 'ALRAZY',
    link: 'http://google.com',
    attachRed: false
  },
  methods: {
    changeLink: function() {
      this.link = 'http://apple.com'
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Trykker', 'Spectral SC', serif;
}

h1,h2,h3,h4,h5,h6 {
  font-family: 'Spectral SC', serif;
}

p {
  font-family: 'Trykker', serif;
}

.demo {
  width: 100px;
  height: 100px;
  background-color: grey;
  display: inline-block;
  margin: 10px;
}

.red {
  background: red;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Spectral+SC:400,400i,500,500i,600|Trykker" rel="stylesheet" >

{{ title }}

      <input type="text" v-model="name" name="">

 {{ name }}

      <button onclick="changeLink" class="btn btn-danger btn-lg">click to change</button>
      Link

You can see me!!!

Do You see me??

```

答:
You're using the standard onclick attribute which is not going to trigger vue methods. Try using v-on:click="changeLink()" or @click="changeLink()" (I'm not entirely sure if the second is the correct syntax). That should resolve your problem.

Similarly, you can do @click="attachRed = !attachRed".

Body:
I'm trying to use Vue's on-click directive on a div but it does not fire as intended. When I click the .demo class nothing happens; I should get a 'test clicked' in the console. I don't see any errors in the console, so I don't know what am I doing wrong.

var app = new Vue({
  el: '#app',
  data: {
    title: 'This is the first vue app',
    name: 'ALRAZY',
    link: 'http://google.com',
    attachRed: false
  },
  methods: {
    changeLink: function() {
      this.link = 'http://apple.com'
    }
  }
})

body {
  font-family: 'Trykker', 'Spectral SC', serif;
}

h1,h2,h3,h4,h5,h6 {
  font-family: 'Spectral SC', serif;
}

p {
  font-family: 'Trykker', serif;
}

.demo {
  width: 100px;
  height: 100px;
  background-color: grey;
  display: inline-block;
  margin: 10px;
}

.red {
  background: red;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Spectral+SC:400,400i,500,500i,600|Trykker" rel="stylesheet" >

{{ title }}

      <input type="text" v-model="name" name="">

 {{ name }}

      <button onclick="changeLink" class="btn btn-danger btn-lg">click to change</button>
      Link

You can see me!!!

Do You see me??


问:
Adding a unique constraint on a nullable column in PSQL
I am having a table with two columns. Want to add unique constraint on both columns. One of the column is nullable.

I m trying with this syntax:

```<code>ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, (coalesce(a_name, '')));
</code>```

Its prompting error at or near "("

答:
You don't need to use coalesce in that case. Just create constraint in the usual way:

```<code>ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, a_name);
</code>```

Body:
I am having a table with two columns. Want to add unique constraint on both columns. One of the column is nullable.

I m trying with this syntax:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, (coalesce(a_name, '')));

Its prompting error at or near "("

Body:
You don't need to use coalesce in that case. Just create constraint in the usual way:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, a_name);


问:
What's the right way to float right or left using the material-ui appbar with material-ui-next?
I can't figure out if I'm using the right approach to get the login/logout buttons to float right in while using material-ui-next ("material-ui": "^1.0.0-beta.22",)

It seems they removed iconElementRight= from the api. Do we have to use the <Grid> now in the appbar? It feels kinds of cludgy. What's the right way to float buttons (e.g. login) in the appbar?

```<code><AppBar position="static">
      <Toolbar>
        <Grid container spacing={24}>
          <Grid item xs={11}>
            <Typography type="title" color="inherit">
              Title
            </Typography>
          </Grid>

          <Grid item xs={1}>
            <div>
              <HeartIcon />
              <Button raised color="accent">
                Login
              </Button>
            </div>
          </Grid>
        </Grid>
      </Toolbar>
    </AppBar>
</code>```

答:
You need to add flex: 1 to your <Typography /> component so it pushes the
 to the rightmost part of the AppBar:

```<code><AppBar position="static">
  <Toolbar>
    <Typography type="title" color="inherit" style={{ flex: 1 }}>
      Title
    </Typography>
    <div>
      <HeartIcon />
      <Button raised color="accent">
        Login
      </Button>
    </div>
  </Toolbar>
</AppBar>
</code>```

Body:
I can't figure out if I'm using the right approach to get the login/logout buttons to float right in while using material-ui-next ("material-ui": "^1.0.0-beta.22",)

It seems they removed iconElementRight= from the api. Do we have to use the <Grid> now in the appbar? It feels kinds of cludgy. What's the right way to float buttons (e.g. login) in the appbar?

<AppBar position="static">
      <Toolbar>
        <Grid container spacing={24}>
          <Grid item xs={11}>
            <Typography type="title" color="inherit">
              Title
            </Typography>
          </Grid>

          <Grid item xs={1}>

              <HeartIcon />
              <Button raised color="accent">
                Login
              </Button>

          </Grid>
        </Grid>
      </Toolbar>
    </AppBar>

Body:
You need to add flex: 1 to your <Typography /> component so it pushes the <div /> to the rightmost part of the AppBar:

<AppBar position="static">
  <Toolbar>
    <Typography type="title" color="inherit" style={{ flex: 1 }}>
      Title
    </Typography>
    <div>
      <HeartIcon />
      <Button raised color="accent">
        Login
      </Button>
    </div>
  </Toolbar>
</AppBar>


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
I second that Mehrdad's explanation is to the point.

It's not uncommon that in C code you define a variable with the same name as the struct name for instance "node node;". Maybe it is not a good style; it is common in, e.g. linux kernel, code.

The real problem in the original code is that the compiler doesn't know how to interpret "tree" in "(tree*) malloc". According to the compiling error, it is obviously interpreted as a variable.

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?


问:
Changing The Date Values of NSUserDefaults standardUserDefaults from a Dictionary Response
My method receives a Dictionary named responseDict which contains keys, such as id, status, name, phoneNumber, date etc. in

```<code>responseDict[@"data"][@"value"][n]
</code>```

(n for number)

If our code uses NSUserDefaults to access data:

```<code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
</code>```

How can I change the date MySQL attribute 2017-05-12 10:00:00 to Dec 5, 2017 10 AM?

I tried the following, but it does not seem to change the defaults in the UILabel.

```<code>[defaults setInteger:[dictionary[@"id"] integerValue] forKey:@"ID"];
[defaults setObject:dictionary[@"status"] forKey:kNSUDoctorStatus];
[defaults setInteger:[dictionary[@"dur"] integerValue] forKey:@"duration"];
[defaults setObject:[NSString stringWithFormat:@"%@ some",dictionary[@"date"]] forKey:@"date"];
[defaults synchronize];
</code>```

Edit:

UILabel

The UILabel seems to have been added to the view by:

```<code>UILabel *vb = (UILabel *)[self.view viewWithTag:personMessageViewTag];
</code>```

which was defined by:

```<code>#define personMessageViewTag 3001
</code>```

Doctor Class

There is also a PersonDetailView class initialized:

```<code>PersonDetailView *personOnTheView;
</code>```

And called in a method:

```<code>personOnTheView = [PersonDetailView sharedInstance];
personOnTheView.delegate = self;
[personOnTheView updateValues];
[self.view addSubview:personOnTheView];
</code>```

Method:
Here is the code for [personOnTheView updateValues]

```<code>-(void)updateValues{

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    NSString *strImageUrl = [NSString stringWithFormat:@"%@%@",baseUrlForXXHDPIImage,[ud objectForKey:kOnGoingBookingPersonProfileImageKey]];
    _doctorName.text = [ud objectForKey:kOnGoingBookingPersonNameKey];

    NSString *at = [NSString stringWithFormat:@"%@",flStrForObj([Helper getLocalDate:[ud objectForKey:kOnGoingBookingPersonBookingDate]])];

    _appoinmentTime.text = at;

     float rating = [[ud objectForKey:kOnGoingBookingPersonRatingKey] floatValue];

    _starRatingView.value = rating;

    [_profilepic sd_setImageWithURL:[NSURL URLWithString:[Helper removeWhiteSpaceFromURL:strImageUrl]]
                  placeholderImage:[UIImage imageNamed:@"doctor_image_thumbnail"]
                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
                         }];
}
</code>```

Problem:

Everytime I change or modify:

```<code>[defaults setObject:dictionary[kPNPayloadAppoinmentTimeKey] forKey:kOnGoingBookingPersonBookingDate];
</code>```

To:

```<code>[defaults setObject:[NSString stringWithFormat:@"%@ some",dictionary[@"date"]] forKey:@"date"];
</code>```

or just as simple as:

```<code>[defaults setObject:@"Something here" forKey:@"date"];
</code>```

It displays blank.

Additional Information Edit:

[Helper getLocalDate] code:

```<code>+(NSString *)getLocalDate:(NSString *)gmtdate {

    NSString *dateStr = gmtdate;
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *destinationDate = [dateFormatter1 dateFromString:dateStr];

    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
    [dateFormatters setDateFormat:@"MMM d, yyyy HH a"];
    dateStr = [dateFormatters stringFromDate: destinationDate];
    // NSLog(@"DateString : %@", dateStr);
    return dateStr;
}
</code>```

答:
With the help of this method you can get the date in local format if you having time zone in date string

```<code>-(NSDate*)convertDateToLocal:(NSString *)strDate
{
    NSDateFormatter *localFormat = [[NSDateFormatter alloc] init];
    [localFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    NSDate *localDate = [localFormat dateFromString:strDate];
    return localDate;
}
</code>```

Here are two public method for date conversion if you don't have time zone

1) Date from string,

```<code>+ (NSDate *)dateFromString:(NSString *)strSource inFormat:(NSString *)strTargetFormat
{
  NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
  [dtfFormatter setDateFormat:strTargetFormat];

  return [dtfFormatter dateFromString:strSource];
}
</code>```

2) String from date,

```<code>+ (NSString *)stringFromDate:(NSDate *)dtSourceDate inFormat:(NSString *)strTargetFormat
{
  NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
  [dtfFormatter setDateFormat:strTargetFormat];

  if (dtSourceDate != nil)
    return [dtfFormatter stringFromDate:dtSourceDate];
  else
    return @"";
}
</code>```

Hope this helps.

Body:
My method receives a Dictionary named responseDict which contains keys, such as id, status, name, phoneNumber, date etc. in

responseDict[@"data"][@"value"][n]

(n for number)

If our code uses NSUserDefaults to access data:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

How can I change the date MySQL attribute 2017-05-12 10:00:00 to Dec 5, 2017 10 AM?

I tried the following, but it does not seem to change the defaults in the UILabel.

[defaults setInteger:[dictionary[@"id"] integerValue] forKey:@"ID"];
[defaults setObject:dictionary[@"status"] forKey:kNSUDoctorStatus];
[defaults setInteger:[dictionary[@"dur"] integerValue] forKey:@"duration"];
[defaults setObject:[NSString stringWithFormat:@"%@ some",dictionary[@"date"]] forKey:@"date"];
[defaults synchronize];

Edit:

UILabel

The UILabel seems to have been added to the view by:

UILabel *vb = (UILabel *)[self.view viewWithTag:personMessageViewTag];

which was defined by:

#define personMessageViewTag 3001

Doctor Class

There is also a PersonDetailView class initialized:

PersonDetailView *personOnTheView;

And called in a method:

personOnTheView = [PersonDetailView sharedInstance];
personOnTheView.delegate = self;
[personOnTheView updateValues];
[self.view addSubview:personOnTheView];

Method:
Here is the code for [personOnTheView updateValues]

-(void)updateValues{

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    NSString *strImageUrl = [NSString stringWithFormat:@"%@%@",baseUrlForXXHDPIImage,[ud objectForKey:kOnGoingBookingPersonProfileImageKey]];
    _doctorName.text = [ud objectForKey:kOnGoingBookingPersonNameKey];

    NSString *at = [NSString stringWithFormat:@"%@",flStrForObj([Helper getLocalDate:[ud objectForKey:kOnGoingBookingPersonBookingDate]])];

    _appoinmentTime.text = at;

     float rating = [[ud objectForKey:kOnGoingBookingPersonRatingKey] floatValue];

    _starRatingView.value = rating;

    [_profilepic sd_setImageWithURL:[NSURL URLWithString:[Helper removeWhiteSpaceFromURL:strImageUrl]]
                  placeholderImage:[UIImage imageNamed:@"doctor_image_thumbnail"]
                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
                         }];
}

Problem:

Everytime I change or modify:

[defaults setObject:dictionary[kPNPayloadAppoinmentTimeKey] forKey:kOnGoingBookingPersonBookingDate];

To:

[defaults setObject:[NSString stringWithFormat:@"%@ some",dictionary[@"date"]] forKey:@"date"];

or just as simple as:

[defaults setObject:@"Something here" forKey:@"date"];

It displays blank.

Additional Information Edit:

[Helper getLocalDate] code:

+(NSString *)getLocalDate:(NSString *)gmtdate {

    NSString *dateStr = gmtdate;
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *destinationDate = [dateFormatter1 dateFromString:dateStr];

    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
    [dateFormatters setDateFormat:@"MMM d, yyyy HH a"];
    dateStr = [dateFormatters stringFromDate: destinationDate];
    // NSLog(@"DateString : %@", dateStr);
    return dateStr;
}

Body:
With the help of this method you can get the date in local format if you having time zone in date string

-(NSDate*)convertDateToLocal:(NSString *)strDate
{
    NSDateFormatter *localFormat = [[NSDateFormatter alloc] init];
    [localFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    NSDate *localDate = [localFormat dateFromString:strDate];
    return localDate;
}

Here are two public method for date conversion if you don't have time zone

1) Date from string,

+ (NSDate *)dateFromString:(NSString *)strSource inFormat:(NSString *)strTargetFormat
{
  NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
  [dtfFormatter setDateFormat:strTargetFormat];

  return [dtfFormatter dateFromString:strSource];
}

2) String from date,

+ (NSString *)stringFromDate:(NSDate *)dtSourceDate inFormat:(NSString *)strTargetFormat
{
  NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
  [dtfFormatter setDateFormat:strTargetFormat];

  if (dtSourceDate != nil)
    return [dtfFormatter stringFromDate:dtSourceDate];
  else
    return @"";
}

Hope this helps.


问:
How to use findViewById in a public class ItemThreeFragment extends Fragment
I want to display another fragment within my fragment that has been showed and when I Run it it will show an error  Error:(31, 75) error: cannot find symbol method findViewById(int), is their some kind of way that I can use the findViewByID in a fragment class not AppCompatActivity ?

```<code>ItemThreeFragment.java

public class ItemThreeFragment extends Fragment {

private BottomNavigationView bottomNavigationView;

public static ItemThreeFragment newInstance() {
    ItemThreeFragment fragment = new ItemThreeFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.NavGroup);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getChildFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

                }
            });

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_item_three, container, false);

}
}
</code>```

Code for the fragment what Im calling

```<code>GroupOne.java

public class GroupOne extends Fragment {
public static GroupOne newInstance() {
    GroupOne fragment = new GroupOne();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_one, container, false);
}
}
</code>```

for    GroupTwo.java

```<code>public class GroupTwo extends Fragment {
public static GroupTwo newInstance() {
    GroupTwo fragment = new GroupTwo();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_two, container, false);
}
}
</code>```

This is my Main Activity

public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.NavBot);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.home:
                            selectedFragment = ItemOneFragment.newInstance();
                            break;
                        case R.id.search:
                            selectedFragment = ItemTwoFragment.newInstance();
                            break;
                        case R.id.groups:
                            selectedFragment = ItemThreeFragment.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance());
    transaction.commit();

    //Used to select an item programmatically
    //bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
</code>```

activity_main.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.MainActivity">

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/navigation"
    android:animateLayoutChanges="true"
    android:layout_below="@+id/bottomNavigationView">
</FrameLayout>

<android.support.design.widget.BottomNavigationView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NavBot"
    android:layout_gravity="bottom"
    app:menu="@menu/menu_nav"
    android:background="@color/Lime"
    app:itemIconTint="@android:color/white"
    app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>
</code>```

fragment_item_three.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:weightSum="1">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/searchGroup"
        android:scrollbarSize="10dp"/>

    <android.support.design.widget.BottomNavigationView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/NavGroup"
        android:layout_gravity="bottom"
        app:menu="@menu/menu_group"
        android:background="@color/Lime"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

    <FrameLayout
        android:id="@+id/groupFrame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:animateLayoutChanges="true"
        android:layout_below="@+id/bottomNavigationView">
    </FrameLayout>

</LinearLayout>
</code>```

fragment_group_one.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupOne">

<!-- TODO: Update blank fragment layout -->

<TextView
    android:text="Hay salamat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView3" />
</code>```

fragment_group_two.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupTwo">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hay Humana" />
</code>```

答:
This is the answer to my question

```<code> private void findViews(View view)
{
    bottomNavigationView = (BottomNavigationView)view.findViewById(R.id.NavGroup);
    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

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

then add in the onCreateView

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_three, container, false);
    findViews(view);
    return view;

}
</code>```

Body:
I want to display another fragment within my fragment that has been showed and when I Run it it will show an error  Error:(31, 75) error: cannot find symbol method findViewById(int), is their some kind of way that I can use the findViewByID in a fragment class not AppCompatActivity ?

ItemThreeFragment.java

public class ItemThreeFragment extends Fragment {

private BottomNavigationView bottomNavigationView;

public static ItemThreeFragment newInstance() {
    ItemThreeFragment fragment = new ItemThreeFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.NavGroup);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getChildFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

                }
            });

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_item_three, container, false);

}
}

Code for the fragment what Im calling

GroupOne.java

public class GroupOne extends Fragment {
public static GroupOne newInstance() {
    GroupOne fragment = new GroupOne();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_one, container, false);
}
}

for    GroupTwo.java

public class GroupTwo extends Fragment {
public static GroupTwo newInstance() {
    GroupTwo fragment = new GroupTwo();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_two, container, false);
}
}

This is my Main Activity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.NavBot);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.home:
                            selectedFragment = ItemOneFragment.newInstance();
                            break;
                        case R.id.search:
                            selectedFragment = ItemTwoFragment.newInstance();
                            break;
                        case R.id.groups:
                            selectedFragment = ItemThreeFragment.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance());
    transaction.commit();

    //Used to select an item programmatically
    //bottomNavigationView.getMenu().getItem(2).setChecked(true);
}

activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.MainActivity">

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/navigation"
    android:animateLayoutChanges="true"
    android:layout_below="@+id/bottomNavigationView">
</FrameLayout>

<android.support.design.widget.BottomNavigationView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NavBot"
    android:layout_gravity="bottom"
    app:menu="@menu/menu_nav"
    android:background="@color/Lime"
    app:itemIconTint="@android:color/white"
    app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

fragment_item_three.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:weightSum="1">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/searchGroup"
        android:scrollbarSize="10dp"/>

    <android.support.design.widget.BottomNavigationView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/NavGroup"
        android:layout_gravity="bottom"
        app:menu="@menu/menu_group"
        android:background="@color/Lime"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

    <FrameLayout
        android:id="@+id/groupFrame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:animateLayoutChanges="true"
        android:layout_below="@+id/bottomNavigationView">
    </FrameLayout>

</LinearLayout>

fragment_group_one.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupOne">

<TextView
    android:text="Hay salamat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView3" />

fragment_group_two.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupTwo">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hay Humana" />

Body:
This is the answer to my question

 private void findViews(View view)
{
    bottomNavigationView = (BottomNavigationView)view.findViewById(R.id.NavGroup);
    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

                }
            });
}

then add in the onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_three, container, false);
    findViews(view);
    return view;

}


问:
Laravel Route, ->name method?
Laravel 5.5
which is the different doing (no get and post methods) on route defintion web.php file:

```<code>$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
</code>```

regarding ->name('') method

Is required define that method? in which cases?

(sample taked from Auth Class definition laravel)

答:
The idea of defining ->name() in routes is for easier code maintenance in the future, it's not mandatory.

Say for example you have few places which uses the route login, one fine day you update the route to user-login. You will have to find and update all the route being used, changing from url('login') to url('user-login').

If you have a route name defined, you will be using route('login'), when you update your route url, there's no need to update all the other files that you're using that route.

Title: Laravel Route, ->name method?

Body:
Laravel 5.5
which is the different doing (no get and post methods) on route defintion web.php file:

$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');

regarding ->name('') method

Is required define that method? in which cases?

(sample taked from Auth Class definition laravel)


问:
Static resources in Spring not working. Any ideas?

Situation:

I have a fresh spring project from start.spring.io

And I have created the file project/src/main/resources/js/a.js

I have created also project/src/main/resources/templates/index.html (it's with thymeleaf)
that needs that a.js by

I also have the following configuration:

```<code>@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/js/**")
                .addResourceLocations("/js/");

    }
}
</code>```

When the app is starting I can see in the logs:

Mapped URL path [/js/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Tried:

At the  .addResourceLocations(); I have tried all kind of variants like:
"/resources/js", "resources/js", "/js", "js"

Also in application.properties used spring.resources.static-locations=classpath:/resources/

create /resources/static/js/a.js and update the addResourceLocatios parameter accordingly

Any ideas?

答:
You will need to place a.js file inside static folder. I have attached folder structure below:

Also remove your MvcConfig since it is not required.

Body:
Situation:

I have a fresh spring project from start.spring.io

And I have created the file project/src/main/resources/js/a.js

I have created also project/src/main/resources/templates/index.html (it's with thymeleaf)
that needs that a.js by

I also have the following configuration:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/js/**")
                .addResourceLocations("/js/");

    }
}

When the app is starting I can see in the logs:

Mapped URL path [/js/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Tried:

At the  .addResourceLocations(); I have tried all kind of variants like:
"/resources/js", "resources/js", "/js", "js"

Also in application.properties used spring.resources.static-locations=classpath:/resources/

create /resources/static/js/a.js and update the addResourceLocatios parameter accordingly

Any ideas?


问:
Unable to install rdkafka on Ubuntu 16.04
I want to install rdkafka

Upon running the command as per the instructions: sudo pecl install rdkafka

I have installed pecl using the command:

```<code>sudo apt-get install php-pear php-dev
</code>```

答:
Before doing that install librdkafka . linux command  sudo apt-get install librdkafka . After that try the same command as you mentioned using pecl. Hope it should work.

For more detail use this link: https://arnaud-lb.github.io/php-rdkafka/phpdoc/book.rdkafka.html

Body:
I want to install rdkafka

Upon running the command as per the instructions: sudo pecl install rdkafka

I have installed pecl using the command:

sudo apt-get install php-pear php-dev


问:
How do I rename a file using VBScript?
I am trying to rename a file and was using the below code but it does not seem to work. Can someone please tell me why? What is the correct way to rename a file from VBScript?

```<code>FSO.GetFile("MyFile.txt).Name = "Hello.txt"
</code>```

I am using this thread for reference: Rename files without copying in same folder

答:
Yes you can do that.

Here I am renaming a .exe file to .txt file

rename a file

```<code>Dim objFso
Set objFso= CreateObject("Scripting.FileSystemObject")
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"
</code>```

Title: How do I rename a file using VBScript?

Body:
I am trying to rename a file and was using the below code but it does not seem to work. Can someone please tell me why? What is the correct way to rename a file from VBScript?

FSO.GetFile("MyFile.txt).Name = "Hello.txt"

I am using this thread for reference: Rename files without copying in same folder

Body:
Yes you can do that.

Here I am renaming a .exe file to .txt file

rename a file

Dim objFso
Set objFso= CreateObject("Scripting.FileSystemObject")
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"