问:
Passing a Variable from one JS function to another function
I'm using ajax to fetch my data based on some select tags. When I select body part it send a request to sub_parts_ajax() function and does it work perfect and when I select disease type from another select tag which links to disease_name_ajax() where I want the id of last selected in the sub_parts_ajax()

Here is my code:

```<code>    <script type="text/javascript">

 function sub_parts_ajax(id){

    var VAR = {
        myvalue: id
     };

        $.ajax({

            url: 'fetching_parts',
            data: 'id='+id,
            success:function(res){
                //alert(res);
                $("#sub_part").empty();
                $.each(res,function(key,value){
                    $("#sub_part").append('<option value="'+key+'">'+value+'</option>');
                });
            }
        });
    }
</code>```

Second Function

```<code>  function disease_name_ajax(typeid){
</code>```

here I want to alert the value named: myvalue

```<code>alert(VAR.myvalue);

        $.ajax({

            url: 'fetching_names',
            data: 'typeid='+typeid,
            success:function(res){
                //alert(res);
                $("#disease_name").empty();
                $.each(res,function(key,value){
                    $("#disease_name").append('<option value="'+key+'">'+value+'</option>');
                });
            }
        });
    }

</script>
</code>```

答:
Either you store the object as a global variable which can be accessed and modified from any function (Not recommended)

Or

You save the value in this case as JSON to a custom hidden input in the DOM which also can accessed from any function.

```<code><input type="hidden" id="argVal"/>
 var VAR = { myvalue : id };
 var argJSON = JSON.stringify(VAR);
 $("#argVal").val(argJSON);
</code>```

To retrieve the value from any function

```<code> var val = JSON.parse($("#argVal").val());
</code>```

Body:
Either you store the object as a global variable which can be accessed and modified from any function (Not recommended)

Or

You save the value in this case as JSON to a custom hidden input in the DOM which also can accessed from any function.

<input type="hidden" id="argVal"/>
 var VAR = { myvalue : id };
 var argJSON = JSON.stringify(VAR);
 $("#argVal").val(argJSON);

To retrieve the value from any function

 var val = JSON.parse($("#argVal").val());


来源: stackexchange

问:
How to use vector of vector for reading a graph?
```<code>#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);

int main()
{

    vector<vector<int> > adj(4);
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< i+1 << " , " << cout<< adj[i][j]<<endl;
        }
    }
}
</code>```

I have written the code for reading the graph and printing it.

Prior to this for reading graph I used to use

```<code>vector<int>adj[5];
</code>```

But I have been told that , use

```<code>`vector<vector<int> > adj`  or `list<list<int> > adj`
</code>```

I tried but now I am getting No output.    ( update)

Can anyone help me in using vector of vector ?? Please help for list of list also.

答:
To use a vector of vectors you could write

```<code>std::vector<std::vector<int>> adj(5); // Note: round parentheses
</code>```

This works because standard vectors have a constructor that accepts the requested size as parameter and default-initializes all elements.

Being adj a vector of vectors the elements of adj will be initialized as empty vectors, that you can later fill with push_back.

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);

int main()
{

    vector<vector<int> > adj(4);
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< i+1 << " , " << cout<< adj[i][j]<<endl;
        }
    }
}

I have written the code for reading the graph and printing it.

Prior to this for reading graph I used to use

vector<int>adj[5];

But I have been told that , use

`vector<vector<int> > adj`  or `list<list<int> > adj`

I tried but now I am getting No output.    ( update)

Can anyone help me in using vector of vector ?? Please help for list of list also.

Body:
To use a vector of vectors you could write

std::vector<std::vector<int>> adj(5); // Note: round parentheses

This works because standard vectors have a constructor that accepts the requested size as parameter and default-initializes all elements.

Being adj a vector of vectors the elements of adj will be initialized as empty vectors, that you can later fill with push_back.


问:
All divs has background blue.When I click on any div , background color has to change to red for only that div clicked & not others
But when you click on any one of div, the other divs remains blue and the clicked div has to changed to red only.How we implement using jquery ?

.blue {
    background:blue;
    width:100px;
    height:100px;
    display:inline-block;
    float:left;
    margin-right:20px;
}
```

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<body>
  <div id="test1" class="blue"></div>
  <div id="test2" class="blue"></div>
  <div id="test3" class="blue"></div>
</body>
</html>
</code>```

答:
by using this keyword change the background color the current div</p>

```<code>$(".blue").on("click", function() {
$(".blue").css("background-color","blue");
$(this).css("background-color","red");
});
</code>```

Body:
But when you click on any one of div, the other divs remains blue and the clicked div has to changed to red only.How we implement using jquery ?

.blue {
    background:blue;
    width:100px;
    height:100px;
    display:inline-block;
    float:left;
    margin-right:20px;
}

<!doctype html>

Body:
by using this keyword change the background color the current div

$(".blue").on("click", function() {
$(".blue").css("background-color","blue");
$(this).css("background-color","red");
});


问:
How to render formatted post content in widget in Wordpress
I am new on wordpress and try to make a widget which will only show the last post of particuler category.

TO do this I have given some settings in admin to select category for which admin wants to display last post (post of last ID).

I am using the below code to in widget to display post content:

```<code>$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    echo $post->post_content;
}
</code>```

But the above code is showing content in one paragraph or you can say that without format. I have done lot of search and found that, I need to apply  "the_content" filter to format the content. So I have done the same as below code:

```<code>if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    $content = apply_filters('the_content', $post->post_content);
    echo $content;
}
</code>```

Now the above changes is returning the null string. I have google lot of things but everyone is saying that to use apply filter or use the_content() function. I have tried both solutions but nothing happening.

Can anyone please share the solution for this problem?

答:
All you need to do is,</p>

```<code>$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
while ($posts_query->have_posts()) {
    $posts_query->the_post();
    echo get_the_content();
}
</code>```

Body:
I am new on wordpress and try to make a widget which will only show the last post of particuler category.

TO do this I have given some settings in admin to select category for which admin wants to display last post (post of last ID).

I am using the below code to in widget to display post content:

$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    echo $post->post_content;
}

But the above code is showing content in one paragraph or you can say that without format. I have done lot of search and found that, I need to apply  "the_content" filter to format the content. So I have done the same as below code:

if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    $content = apply_filters('the_content', $post->post_content);
    echo $content;
}

Now the above changes is returning the null string. I have google lot of things but everyone is saying that to use apply filter or use the_content() function. I have tried both solutions but nothing happening.

Can anyone please share the solution for this problem?

Body:
All you need to do is,

$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
while ($posts_query->have_posts()) {
    $posts_query->the_post();
    echo get_the_content();
}


问:
Image not inserting in folder using PHP and MYSQL

Iam trying to insert image in folder using php and mysql but the image is not storing in folder as well as in database
  This is my PHP Code

```<code> if(isset($name)) {
$pass = base64_encode($pass);
$cpass = base64_encode($cpass);
$image_name = $_FILES['image']['name'];
$image_temp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image_type == 'image/png' || $image_type == 'image/jpg' || $image_type == 'image/iso' || $image_type = 'image/gif') {
    $upload = move_uploaded_file('uploads1/' . $_FILES['image']['name']);
      if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$image_name')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
  }
}
</code>```

This is my HTML code

```<code>      <form method="post" action="" enctype="multipart/form-data">
      <input type="text" name="name" placeholder="name" class="form-control" id="name"> <br>
      <input type="email" name="mail" placeholder="mailid@domain" class="form-control" id="mail"> <br>
      <input type="text" name="mobile" placeholder="Mobile" class="form-control" id="mobile"> <br>
      <input type="password" name="password" placeholder="password" class="form-control" id="password"> <br>
      <input type="password" name="cpassword" placeholder="confirm-password" class="form-control" id="cpassword"> <br>
      <input type="file" name="image" id="file" class="form-control" required> <br>
 </form>
</code>```

答:
```<code>just reviewed  your code i think the following code could work you please go through it and let me know if there is some issue..

<?php
 $con = mysqli_connect("localhost","root","","test");

if(isset($_POST['submit']))
{
        $pass = base64_encode($_POST['password']);
        $cpass = base64_encode($_POST['cpassword']);
        $name=$_POST['name'];
        $mail=$_POST['mail'];
        $cell=$_POST['mobile'];
       $image_name = $_FILES['image']['name'];
       $image_temp = $_FILES['image']['tmp_name'];
      $image_type = $_FILES['image']['type'];
       if ($image_type == 'image/png' || $image_type == 'image/jpg' ||                          $image_type == 'image/iso' || $image_type = 'image/gif')
    {
        $upload = move_uploaded_file($_FILES["image"]["tmp_name"],'uploads1/' . $_FILES['image']['name']);
        if($upload)
        {
           $reg_query = mysqli_query($con, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$image_name')");
           if ($reg_query) {
               echo 'success';
           } else {
               echo 'fail';
           }
        }
     }
}
?>
</code>```

Body:
Iam trying to insert image in folder using php and mysql but the image is not storing in folder as well as in database
  This is my PHP Code

 if(isset($name)) {
$pass = base64_encode($pass);
$cpass = base64_encode($cpass);
$image_name = $_FILES['image']['name'];
$image_temp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image_type == 'image/png' || $image_type == 'image/jpg' || $image_type == 'image/iso' || $image_type = 'image/gif') {
    $upload = move_uploaded_file('uploads1/' . $_FILES['image']['name']);
      if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$image_name')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
  }
}

This is my HTML code

      <form method="post" action="" enctype="multipart/form-data">
      <input type="text" name="name" placeholder="name" class="form-control" id="name">

      <input type="email" name="mail" placeholder="mailid@domain" class="form-control" id="mail">

      <input type="text" name="mobile" placeholder="Mobile" class="form-control" id="mobile">

      <input type="password" name="password" placeholder="password" class="form-control" id="password">

      <input type="password" name="cpassword" placeholder="confirm-password" class="form-control" id="cpassword">

      <input type="file" name="image" id="file" class="form-control" required>

 </form>


问:
Angular routing error: should only include this file once
I am playing with tutorial Tour of Heroes found here. Everything runs and looks fine. However, after I added routing from root page to dashboard and to hero's detail, I got the following error in the console:

```<code>Unexpected condition on http://localhost:3000/dashboard: should only include this file once
</code>```

The error is seen after I click in the link to Dashboard.
The message is thrown from that line of code:

```<code>expect(!loadTimeData, 'should only include this file once');
</code>```

in VM1812:155. JS version is V8 5.6.326.50. Version of Angular I am using is 4.0.0, as declared in package.json:

```<code>"dependencies": {
  "@angular/common": "~4.0.0",
  "@angular/compiler": "~4.0.0",
  "@angular/core": "~4.0.0",
  ...
}
</code>```

dashboard.component.ts

```<code>import { Component, OnInit  } from '@angular/core';

import { Hero } from '../heroes/hero';
import { HeroService } from '../model/hero.service';

@Component ({
  selector: 'my-dashboard',
  templateUrl: './html/dashboard.component.html',
  styleUrls: ['./css/app.css'],
})

export class DashboardComponent implements OnInit {

  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));
  }
}
</code>```

The /dashboard page is linked in app.component template, like that:

```<code><nav>
  <a routerLink="/heroes">Heroes</a><!--another page, also problematic-->
  <a routerLink="/dashboard">Dashboard</a>
</nav>
<router-outlet></router-outlet>
</code>```

and route definition is defined in a module like that:

```<code>@NgModule({
  imports: [ RouterModule.forRoot(
    [
      { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
      { path: 'dashboard',  component: DashboardComponent },
    ]
  ) ],
  //...
})
</code>```

Anyone knows what this error means and why it pops up?

答:
I checked with every browser and seems it applies only to Yandex browser. From my perspective, that bug needs to be sent to Yandex Support team. However, it doesn't affect end-user experience or any functionally. We can safely ignore it for now.

PS - angular application isn't working on old safari (5.1.7), use the latest one(9-10) which is available only on MacOS or any other modern browser.

Body:
I am playing with tutorial Tour of Heroes found here. Everything runs and looks fine. However, after I added routing from root page to dashboard and to hero's detail, I got the following error in the console:

Unexpected condition on http://localhost:3000/dashboard: should only include this file once

The error is seen after I click in the link to Dashboard.
The message is thrown from that line of code:

expect(!loadTimeData, 'should only include this file once');

in VM1812:155. JS version is V8 5.6.326.50. Version of Angular I am using is 4.0.0, as declared in package.json:

"dependencies": {
  "@angular/common": "~4.0.0",
  "@angular/compiler": "~4.0.0",
  "@angular/core": "~4.0.0",
  ...
}

dashboard.component.ts

import { Component, OnInit  } from '@angular/core';

import { Hero } from '../heroes/hero';
import { HeroService } from '../model/hero.service';

@Component ({
  selector: 'my-dashboard',
  templateUrl: './html/dashboard.component.html',
  styleUrls: ['./css/app.css'],
})

export class DashboardComponent implements OnInit {

  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));
  }
}

The /dashboard page is linked in app.component template, like that:

  Heroes
  Dashboard

<router-outlet></router-outlet>

and route definition is defined in a module like that:

@NgModule({
  imports: [ RouterModule.forRoot(
    [
      { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
      { path: 'dashboard',  component: DashboardComponent },
    ]
  ) ],
  //...
})

Anyone knows what this error means and why it pops up?


问:
How to learn to write idiomatic c++ code
I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

答:
You might wnat to check out The Definitive C++ Book Guide and List

For your purposes I would especially recommend:

C++ Coding Standards

Effective STL

Beyond the C++ Standard Library: An Introduction to Boost

Code Complete

Clean Code (Examples in Java, still valid though.)

They are not in particular order, also you might want to read and code something in between them.

(Note: As noted by @John Dibling the Boost book might be a bit out of date, I do not have experience with that one myself)

ContentLicense: CC BY-SA 2.5


问:
how to implement modal by using bootstrap?
I am using modal concept of bootstrap in my html file. In modal i am entering data after clicking on save this data should be displayed in  html page where modal is called. By using which function i can include or display this data in html page.

答:
Here's a working Plunker for your reference

The basic idea is that you can pass an object from a modal back to the controller which opens the modal with close() as follows

```<code>$uibModalInstance.close($ctrl.modal);
</code>```

Then in the parent controller, you can obtain the object as follows

```<code>modalInstance.result.then(function(modal) {
  $ctrl.modal = modal;
}, function () {
  $log.info('Modal dismissed at: ' + new Date());
});
</code>```

Body:
Here's a working Plunker for your reference

The basic idea is that you can pass an object from a modal back to the controller which opens the modal with close() as follows

$uibModalInstance.close($ctrl.modal);

Then in the parent controller, you can obtain the object as follows

modalInstance.result.then(function(modal) {
  $ctrl.modal = modal;
}, function () {
  $log.info('Modal dismissed at: ' + new Date());
});


问:
How to control gif in a webpage?
I embedded a gif like this:

```<code><img src="myimage.gif">
</code>```

This plays when the page is loaded. I want to be able to have a start and stop or pause functionality for the image. The gif should toggle start and stop on click.

How can I achieve this?
Many Thanks.

答:
```<code><script type="text/javascript" src="./libgif.js"></script>
<img src="./example1_preview.gif" rel:animated_src="./example1.gif"
 width="360" height="360" rel:auto_play="1" rel:rubbable="1" />

<script type="text/javascript">
    $$('img').each(function (img_tag) {
        if (/.*\.gif/.test(img_tag.src)) {
            var rub = new SuperGif({ gif: img_tag } );
            rub.load(function(){
                console.log('oh hey, now the gif is loaded');
            });
        }
    });
</script>
</code>```

You use java script code to control Gif

Title: How to control gif in a webpage?

Body:
I embedded a gif like this:

This plays when the page is loaded. I want to be able to have a start and stop or pause functionality for the image. The gif should toggle start and stop on click.

How can I achieve this?
Many Thanks.

Body:
<script type="text/javascript" src="./libgif.js"></script>
<img src="./example1_preview.gif" rel:animated_src="./example1.gif"
 width="360" height="360" rel:auto_play="1" rel:rubbable="1" />

<script type="text/javascript">
    $$('img').each(function (img_tag) {
        if (/.*\.gif/.test(img_tag.src)) {
            var rub = new SuperGif({ gif: img_tag } );
            rub.load(function(){
                console.log('oh hey, now the gif is loaded');
            });
        }
    });
</script>

You use java script code to control Gif


答:
Is it index of character in my String or sth else? What 1833 mean?

It's a byte offset in the data.

In your case, bytes in data converted from your string:

```<code>+1829: f0
+1830: 9f
+1831: 99
+1832: 83
+1833: 0a <-
+1834: 0a
+1835: 57
+1836: 79
+1837: 72
</code>```

(Offsets shown in decimal, each byte in hexadecimal.)

It's around here in your String: Aaaaaaaaaaaa\n\nWyrazil. (Precisely, the 9 bytes above represent \n\nWyr.)

As Swift Optional outputs its content in a debugging form, \n represents a single control character U+000A, which is not valid in JSON string.

I don't see how you get that String, so I cannot show in code, but you need to fix the part which is generating such invalid JSON. Control characters in JSON string need to be escaped.

ContentLicense: CC BY-SA 4.0

Title: Unescaped control character around character 1833

Body:
Is it index of character in my String or sth else? What 1833 mean?

It's a byte offset in the data.

In your case, bytes in data converted from your string:

+1829: f0
+1830: 9f
+1831: 99
+1832: 83
+1833: 0a <-
+1834: 0a
+1835: 57
+1836: 79
+1837: 72

(Offsets shown in decimal, each byte in hexadecimal.)

It's around here in your String: Aaaaaaaaaaaa\n\nWyrazil. (Precisely, the 9 bytes above represent \n\nWyr.)

As Swift Optional outputs its content in a debugging form, \n represents a single control character U+000A, which is not valid in JSON string.

I don't see how you get that String, so I cannot show in code, but you need to fix the part which is generating such invalid JSON. Control characters in JSON string need to be escaped.


问:
Items are not the same width when using RecyclerView GridLayoutManager to make column spacing by ItemDecoration
I'm trying to use RecyclerView and GridLayoutManager to make a 3 columns grid, and I use ItemDecoration to make column spacing, now the problem is the item's width in third column is smaller than the item in first and second column! See the screen capture below.

If I don't add the custom ItemDecoration to RecyclerView, everything is OK.

Here is my code:

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;

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

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);

        int horizontalSpacing = 20;
        int verticalSpacing = 10;
        SpacingDecoration decoration = new SpacingDecoration(horizontalSpacing, verticalSpacing, true);
        mRecyclerView.addItemDecoration(decoration);
    }

    private static class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private int[] mColors = new int[]{Color.RED, Color.BLUE, Color.MAGENTA};

        private static class ItemHolder extends RecyclerView.ViewHolder {

            public MyTextView title;

            public ItemHolder(View itemView) {
                super(itemView);
                title = (MyTextView) itemView.findViewById(android.R.id.text1);
                title.setTextColor(Color.WHITE);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            ItemHolder holder = new ItemHolder(itemView);
            holder.itemView.setOnClickListener(itemClickListener);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder rHolder, int position) {
            ItemHolder holder = (ItemHolder) rHolder;

            holder.title.setText(String.format("[%d]width:%d", position, holder.itemView.getWidth()));
            holder.itemView.setBackgroundColor(mColors[position % mColors.length]);
            holder.itemView.setTag(position);
            holder.title.setTag(position);
        }

        @Override
        public int getItemCount() {
            return 50;
        }

        private View.OnClickListener itemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                showText(v.getContext(), String.format("[%d]->width:%d", position, v.getWidth()));
            }
        };

    }

    public static class SpacingDecoration extends RecyclerView.ItemDecoration {

        private int mHorizontalSpacing = 5;
        private int mVerticalSpacing = 5;
        private boolean isSetMargin = true;

        public SpacingDecoration(int hSpacing, int vSpacing, boolean setMargin) {
            isSetMargin = setMargin;
            mHorizontalSpacing = hSpacing;
            mVerticalSpacing = vSpacing;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            boolean isSetMarginLeftAndRight = this.isSetMargin;
            int bottomOffset = mVerticalSpacing;
            int leftOffset = 0;
            int rightOffset = 0;

            RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams();
            if (parent.getLayoutManager() instanceof GridLayoutManager) {
                GridLayoutManager lm = (GridLayoutManager) parent.getLayoutManager();
                GridLayoutManager.LayoutParams gridLp = (GridLayoutManager.LayoutParams) lp;

                if (gridLp.getSpanSize() == lm.getSpanCount()) {
                    // Current item is occupied the whole row
                    // We just need to care about margin left and right now
                    if (isSetMarginLeftAndRight) {
                        leftOffset = mHorizontalSpacing;
                        rightOffset = mHorizontalSpacing;
                    }
                } else {
                    // Current item isn't occupied the whole row
                    if (gridLp.getSpanIndex() > 0) {
                        // Set space between items in one row
                        leftOffset = mHorizontalSpacing;
                    } else if (gridLp.getSpanIndex() == 0 && isSetMarginLeftAndRight) {
                        // Set left margin of a row
                        leftOffset = mHorizontalSpacing;
                    }
                    if (gridLp.getSpanIndex() == lm.getSpanCount() - gridLp.getSpanSize() && isSetMarginLeftAndRight) {
                        // Set right margin of a row
                        rightOffset = mHorizontalSpacing;
                    }
                }
            }
            outRect.set(leftOffset, 0, rightOffset, bottomOffset);
        }
    }

    private static Toast sToast;

    public static void showText(Context context, String text) {
        if (sToast != null) {
            sToast.cancel();
        }
        sToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        sToast.show();
    }
}
</code>```

activity_main.xml

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>
</code>```

item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <com.example.liuqing.rvgldemo.MyTextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:textColor="#ffffff"
        android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
</code>```

MyTextView.java

```<code>public class MyTextView extends TextView {

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

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

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

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus) {
            setText("[" + getTag() + "]width:" + getWidth());
        }
    }
}
</code>```

It will be much appreciate if someone can explain this problem.

答:
I've wrote a more robust ItemDecoration based on @AvatarQing 's answer: SCommonItemDecoration

You can set same vertical or horizontal space between items, besides you can set different space to different type of items.

Body:
I'm trying to use RecyclerView and GridLayoutManager to make a 3 columns grid, and I use ItemDecoration to make column spacing, now the problem is the item's width in third column is smaller than the item in first and second column! See the screen capture below.

If I don't add the custom ItemDecoration to RecyclerView, everything is OK.

Here is my code:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;

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

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);

        int horizontalSpacing = 20;
        int verticalSpacing = 10;
        SpacingDecoration decoration = new SpacingDecoration(horizontalSpacing, verticalSpacing, true);
        mRecyclerView.addItemDecoration(decoration);
    }

    private static class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private int[] mColors = new int[]{Color.RED, Color.BLUE, Color.MAGENTA};

        private static class ItemHolder extends RecyclerView.ViewHolder {

            public MyTextView title;

            public ItemHolder(View itemView) {
                super(itemView);
                title = (MyTextView) itemView.findViewById(android.R.id.text1);
                title.setTextColor(Color.WHITE);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            ItemHolder holder = new ItemHolder(itemView);
            holder.itemView.setOnClickListener(itemClickListener);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder rHolder, int position) {
            ItemHolder holder = (ItemHolder) rHolder;

            holder.title.setText(String.format("[%d]width:%d", position, holder.itemView.getWidth()));
            holder.itemView.setBackgroundColor(mColors[position % mColors.length]);
            holder.itemView.setTag(position);
            holder.title.setTag(position);
        }

        @Override
        public int getItemCount() {
            return 50;
        }

        private View.OnClickListener itemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                showText(v.getContext(), String.format("[%d]->width:%d", position, v.getWidth()));
            }
        };

    }

    public static class SpacingDecoration extends RecyclerView.ItemDecoration {

        private int mHorizontalSpacing = 5;
        private int mVerticalSpacing = 5;
        private boolean isSetMargin = true;

        public SpacingDecoration(int hSpacing, int vSpacing, boolean setMargin) {
            isSetMargin = setMargin;
            mHorizontalSpacing = hSpacing;
            mVerticalSpacing = vSpacing;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            boolean isSetMarginLeftAndRight = this.isSetMargin;
            int bottomOffset = mVerticalSpacing;
            int leftOffset = 0;
            int rightOffset = 0;

            RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams();
            if (parent.getLayoutManager() instanceof GridLayoutManager) {
                GridLayoutManager lm = (GridLayoutManager) parent.getLayoutManager();
                GridLayoutManager.LayoutParams gridLp = (GridLayoutManager.LayoutParams) lp;

                if (gridLp.getSpanSize() == lm.getSpanCount()) {
                    // Current item is occupied the whole row
                    // We just need to care about margin left and right now
                    if (isSetMarginLeftAndRight) {
                        leftOffset = mHorizontalSpacing;
                        rightOffset = mHorizontalSpacing;
                    }
                } else {
                    // Current item isn't occupied the whole row
                    if (gridLp.getSpanIndex() > 0) {
                        // Set space between items in one row
                        leftOffset = mHorizontalSpacing;
                    } else if (gridLp.getSpanIndex() == 0 && isSetMarginLeftAndRight) {
                        // Set left margin of a row
                        leftOffset = mHorizontalSpacing;
                    }
                    if (gridLp.getSpanIndex() == lm.getSpanCount() - gridLp.getSpanSize() && isSetMarginLeftAndRight) {
                        // Set right margin of a row
                        rightOffset = mHorizontalSpacing;
                    }
                }
            }
            outRect.set(leftOffset, 0, rightOffset, bottomOffset);
        }
    }

    private static Toast sToast;

    public static void showText(Context context, String text) {
        if (sToast != null) {
            sToast.cancel();
        }
        sToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        sToast.show();
    }
}

activity_main.xml

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <com.example.liuqing.rvgldemo.MyTextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:textColor="#ffffff"
        android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>

MyTextView.java

public class MyTextView extends TextView {

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

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

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

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus) {
            setText("[" + getTag() + "]width:" + getWidth());
        }
    }
}

It will be much appreciate if someone can explain this problem.


问:
Change cssclass of button inside datalist using jquery in asp.net
I have a button inside datalist, if I click one button have to change the css of other button in jquery.

I have more images in my page. my code accept only one "like".
I want to differentiate which one I selected.

jquery

```<code>function Addlike(btnlike, hdnId, term, cId) {
    $.ajax({
        type: "POST",
        url: "CommonFunction.aspx/SaveToLike",
        data: '{user: ' + JSON.stringify(user) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            $(btnlike).attr("class", "btn btn-success");
            //  alert("Data added successfully.");

        },
        error: function (response) {
            alert("Unexpected error occurred.");
        }
    });
    return false;
}
</code>```

aspx code

```<code><asp:DataList ID="dtlist" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dtlist_OnItemDataBound">
    <ItemTemplate>
        <asp:LinkButton ID="btnlike" runat="server" CommandArgument='<%# Eval("Id") %>'><i class="fa fa-users"></i></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>
</code>```

I just want to change other buttons cssclass. how to find the control?

答:
You can find control ID Using Jquery in following manner.

```<code>$('#<%= dtlist.FindControl("btnlike").ClientID %>')
</code>```

Hope it helps.

Body:
I have a button inside datalist, if I click one button have to change the css of other button in jquery.

I have more images in my page. my code accept only one "like".
I want to differentiate which one I selected.

jquery

function Addlike(btnlike, hdnId, term, cId) {
    $.ajax({
        type: "POST",
        url: "CommonFunction.aspx/SaveToLike",
        data: '{user: ' + JSON.stringify(user) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            $(btnlike).attr("class", "btn btn-success");
            //  alert("Data added successfully.");

        },
        error: function (response) {
            alert("Unexpected error occurred.");
        }
    });
    return false;
}

aspx code

<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dtlist_OnItemDataBound">
    <ItemTemplate>
        <asp:LinkButton ID="btnlike" runat="server" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>

I just want to change other buttons cssclass. how to find the control?

Body:
You can find control ID Using Jquery in following manner.

$('#<%= dtlist.FindControl("btnlike").ClientID %>')

Hope it helps.


问:
How can I find out if the gradle daemon is running?
I am developing Android applications with Android Studio 2.0. I read in a lot of blogposts that enabling the gradle daemon should increase the build performance drastically.

My problem is, that I do not know how to check if the daemon is running. I added the line

```<code>org.gradle.daemon=true
</code>```

to the gradle.properties file but Android Studio shows me a unused property warning, so I am not sure if the daemon is actually running. How can I find out if the daemon is actually running?

答:
Long time passed since the question is asked, but I see no exact answer to the question:

How can I find out if the gradle daemon is running?

Running in terminal gradle --status will give the status of the gradle. You'll see "No Gradle daemons are running" message if there's no gradle daemon running.

Otherwise, you'll see status of the daemon.

Body:
I am developing Android applications with Android Studio 2.0. I read in a lot of blogposts that enabling the gradle daemon should increase the build performance drastically.

My problem is, that I do not know how to check if the daemon is running. I added the line

org.gradle.daemon=true

to the gradle.properties file but Android Studio shows me a unused property warning, so I am not sure if the daemon is actually running. How can I find out if the daemon is actually running?


问:
Bezier clipping
I'm trying to find/make an algorithm to compute the intersection (a new filled object) of two arbitrary filled 2D objects. The objects are defined using either lines or cubic beziers and may have holes or self-intersect. I'm aware of several existing algorithms doing the same with polygons, listed here. However, I'd like to support beziers without subdividing them into polygons, and the output should have roughly the same control points as the input in areas where there are no intersections.

This is for an interactive program to do some CSG but the clipping doesn't need to be real-time. I've searched for a while but haven't found good starting points.

答:
I wrote code to do this a long, long time ago.  The project I was working on defined 2D objects using piecewise Bezier boundaries that were generated as PostScipt paths.

The approach I used was:

Let curves p, q, be defined by Bezier control points.  Do they intersect?

Compute the bounding boxes of the control points.  If they don't overlap, then the two curves don't intersect.  Otherwise:

p.x(t), p.y(t), q.x(u), q.y(u) are cubic polynomials on 0 <= t,u <= 1.0.
The distance squared (p.x - q.x) ** 2 + (p.y - q.y) ** 2 is a polynomial on (t,u).
Use Newton-Raphson to try and solve that for zero.  Discard any solutions outside 0 <= t,u <= 1.0

N-R may or may not converge.  The curves might not intersect, or N-R can just blow up when the two curves are nearly parallel.  So cut off N-R if it's not converging after after some arbitrary number of  iterations.  This can be a fairly small number.

If N-R doesn't converge on a solution, split one curve (say, p) into two curves pa, pb at t = 0.5.  This is easy, it's just computing midpoints, as the linked article shows.  Then recursively test (q, pa) and (q, pb) for intersections.  (Note that in the next layer of recursion that q has become p, so that p and q are alternately split on each ply of the recursion.)

Most of the recursive calls return quickly because the bounding boxes are non-overlapping.

You will have to cut off the recursion at some arbitrary depth, to handle weird cases where the two curves are parallel and don't quite touch, but the distance between them is arbitrarily small -- perhaps only 1 ULP of difference.

When you do find an intersection, you're not done, because cubic curves can have multiple crossings.  So you have to split each curve at the intersecting point, and recursively check for more interections between (pa, qa), (pa, qb), (pb, qa), (pb, qb).

OwnerDisplayName: jjrv

Title: Bezier clipping

LastEditorDisplayName: Nils

OwnerDisplayName: Die in Sente


问:
Multiple Converters/Generators in Jekyll?
I would like to write a Jekyll plugin that makes all posts available in PDF format by utilizing Kramdown's LaTeX export capabilities.  For each post in Markdown format, I'd like to end up with the normal .html post along with a .tex file containing the LaTeX markup and finally a .pdf.

Following the documentation for creating plugins, I see two ways of approaching the problem, either with a Converter or with a Generator.

Converter plugins seem to run after the built-in Converters, so the .markdown files have all been converted to .html by the time they reach the Converter.

When I try to implement a Generator, I am able to use fileutils to write a file successfully, but by the end of Jekyll's cycle, that file has been removed.  It seems there's a StaticFile class which you can use to register new output files with Jekyll, but I cannot find any real guidance on how to use it.

答:
I try to do the same but with direct html->pdf conversion.
It did not work inside a gitlab-ci pipeline at this time, nonetheless it work on my workstation (see here) with a third possibility : a hook !

(here with pdfkit)

```<code>require 'pdfkit'

module Jekyll

  Jekyll::Hooks.register :site, :post_write do |post|

      post.posts.docs.each do |post|
          filename = post.site.dest + post.id + ".pdf"
          dirname = File.dirname(filename)
          Dir.mkdir(dirname) unless File.exists?(dirname)

          kit = PDFKit.new(post.content, :page_size => 'Letter')
          kit.stylesheets << './css/bootstrap.min.css'
          kit.to_file(filename)
      end
  end

end
</code>```

Body:
I try to do the same but with direct html->pdf conversion.
It did not work inside a gitlab-ci pipeline at this time, nonetheless it work on my workstation (see here) with a third possibility : a hook !

(here with pdfkit)

require 'pdfkit'

module Jekyll

  Jekyll::Hooks.register :site, :post_write do |post|

      post.posts.docs.each do |post|
          filename = post.site.dest + post.id + ".pdf"
          dirname = File.dirname(filename)
          Dir.mkdir(dirname) unless File.exists?(dirname)

          kit = PDFKit.new(post.content, :page_size => 'Letter')
          kit.stylesheets << './css/bootstrap.min.css'
          kit.to_file(filename)
      end
  end

end


问:
how can smallest floating point number be 2^(-126) , not 2^(-128)
Consider a 32 bit floating point number (IEEE 754) having 0-22 for mantissa(23 bits) , 23-30 for exponent(8 bits) , 31 for sign(1bit)

I want to find out the smallest positive number that can be stored.

I have been told answer is 1.18*10-38 which is approx 2-126

My analysis is as follows

if we put all zeroes in mantissa and put all ones in exponent then the decimal equivalent would be
 1.0 x 2-128 = 2.93 x 10-39

Where am I going wrong ?

Thanks

答: If you put all ones in exponent you will get NaN if mantissa is non-zero or infinite if mantissa is 0. Wikipedia IEEE 754. Also your minimal value is inside Denormal numbers space when exponent is binary equal to 0.


问:
How to configure IIS 8.5 to work with Asp.Net UpdatePanel?
I've created an Asp.Net Web forms project and using an UpdatePanel to prevent page postback. The update panel is working fine in local testing and also working fine in Windows Local IIS but when I deploy on Windows Server 2012 R2 IIS the page posts back and update panel don't work. I've also debug the HTML page and it shows the error

Sys is Undefined

I'm not able to know if it is the problem from server side or inside the project. Below is the configuration on System.Web and System.webServer in web.config.

```<code><system.web>
    <httpHandlers></httpHandlers>
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <handlers>
      <add name="Ajax" verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
    </handlers>
  </system.webServer>
</code>```

答: There was a problem with references of the ScripManager. I added the references from packages that were downloaded and it then worked.</p>

Body:
I've created an Asp.Net Web forms project and using an UpdatePanel to prevent page postback. The update panel is working fine in local testing and also working fine in Windows Local IIS but when I deploy on Windows Server 2012 R2 IIS the page posts back and update panel don't work. I've also debug the HTML page and it shows the error

Sys is Undefined

I'm not able to know if it is the problem from server side or inside the project. Below is the configuration on System.Web and System.webServer in web.config.

<system.web>
    <httpHandlers></httpHandlers>
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <handlers>
      <add name="Ajax" verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
    </handlers>
  </system.webServer>


答:
Use this.

$(".blue").on("click", function() {
   $(".blue").css("background", "blue")
   $(this).css("background", "red")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blue {
    background:blue;
    width:100px;
    height:100px;
    display:inline-block;
    float:left;
    margin-right:20px;
}</code>```

```

Title: All divs has background blue.When I click on any div , background color has to change to red for only that div clicked & not others

Body:
Use this.

$(".blue").on("click", function() {
   $(".blue").css("background", "blue")
   $(this).css("background", "red")
})

.blue {
    background:blue;
    width:100px;
    height:100px;
    display:inline-block;
    float:left;
    margin-right:20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1" class="blue"></div>
<div id="test2" class="blue"></div>
<div id="test3" class="blue"></div>


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
I think that the best background to learn Objective - C is C. If you know C, you'll easily become familiar with object-oriented programming and write in Objective - C.

Personally, I don't think learning Smalltalk us a good idea.


答:
Vectors use zero-based indexing. adj[0] is the first element in the vector.

Also vectors start with no size. There will be no adj[0] element until you add one.

You may want to adj.resize(4) before you try and call adj[u].push_back(v).

Title: How to use vector of vector for reading a graph?

Body:
#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);

int main()
{

    vector<vector<int> > adj(4);
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< i+1 << " , " << cout<< adj[i][j]<<endl;
        }
    }
}

I have written the code for reading the graph and printing it.

Prior to this for reading graph I used to use

vector<int>adj[5];

But I have been told that , use

`vector<vector<int> > adj`  or `list<list<int> > adj`

I tried but now I am getting No output.    ( update)

Can anyone help me in using vector of vector ?? Please help for list of list also.


问:
DLL containing ENUM is creating weird behaviour
Most of you guys will find this as dumb question, but need your genuine help here.

Problem:
I have created a separate project to define constants. I am using that project reference to other 300 projects(basically DLL).Everything was working fine since last week. Now I have changed my constant project to remove some ENUM values.

my code:

```<code>public enum KVP:int
[EnumMember(Value="1")]
KVP1,
[EnumMember(Value="2")]
KVP2,
[EnumMember(Value="3")]
KVP3,
//[EnumMember(Value="4")]
//KVP4,
[EnumMember(Value="5")]
KVP5
</code>```

I have removed KVP4 from the project and built a new DLL. I have tried to run the application,but with bad luck I got error related to KVP4 which I already removed.

point1: I've just built the constant DLL in which I've made changes.

point2: I haven't updated constant project reference to remaining 300 projects which is not practical,though.

I am getting confused here because If I update other constant values in the DLL(constant project), that works fine. Other Projects start taking the new values automatically which means all othe projects referencing the new updated DLL,but not in the case of ENUM.

Anyone having any suggestion or remedy to cop up with the issue?

EDIT:
there must be some difference between the word CONST and ENUM (to the one who requested closing this as duplicate).What should I use if I have to define constants then? A model class with props and static value??

答:
You should never do such things. You are breaking the system.

I haven't updated constant project reference to remaining 300 projects which is not practical,though

So, the value is still being used in those 300 projects.
You should try to compile them and see if they compile (they won't).

Instead of deleting the value, you can mark it as Obsolete with the [Obsolete] attribute.
And slowly start to change the other projects for not using it anymore. Only after you are absolutely 100% sure that no other code uses this value, you can remove it.

Body:
Most of you guys will find this as dumb question, but need your genuine help here.

Problem:
I have created a separate project to define constants. I am using that project reference to other 300 projects(basically DLL).Everything was working fine since last week. Now I have changed my constant project to remove some ENUM values.

my code:

public enum KVP:int
[EnumMember(Value="1")]
KVP1,
[EnumMember(Value="2")]
KVP2,
[EnumMember(Value="3")]
KVP3,
//[EnumMember(Value="4")]
//KVP4,
[EnumMember(Value="5")]
KVP5

I have removed KVP4 from the project and built a new DLL. I have tried to run the application,but with bad luck I got error related to KVP4 which I already removed.

point1: I've just built the constant DLL in which I've made changes.

point2: I haven't updated constant project reference to remaining 300 projects which is not practical,though.

I am getting confused here because If I update other constant values in the DLL(constant project), that works fine. Other Projects start taking the new values automatically which means all othe projects referencing the new updated DLL,but not in the case of ENUM.

Anyone having any suggestion or remedy to cop up with the issue?

EDIT:
there must be some difference between the word CONST and ENUM (to the one who requested closing this as duplicate).What should I use if I have to define constants then? A model class with props and static value??


问:
Get data by id wordpress

Problem

I have two different plugin tables and I want to get their value by sql. Problem is id where I cannot find connection which I can retrieve data.

Table 1 (bdt_mappress_posts)

postid = 2 and mapid = 3

Table 2 (bdt_mappress_maps)

mapid = 3 and obj = json

```<code><? $postid = get_the_ID();
$results = $GLOBALS['wpdb']->get_results( 'SELECT obj FROM bdt_mappress_maps INNER JOIN bdt_mappress_posts WHERE bdt_mappress_maps.mapid = bdt_mappress_posts AND   bdt_mappress_posts.postid ='.$postid); print_r($results);
 ?>
</code>```

$postid returns me id of the post. The sql returns me empty value, I know sql but not so strong. If someone can help me or give related post which I can find answer. Thanks beforehand!

答:
```<code><? $postid = get_the_ID();
$results = $GLOBALS['wpdb']->get_results( 'SELECT obj FROM bdt_mappress_posts INNER JOIN bdt_mappress_maps WHERE bdt_mappress_posts.mapid = bdt_mappress_maps.mapid AND   bdt_mappress_posts.postid ='.$postid); print_r($results);
?>
</code>```

Solve the problem

That should only changing the place the rule of the left sql

Title: Get data by id wordpress

Body:
Problem

I have two different plugin tables and I want to get their value by sql. Problem is id where I cannot find connection which I can retrieve data.

Table 1 (bdt_mappress_posts)

postid = 2 and mapid = 3

Table 2 (bdt_mappress_maps)

mapid = 3 and obj = json

<? $postid = get_the_ID();
$results = $GLOBALS['wpdb']->get_results( 'SELECT obj FROM bdt_mappress_maps INNER JOIN bdt_mappress_posts WHERE bdt_mappress_maps.mapid = bdt_mappress_posts AND   bdt_mappress_posts.postid ='.$postid); print_r($results);
 ?>

$postid returns me id of the post. The sql returns me empty value, I know sql but not so strong. If someone can help me or give related post which I can find answer. Thanks beforehand!

Body:
<? $postid = get_the_ID();
$results = $GLOBALS['wpdb']->get_results( 'SELECT obj FROM bdt_mappress_posts INNER JOIN bdt_mappress_maps WHERE bdt_mappress_posts.mapid = bdt_mappress_maps.mapid AND   bdt_mappress_posts.postid ='.$postid); print_r($results);
?>

Solve the problem

That should only changing the place the rule of the left sql


问:
What is the use of ("*") in jquery
I am reading jQuery, i don't know why use <code>("*")</code> please explain it's helpful </p>

```<code><script>
    $(document).ready(function(){
        $("button").click(function(){
            $("*").hide();
        });
    });
</script>
</code>```

答: $(*) is used to select all elements inside the document. Refer this: https://www.w3schools.com/jquery/sel_all.asp

Title: What is the use of ("*") in jquery

Body: I am reading jQuery, i don't know why use ("*") please explain it's helpful


问:
Tensorflow - ValueError: Parent directory of trained_variables.ckpt doesn't exist, can't save
I want to save my tensorflow session sess but i have the following error

ValueError: Parent directory of trained_variables.ckpt doesn't exist, can't save.

This is my line of code :

saver.save(sess, "trained_variables.ckpt")

I've also tried to change the file name and put model instead of trained_variables.ckpt but i get the same problem.

Following this tutorial A TensorFlow Tutorial: Email Classification

Body: saver.save(sess, "./trained_variables.ckpt")


问:
How to config Spring bean for prototype?
I wrote it as a singleton before, there were no errors.
But I think I should make it instance per request.
And I have the code

```<code><!--Dao configuration-->
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean" scope="request">
    <property name="mapperInterface" value="Dao.UserDao"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

package Test;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import Common.InitDataBases;
import Common.Controller.OutputStringController;
import Dao.UserDao;
import Model.User;
import java.util.List;

import org.apache.log4j.Logger;

@Controller
@Scope("request")
public class Hello extends OutputStringController{
    private UserDao uDao;
    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String dbTest(String username) {
        System.out.println(uDao.findByUsername(username).getUsername());
        return success("");
    }
    @Required
    public void setuDao(UserDao uDao) {
        this.uDao = uDao;
    }

}
</code>```

and it threw an exception.

```<code>org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345)
    at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:44)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:255)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:323)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:61)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:352)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1131)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:936)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

and I can't find a solution for it now.
I would like to make it like : Each http request will create a controller , a service,and a dao.
Help!

答:
looking at the exception

org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'

uDao is not configured to be injected in to the bean.

Try using

```<code>@Autowired
private UserDao uDao;
</code>```

also make sure if component scan is enabled in the xml configuration.

Body:
I wrote it as a singleton before, there were no errors.
But I think I should make it instance per request.
And I have the code

<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean" scope="request">
    <property name="mapperInterface" value="Dao.UserDao"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

package Test;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import Common.InitDataBases;
import Common.Controller.OutputStringController;
import Dao.UserDao;
import Model.User;
import java.util.List;

import org.apache.log4j.Logger;

@Controller
@Scope("request")
public class Hello extends OutputStringController{
    private UserDao uDao;
    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String dbTest(String username) {
        System.out.println(uDao.findByUsername(username).getUsername());
        return success("");
    }
    @Required
    public void setuDao(UserDao uDao) {
        this.uDao = uDao;
    }

}

and it threw an exception.

org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345)
    at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:44)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:255)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:323)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:61)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:352)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1131)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:936)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

and I can't find a solution for it now.
I would like to make it like : Each http request will create a controller , a service,and a dao.
Help!

Body:
looking at the exception

org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'

uDao is not configured to be injected in to the bean.

Try using

@Autowired
private UserDao uDao;

also make sure if component scan is enabled in the xml configuration.


问:
How To Only Selectively Read Numbers and/or Words From a .txt File?
I have a simple .txt file ("theFile.txt") with the following format where the left column are the lineNumber and the right column are the word:

```<code>5     today
2     It's
1     "
4     sunny
3     a
6     "
</code>```

For this txt file, I'm making two separate methods to each get only the number and only the string, plus another method to scan the file and put each lineNumber and word in a double-linked list DLL:

```<code>  String fileName = "theFile.txt";

  public int getNumberOnly() {
       int lineNumber;

       //code to only get the lineNumber but NOT the words
       //This is as far as I got and I need help on this part

       return lineNumber;
  }

  public String getWordsOnly() {
       String words;

       //code to only get the words but NOT the lineNumber
       //This is as far as I got and I need help on this part

       return words;
  }

  public void readAndPrintWholeFile(String fileName){

          String fileContents = new String();
          File file = new File("theFile.txt");
          Scanner scanner = new Scanner(new FileInputStream(fileName));
          DLL<T> list = new DLL<T>();

         //Print each lineNumber and corresponding words for example
         // 5   Today
         // 2   It's

         while (scanner.hasNextLine())
         {
              fileContents = scanner.nextLine();
              System.out.println(list.getNumbersOnly() + " " +  list.getWordOnly());
              //prints the lineNumber then space then the word
         }
  }

  //I already have all DLL accessors and mutators such as get & set next/previous nodes here, etc.
</code>```

I'm stuck on how to code the method bodies for both getNumbersOnly() and getWordOnly()

I've tried my best to get to this point.  Thanks for your help.

答:
```<code>public static void readAndPrintWholeFile(String filename) throws FileNotFoundException {
    String fileContents;
    File file = new File(filename);
    Scanner scanner = new Scanner(new FileInputStream(file));
    Map<String, String> map = new HashMap<>();

    while (scanner.hasNextLine()) {
        try {
            fileContents = scanner.nextLine();
            String[] as = fileContents.split(" +");
            map.put(as[0], as[1]);
            System.out.println(as[0] + " " + as[1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            //If some problam with File formate e.g. number without word
        }
    }
}
</code>```

You can do this in many way and one of them is hear.
Hera I am not implemented getNumberOnly() and getWordsOnly() method and I d't have DLL implementation so put data in map(HashMap).

Body:
I have a simple .txt file ("theFile.txt") with the following format where the left column are the lineNumber and the right column are the word:

5     today
2     It's
1     "
4     sunny
3     a
6     "

For this txt file, I'm making two separate methods to each get only the number and only the string, plus another method to scan the file and put each lineNumber and word in a double-linked list DLL:

  String fileName = "theFile.txt";

  public int getNumberOnly() {
       int lineNumber;

       //code to only get the lineNumber but NOT the words
       //This is as far as I got and I need help on this part

       return lineNumber;
  }

  public String getWordsOnly() {
       String words;

       //code to only get the words but NOT the lineNumber
       //This is as far as I got and I need help on this part

       return words;
  }

  public void readAndPrintWholeFile(String fileName){

          String fileContents = new String();
          File file = new File("theFile.txt");
          Scanner scanner = new Scanner(new FileInputStream(fileName));
          DLL<T> list = new DLL<T>();

         //Print each lineNumber and corresponding words for example
         // 5   Today
         // 2   It's

         while (scanner.hasNextLine())
         {
              fileContents = scanner.nextLine();
              System.out.println(list.getNumbersOnly() + " " +  list.getWordOnly());
              //prints the lineNumber then space then the word
         }
  }

  //I already have all DLL accessors and mutators such as get & set next/previous nodes here, etc.

I'm stuck on how to code the method bodies for both getNumbersOnly() and getWordOnly()

I've tried my best to get to this point.  Thanks for your help.

Body:
public static void readAndPrintWholeFile(String filename) throws FileNotFoundException {
    String fileContents;
    File file = new File(filename);
    Scanner scanner = new Scanner(new FileInputStream(file));
    Map<String, String> map = new HashMap<>();

    while (scanner.hasNextLine()) {
        try {
            fileContents = scanner.nextLine();
            String[] as = fileContents.split(" +");
            map.put(as[0], as[1]);
            System.out.println(as[0] + " " + as[1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            //If some problam with File formate e.g. number without word
        }
    }
}

You can do this in many way and one of them is hear.
Hera I am not implemented getNumberOnly() and getWordsOnly() method and I d't have DLL implementation so put data in map(HashMap).


问:
jQuery - Issues with combining selectors in a single event handler
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});
</code>```

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

答:
Well it is inefficient in the way that using a multiple selector would indicate that the function is generic enough to be used for all selected elements.

It would in my point of view be better to select each selector individualy and attach a click event to it. It then would also look more natural to me.

Body:
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()


问:
Unable to use a variable in a sh block
Why do I get the following error:

++ cat package.json

  ++ jq .version

  + TAG = '"0.0.5"' /****/script.sh:

  line 12: TAG: command not found

When running the below in a Jenkinsfile:

```<code>sh '''
    ...
    ...
    TAG = \$(cat package.json | jq '.version')
    git tag -a v${TAG} -m "New release: ${TAG}"
'''
</code>```

答:
As was mentioned in the comments, the problem was with the spaces before and after =. Additionally, I added escaping in the second line so it'll display as v0.0.6 and not v"0.0.6".

```<code>sh '''
    ...
    ...
    TAG=\$(jq -r '.version' package.json)
    git tag -a "v${TAG}" -m "New release: ${TAG}"
'''
</code>```

Title: Unable to use a variable in a sh block

Body:
Why do I get the following error:

++ cat package.json

  ++ jq .version

  + TAG = '"0.0.5"' /****/script.sh:

  line 12: TAG: command not found

When running the below in a Jenkinsfile:

sh '''
    ...
    ...
    TAG = \$(cat package.json | jq '.version')
    git tag -a v${TAG} -m "New release: ${TAG}"
'''

Body:
As was mentioned in the comments, the problem was with the spaces before and after =. Additionally, I added escaping in the second line so it'll display as v0.0.6 and not v"0.0.6".

sh '''
    ...
    ...
    TAG=\$(jq -r '.version' package.json)
    git tag -a "v${TAG}" -m "New release: ${TAG}"
'''


问:
How to control gif in a webpage?
I embedded a gif like this:

```<code><img src="myimage.gif">
</code>```

This plays when the page is loaded. I want to be able to have a start and stop or pause functionality for the image. The gif should toggle start and stop on click.

How can I achieve this?
Many Thanks.

答:
```<code>  $('.gifs a').embedly({
      display: function(obj){
        if (obj.type === 'photo'){

          var $this = $(this);

          // Create the static image src with Embedly Display.
          var src = $.embedly.display.display(obj.url, {query: {animate:false} });

          // Add static gif placeholder to the parent
          $this.html('<img class="gif-holder" src="'+src+'" />');

          // Start preloading the actually gif.
          $this.append('<img class="gif-preload" src="'+obj.url+'" />');

          // Create a promise so we can keep track of state.
          $this.data('promise', $.Deferred());

          // Get the element we added.
          var elem = $this.find('.gif-preload').get(0);

          // If the image is not in cache then onload will fire when it is.
          elem.onload = function(){
            $this.data('promise').resolve();
          };

          // If the image is already in the browsers cache call the handler.
          if (elem.complete) {
            $this.data('promise').resolve();
          }
          // Set the static gif url so we can use it later.
          $(this).data('static_url', src);
        } else {
          // remove li if it's not an image.
          $(this).parent().remove();
        }
      }
    }).on('mouseenter', function(){
      var $this = $(this);

      // Set the hover state to true so that the load function knows to run.
      $this.data('hover', true);

      // Create a function to load the gif into the image.
      var load = function(){
        if ($this.data('hover') === true){
          // Remove the loading image if there is one
          $this.find('.gif-loading').remove();

          // Swap out the static src for the actually gif.
          $this.find('img.gif-holder').attr('src', $this.data('embedly').url);
        }
      };
      // Add the load function to the done callback. If it's already resolved
      // this will fire immediately.
      $this.data('promise').done(load);

      // Add a spinner if it's not going to play right away.
      if ($this.data('promise').state() === 'pending'){
        // Add a loading spinner.
        $this.append('<i class="gif-loading fa fa-spinner fa fa-spin"></i>');

        // we need to center it over the image.
        $this.find('.gif-loading').css({
          top: $this.height() / 2 - 20,
          left: $this.width() / 2 - 20
        });
      }
    }).on('mouseleave', function(){
      var $this = $(this);

      // Make sure the load function knows we are no longer in a hover state.
      $this.data('hover', false);

      // Remove the spiner if it's there.
      $this.find('.gif-loading').remove();

      // Set the src to the static url.
      $this.find('img.gif-holder').attr('src', $(this).data('static_url'));
    });
</code>```

<p>Giving best animation You can use these codes in java script file </p>

Title: How to control gif in a webpage?

Body:
I embedded a gif like this:

This plays when the page is loaded. I want to be able to have a start and stop or pause functionality for the image. The gif should toggle start and stop on click.

How can I achieve this?
Many Thanks.

Body:
  $('.gifs a').embedly({
      display: function(obj){
        if (obj.type === 'photo'){

          var $this = $(this);

          // Create the static image src with Embedly Display.
          var src = $.embedly.display.display(obj.url, {query: {animate:false} });

          // Add static gif placeholder to the parent
          $this.html('<img class="gif-holder" src="'+src+'" />');

          // Start preloading the actually gif.
          $this.append('<img class="gif-preload" src="'+obj.url+'" />');

          // Create a promise so we can keep track of state.
          $this.data('promise', $.Deferred());

          // Get the element we added.
          var elem = $this.find('.gif-preload').get(0);

          // If the image is not in cache then onload will fire when it is.
          elem.onload = function(){
            $this.data('promise').resolve();
          };

          // If the image is already in the browsers cache call the handler.
          if (elem.complete) {
            $this.data('promise').resolve();
          }
          // Set the static gif url so we can use it later.
          $(this).data('static_url', src);
        } else {
          // remove li if it's not an image.
          $(this).parent().remove();
        }
      }
    }).on('mouseenter', function(){
      var $this = $(this);

      // Set the hover state to true so that the load function knows to run.
      $this.data('hover', true);

      // Create a function to load the gif into the image.
      var load = function(){
        if ($this.data('hover') === true){
          // Remove the loading image if there is one
          $this.find('.gif-loading').remove();

          // Swap out the static src for the actually gif.
          $this.find('img.gif-holder').attr('src', $this.data('embedly').url);
        }
      };
      // Add the load function to the done callback. If it's already resolved
      // this will fire immediately.
      $this.data('promise').done(load);

      // Add a spinner if it's not going to play right away.
      if ($this.data('promise').state() === 'pending'){
        // Add a loading spinner.
        $this.append('<i class="gif-loading fa fa-spinner fa fa-spin"></i>');

        // we need to center it over the image.
        $this.find('.gif-loading').css({
          top: $this.height() / 2 - 20,
          left: $this.width() / 2 - 20
        });
      }
    }).on('mouseleave', function(){
      var $this = $(this);

      // Make sure the load function knows we are no longer in a hover state.
      $this.data('hover', false);

      // Remove the spiner if it's there.
      $this.find('.gif-loading').remove();

      // Set the src to the static url.
      $this.find('img.gif-holder').attr('src', $(this).data('static_url'));
    });

Giving best animation You can use these codes in java script file


答:
$(*) is a selector in jqueryto select all elements

and hence

$("*").hide(); will hide all elements

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello</div>
<p>World</p>
<span>Good Morning</span>
<button>Hide</button></code>```

Docs

Title: What is the use of ("*") in jquery

Body:
$(*) is a selector in jqueryto select all elements

and hence

$("*").hide(); will hide all elements

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello</div>
<p>World</p>
<span>Good Morning</span>
<button>Hide</button>

Docs


问:
I was wondering why this code is not working?
I know it is because of the "Or" but I was hoping someone could explain why it does not work. </p>

```<code>If (Sheet.Name <> "Dep 1" Or "Test") Then
</code>```

<p>^</p>

```<code>Sub DeleteSheet()

Dim Sheet As Worksheet

Application.DisplayAlerts = False

For Each Sheet In ActiveWorkbook.Sheets

    If (Sheet.Name <> "Dep 1" Or "Test") Then

        Sheet.Delete

     End If

 Next Sheet

Application.DisplayAlerts = False

End Sub
</code>```

答:
My "Two-cents" to this post:

Try to use meaningful variable names, but NOT ones that are too close to Excel's saves words. Dim Sheet is ~ 85% similar to Sheets, which is a type of Object, I've seen so many posts here that people get cell with Cells mixed-up and get a run-time error.

I've switched your If with Select Case .Name, this way, if in the future you have add more Worksheets or want to perform other actions on other Worksheets, it will be easier to modify the code.

Code

```<code>Option Explicit

Sub DeleteSheet()

Dim ws As Worksheet

Application.DisplayAlerts = False

For Each ws In ActiveWorkbook.Sheets
    With ws
        Select Case .Name
            Case "Dep 1", "Test"
                ' do nothing for now
            Case Else
                .Delete
        End Select
    End With
Next ws
Application.DisplayAlerts = True ' <-- restore setting

End Sub
</code>```

Body:
I know it is because of the "Or" but I was hoping someone could explain why it does not work.

If (Sheet.Name <> "Dep 1" Or "Test") Then

^

Sub DeleteSheet()

Dim Sheet As Worksheet

Application.DisplayAlerts = False

For Each Sheet In ActiveWorkbook.Sheets

    If (Sheet.Name <> "Dep 1" Or "Test") Then

        Sheet.Delete

     End If

 Next Sheet

Application.DisplayAlerts = False

End Sub

Body:
My "Two-cents" to this post:

Try to use meaningful variable names, but NOT ones that are too close to Excel's saves words. Dim Sheet is ~ 85% similar to Sheets, which is a type of Object, I've seen so many posts here that people get cell with Cells mixed-up and get a run-time error.

I've switched your If with Select Case .Name, this way, if in the future you have add more Worksheets or want to perform other actions on other Worksheets, it will be easier to modify the code.

Code

Option Explicit

Sub DeleteSheet()

Dim ws As Worksheet

Application.DisplayAlerts = False

For Each ws In ActiveWorkbook.Sheets
    With ws
        Select Case .Name
            Case "Dep 1", "Test"
                ' do nothing for now
            Case Else
                .Delete
        End Select
    End With
Next ws
Application.DisplayAlerts = True ' <-- restore setting

End Sub


问:
How do I change the size of an array and fill it with automated elements?
I have an array with set elements 1 - 10. I have decided the size of the array and I have decided the elements of the array. My question is, how do I create an array of size x and fill it with elements 1,2,3,4 . . . </p>

```<code>//sets values of the array elements and print them.
cout << "Array should contain x integers set to 1,2,3" << endl;

// QUESTION: How can I change the size of the array and have
//           have values automatically entered?
int array[] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 0; i <= (sizeof(array) / sizeof(int)-1); ++i) {

    // sizeof(array)/sizeof(int) = 36/4. ints are 4.
    cout << "Element " << i << " = " << array[i] << endl;
}
    cout << "The number of elements in the array is: "
    << sizeof(array) / sizeof(int) << endl;
    cout << endl;
    cout << endl;
</code>```

答:
you can use dynamic memory allocation approach for your array, there you can give as much size as you want. Thanks.</p>

```<code>//Variable size of Array program to print Array elements

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter Array size x:" << endl;
    int x = 0;
    cin >> x;

    int *ptrArray = new int[x];

    //Inittialise Array
    for (int i = 0; i < x; i++)
    {
        ptrArray[i] = i + 1;
    }

    //Print Array elemts
    cout << "Array elements:";
    for (int i = 0; i < x; i++)
    {
        cout << ptrArray[i] << endl;
    }

    delete[] ptrArray;

    return 0;
}
</code>```

Body:
I have an array with set elements 1 - 10. I have decided the size of the array and I have decided the elements of the array. My question is, how do I create an array of size x and fill it with elements 1,2,3,4 . . .

//sets values of the array elements and print them.
cout << "Array should contain x integers set to 1,2,3" << endl;

// QUESTION: How can I change the size of the array and have
//           have values automatically entered?
int array[] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 0; i <= (sizeof(array) / sizeof(int)-1); ++i) {

    // sizeof(array)/sizeof(int) = 36/4. ints are 4.
    cout << "Element " << i << " = " << array[i] << endl;
}
    cout << "The number of elements in the array is: "
    << sizeof(array) / sizeof(int) << endl;
    cout << endl;
    cout << endl;

Body:
you can use dynamic memory allocation approach for your array, there you can give as much size as you want. Thanks.

//Variable size of Array program to print Array elements

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter Array size x:" << endl;
    int x = 0;
    cin >> x;

    int *ptrArray = new int[x];

    //Inittialise Array
    for (int i = 0; i < x; i++)
    {
        ptrArray[i] = i + 1;
    }

    //Print Array elemts
    cout << "Array elements:";
    for (int i = 0; i < x; i++)
    {
        cout << ptrArray[i] << endl;
    }

    delete[] ptrArray;

    return 0;
}