问:
Cannot create an instance of class ViewModel
I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle owner:-

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

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}
</code>```

ViewModel:-

```<code>public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}
</code>```

答: Make your constructor public.

Body:
I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle owner:-

public class MainActivity extends LifecycleActivity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}

ViewModel:-

public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}

Body: Make your constructor public.


来源: stackexchange

问:
Raw text "" must be wrapped in explicit text component
I am using a react native component listview to render nested items as follows:

```<code>      constructor() {
        super();

        this.renderRow = this.renderRow.bind(this);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
          dataSource: ds.cloneWithRows([
            [
              {'main':'q', 'sub': 'y'}
            ],
            [
              {'main':'x', 'sub': 'f'},
              {'main':'c', 'sub': 'b'}
            ]
          ]),
        };
      }

      renderRow(rowData, section, row) {
        const total = this.state.dataSource.getRowCount();

        let rowView = rowData.map( x => {
          return <View> <Text>{x['main']}</Text> <Text>{x['sub']}</Text> </View>
        })
        return (
          <View>

            {rowView}
          </View>
        );
      }

      render() {
        return (
          <View style={styles.container}>
            <ListView style={styles.listView}
              dataSource={this.state.dataSource}
              renderRow={this.renderRow}
            />
          </View>
        );
      }
</code>```

But I am getting following error:
Raw text "" must be wrapped in explicit text component.

I am unable to track where I am getting this error from.

答:
Mainly this issue arise due to space between <View> <Text> etc

A trick fix for this issue could be execute Format Document (I am using VScode (IDE), you can try with any IDE which have code styling capability). By Style fixing spaces between tags gets automatically removed.

ContentLicense: CC BY-SA 3.0

Body:
I am using a react native component listview to render nested items as follows:

      constructor() {
        super();

        this.renderRow = this.renderRow.bind(this);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
          dataSource: ds.cloneWithRows([
            [
              {'main':'q', 'sub': 'y'}
            ],
            [
              {'main':'x', 'sub': 'f'},
              {'main':'c', 'sub': 'b'}
            ]
          ]),
        };
      }

      renderRow(rowData, section, row) {
        const total = this.state.dataSource.getRowCount();

        let rowView = rowData.map( x => {
          return <View> <Text>{x['main']}</Text> <Text>{x['sub']}</Text> </View>
        })
        return (
          <View>

            {rowView}
          </View>
        );
      }

      render() {
        return (
          <View style={styles.container}>
            <ListView style={styles.listView}
              dataSource={this.state.dataSource}
              renderRow={this.renderRow}
            />
          </View>
        );
      }

But I am getting following error:
Raw text "" must be wrapped in explicit text component.

I am unable to track where I am getting this error from.


问:
SQL: Advantages of an ENUM vs. a one-to-many relationship?
I very rarely see ENUM datatypes used in the wild; a developer almost always just uses a secondary table that looks like this:

```<code>CREATE TABLE officer_ranks (
id int PRIMARY KEY
,title varchar NOT NULL UNIQUE);
INSERT INTO officer_ranks VALUES (1,'2LT'),(2,'1LT'),(3,'CPT'),(4,'MAJ'),(5,'LTC'),(6,'COL'),(7,'BG'),(8,'MG'),(9,'LTG'),(10,'GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank int NOT NULL REFERENCES officer_ranks(id) ON DELETE RESTRICT
,serial_num varchar PRIMARY KEY);
</code>```

But the same thing can also be shown using a user-defined type / ENUM:

```<code>CREATE TYPE officer_rank AS ENUM ('2LT', '1LT','CPT','MAJ','LTC','COL','BG','MG','LTG','GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank officer_rank NOT NULL
,serial_num varchar PRIMARY KEY);
</code>```

(Example shown using PostgreSQL, but other RDBMS's have similar syntax)

The biggest disadvantage I see to using an ENUM is that it's more difficult to update from within an application.  And it might also confuse an inexperienced developer who's used to using a SQL DB simply as a bit bucket.

Assuming that the information is mostly static (weekday names, month names, US Army ranks, etc) is there any advantage to using a ENUM?

答:
Well, you don't see, because usually developers are using enums in programming languages such as Java, and the don't have their counterparts in database design.

In database such enums are usually text or integer fields, with no constraints. Database enums will not be translated into Java/C#/etc. enums, so the developers see no gain in this.

There are very many very good database features which are rarely used because most ORM tools are too primitive to support them.

ContentLicense: CC BY-SA 4.0

Body:
I very rarely see ENUM datatypes used in the wild; a developer almost always just uses a secondary table that looks like this:

CREATE TABLE officer_ranks (
id int PRIMARY KEY
,title varchar NOT NULL UNIQUE);
INSERT INTO officer_ranks VALUES (1,'2LT'),(2,'1LT'),(3,'CPT'),(4,'MAJ'),(5,'LTC'),(6,'COL'),(7,'BG'),(8,'MG'),(9,'LTG'),(10,'GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank int NOT NULL REFERENCES officer_ranks(id) ON DELETE RESTRICT
,serial_num varchar PRIMARY KEY);

But the same thing can also be shown using a user-defined type / ENUM:

CREATE TYPE officer_rank AS ENUM ('2LT', '1LT','CPT','MAJ','LTC','COL','BG','MG','LTG','GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank officer_rank NOT NULL
,serial_num varchar PRIMARY KEY);

(Example shown using PostgreSQL, but other RDBMS's have similar syntax)

The biggest disadvantage I see to using an ENUM is that it's more difficult to update from within an application.  And it might also confuse an inexperienced developer who's used to using a SQL DB simply as a bit bucket.

Assuming that the information is mostly static (weekday names, month names, US Army ranks, etc) is there any advantage to using a ENUM?

ContentLicense: CC BY-SA 2.5


问:
GAE Getting Started with Flask (empty firefox browser)
I just went through the Getting Start with Flask on App Engine Standard Environment tutorial. The source code is here.

Firefox and Chrome both the html templates but neither render them when running locally:

```<code>dev_appserver.py app.yaml
</code>```

or in the cloud

```<code>gcloud app deploy
</code>```

The FireFox Developer Tools console tells me that:

The character encoding of the HTML document was not declared. The
  document will render with garbled text in some browser configurations
  if the document contains characters from outside the US-ASCII range.
  The character encoding of the page must be declared in the document or
  in the transfer protocol.

I tried adding declaring UTF-8 encoding by adding this line to the html files.

```<code><html>
  <head>
    <meta charset="utf-8"/>
    ...
</code>```

but to no avail. Any ideas?

Thanks!

答:
I don't think this is the reason your template is not rendering.  But, to get rid of that error, try:

```<code><meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</code>```

To troubleshoot your template, please provide your url handlers, view handler, and template.html

Body:
I just went through the Getting Start with Flask on App Engine Standard Environment tutorial. The source code is here.

Firefox and Chrome both the html templates but neither render them when running locally:

dev_appserver.py app.yaml

or in the cloud

gcloud app deploy

The FireFox Developer Tools console tells me that:

The character encoding of the HTML document was not declared. The
  document will render with garbled text in some browser configurations
  if the document contains characters from outside the US-ASCII range.
  The character encoding of the page must be declared in the document or
  in the transfer protocol.

I tried adding declaring UTF-8 encoding by adding this line to the html files.

    <meta charset="utf-8"/>
    ...

but to no avail. Any ideas?

Thanks!

Body:
I don't think this is the reason your template is not rendering.  But, to get rid of that error, try:

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

To troubleshoot your template, please provide your url handlers, view handler, and template.html


问:
Changing language on click of button: Android
I am working on a project in which I have to change the locale on button click. I had set the  default locale as hindi. When the app first starts, the contents are shown in hindi. When I click on the button it will change to english. Now I want that when I again press the button the content shold change back to hindi. But this is not working. I van switch hindi to english  but not vice versa. Below I am posting my code:</p>

```<code>public class MainActivity extends Activity
{
Button btn1;
TextView textView1;
String LOCALE_HINDI = "hi";
String LOCALE_ENGLISH = "en";
Locale mLocale;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    mLocale = new Locale(LOCALE_HINDI);
    Locale.setDefault(mLocale);
    Configuration config = new Configuration();
    config.locale = mLocale;
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());
    this.setContentView(R.layout.activity_main);

    btn1 = (Button)findViewById(R.id.btn1);
    textView1 = (TextView)findViewById(R.id.textView1);

    btn1.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            if(LOCALE_HINDI.equals(mLocale.toString()))
            {
                mLocale = new Locale(LOCALE_ENGLISH);
                Locale.setDefault(mLocale);
                Configuration config = new Configuration();
                config.locale = mLocale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());
                MainActivity.this.setContentView(R.layout.activity_main);
                Log.d("LocaleTest", "if block");
            }//if
            else if (LOCALE_ENGLISH.equals(mLocale))
            {
                mLocale = new Locale(LOCALE_HINDI);
                Locale.setDefault(mLocale);
                Configuration config = new Configuration();
                config.locale = mLocale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());
                MainActivity.this.setContentView(R.layout.activity_main);
                Log.d("LocaleTest", "else if block");
            }//else if
        }
    });
}
}
</code>```

答:
try this methode :</p>

```<code>  public String languageCheck() {
    String lCode="en";
    if(PersistData.getStringData(getApplicationContext(), "LNG").equalsIgnoreCase("en")) {
        lCode="hi";
    }
    else if(PersistData.getStringData(getApplicationContext(), "LNG").equalsIgnoreCase("hi")) {
        lCode="en";
    }
    return lCode;
}
</code>```

Body:
I am working on a project in which I have to change the locale on button click. I had set the  default locale as hindi. When the app first starts, the contents are shown in hindi. When I click on the button it will change to english. Now I want that when I again press the button the content shold change back to hindi. But this is not working. I van switch hindi to english  but not vice versa. Below I am posting my code:

public class MainActivity extends Activity
{
Button btn1;
TextView textView1;
String LOCALE_HINDI = "hi";
String LOCALE_ENGLISH = "en";
Locale mLocale;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    mLocale = new Locale(LOCALE_HINDI);
    Locale.setDefault(mLocale);
    Configuration config = new Configuration();
    config.locale = mLocale;
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());
    this.setContentView(R.layout.activity_main);

    btn1 = (Button)findViewById(R.id.btn1);
    textView1 = (TextView)findViewById(R.id.textView1);

    btn1.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            if(LOCALE_HINDI.equals(mLocale.toString()))
            {
                mLocale = new Locale(LOCALE_ENGLISH);
                Locale.setDefault(mLocale);
                Configuration config = new Configuration();
                config.locale = mLocale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());
                MainActivity.this.setContentView(R.layout.activity_main);
                Log.d("LocaleTest", "if block");
            }//if
            else if (LOCALE_ENGLISH.equals(mLocale))
            {
                mLocale = new Locale(LOCALE_HINDI);
                Locale.setDefault(mLocale);
                Configuration config = new Configuration();
                config.locale = mLocale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());
                MainActivity.this.setContentView(R.layout.activity_main);
                Log.d("LocaleTest", "else if block");
            }//else if
        }
    });
}
}

Body:
try this methode :

  public String languageCheck() {
    String lCode="en";
    if(PersistData.getStringData(getApplicationContext(), "LNG").equalsIgnoreCase("en")) {
        lCode="hi";
    }
    else if(PersistData.getStringData(getApplicationContext(), "LNG").equalsIgnoreCase("hi")) {
        lCode="en";
    }
    return lCode;
}


问:
MTR results to json with php
I'm creating a system for work where I will have VMS around our multiple locations and I'll have a central page where you can enter an IP and it will pull all the MTRS from the remote ones and dump the results.

I'm thinking the best way to accomplish this is would be to make a call to a page on the remote server which will start the MTR and then provide the results in Json,

My issue I'm struggling with is how to break up the different values and metrics in the MTR into different objects in the JSON array. I've considered regex but I feel like that has to be a better way. ALl help is appreciated.

example MTR for discussion.

```<code>Start: Fri Apr 21 01:56:17 2017

HOST: MTR-DC08                             Loss%   Snt   Last   Avg  Best  Wrst StDev

  1.|-- dc03r04ds36.scalabledns.com           0.0%    10    0.1   0.1   0.1   0.1   0.0

  2.|-- dc08mx01.scalabledns.com              0.0%    10    0.8   1.1   0.8   2.0   0.0

  3.|-- enzu.com-gw.lax.ip4.zayo.com          0.0%    10    0.8   1.2   0.8   2.6   0.5

  4.|-- ae16.cr1.lax112.us.zip.zayo.com       0.0%    10    1.0   1.4   1.0   2.5   0.3

  5.|-- ae9.mpr1.lax12.us.zip.zayo.com        0.0%    10    1.0   1.0   1.0   1.2   0.0

  6.|-- ae7.edge2.LosAngles.Level3.net        0.0%    10    1.0   1.6   0.9   6.8   1.7

  7.|-- ae-1-60.edge3.LosAngeles1.Level3.net  0.0%    10    1.1   2.8   1.1   9.1   2.6

  8.|-- a.resolvers.level3.net                0.0%    10    1.0   1.0   1.0   1.1   0.0
</code>```

答:
If you pass the -j flag or --json on the mtr command, your output will be JSON. No regex required.

```<code>$: mtr -j 8.8.8.8

{"report": {
   "mtr": {
     "src": "me",
     "dst": "8.8.8.8",
     "tos": "0x0",
     "psize": "64",
     "bitpattern": "0x00",
     "tests": "10"
   },
   "hubs": [{
     "count": "1",
     "host": "???",
     "Loss%": 0.00,
     "Snt": 10,
     "Last": 1.58,
     "Avg": 19.83,
     "Best": 1.48,
     "Wrst": 183.60,
     "StDev": 57.54
   },

[...]

   {
     "count": "10",
     "host": "google-public-dns-a.google.com",
     "Loss%": 0.00,
     "Snt": 10,
     "Last": 32.19,
     "Avg": 31.02,
     "Best": 25.18,
     "Wrst": 55.12,
     "StDev": 8.87
   }]
}}
</code>```

See the man page for all the supported options: https://www.mankier.com/8/mtr#-j

In more complicated environments that have multipath routing, you may want to consider Dublin Traceroute (https://dublin-traceroute.net) rather than mtr. Again, output is in JSON so it should make it easy for your to parse the hops.

Title: MTR results to json with php

Body:
I'm creating a system for work where I will have VMS around our multiple locations and I'll have a central page where you can enter an IP and it will pull all the MTRS from the remote ones and dump the results.

I'm thinking the best way to accomplish this is would be to make a call to a page on the remote server which will start the MTR and then provide the results in Json,

My issue I'm struggling with is how to break up the different values and metrics in the MTR into different objects in the JSON array. I've considered regex but I feel like that has to be a better way. ALl help is appreciated.

example MTR for discussion.

Start: Fri Apr 21 01:56:17 2017

HOST: MTR-DC08                             Loss%   Snt   Last   Avg  Best  Wrst StDev

  1.|-- dc03r04ds36.scalabledns.com           0.0%    10    0.1   0.1   0.1   0.1   0.0

  2.|-- dc08mx01.scalabledns.com              0.0%    10    0.8   1.1   0.8   2.0   0.0

  3.|-- enzu.com-gw.lax.ip4.zayo.com          0.0%    10    0.8   1.2   0.8   2.6   0.5

  4.|-- ae16.cr1.lax112.us.zip.zayo.com       0.0%    10    1.0   1.4   1.0   2.5   0.3

  5.|-- ae9.mpr1.lax12.us.zip.zayo.com        0.0%    10    1.0   1.0   1.0   1.2   0.0

  6.|-- ae7.edge2.LosAngles.Level3.net        0.0%    10    1.0   1.6   0.9   6.8   1.7

  7.|-- ae-1-60.edge3.LosAngeles1.Level3.net  0.0%    10    1.1   2.8   1.1   9.1   2.6

  8.|-- a.resolvers.level3.net                0.0%    10    1.0   1.0   1.0   1.1   0.0

Body:
If you pass the -j flag or --json on the mtr command, your output will be JSON. No regex required.

$: mtr -j 8.8.8.8

{"report": {
   "mtr": {
     "src": "me",
     "dst": "8.8.8.8",
     "tos": "0x0",
     "psize": "64",
     "bitpattern": "0x00",
     "tests": "10"
   },
   "hubs": [{
     "count": "1",
     "host": "???",
     "Loss%": 0.00,
     "Snt": 10,
     "Last": 1.58,
     "Avg": 19.83,
     "Best": 1.48,
     "Wrst": 183.60,
     "StDev": 57.54
   },

[...]

   {
     "count": "10",
     "host": "google-public-dns-a.google.com",
     "Loss%": 0.00,
     "Snt": 10,
     "Last": 32.19,
     "Avg": 31.02,
     "Best": 25.18,
     "Wrst": 55.12,
     "StDev": 8.87
   }]
}}

See the man page for all the supported options: https://www.mankier.com/8/mtr#-j

In more complicated environments that have multipath routing, you may want to consider Dublin Traceroute (https://dublin-traceroute.net) rather than mtr. Again, output is in JSON so it should make it easy for your to parse the hops.


问:
Jade / pug: passing html that contains a variable into template
I'm working on an application based on keystone.js. I would like the end-users to be able to create content that changes based on variables. For example, if they would like to create an e-mail template, they could write:

Hi #{firstName},...

That would be passed into jade as plain html like so:

 Hi #{firstName}...

The template should evaluate #{firstName} to the first name in question.

I've tried to implement this in a jade template as follows:

```<code>//Jade template
.div
  p #{firstName}
.div
   !=html
</code>```

The line p #{firstName} prints the value for firstName, but !=html prints "Hi #{firstName},...".

Is there anything I'm doing wrong or is this just not supported with Jade?

答:
this is expected behavior. ! is a escape character and expects only text not variables.

you should evaluate pug html in nodejs, pass this string as variable to pug template.

nodejs code

```<code>var pug = require('pug');
html = pug.render(html, {firstName:firstName});
</code>```

pug code

```<code>.div
  p #{firstName}
.div
   !=html
</code>```

Body:
I'm working on an application based on keystone.js. I would like the end-users to be able to create content that changes based on variables. For example, if they would like to create an e-mail template, they could write:

Hi #{firstName},...

That would be passed into jade as plain html like so:

 Hi #{firstName}...

The template should evaluate #{firstName} to the first name in question.

I've tried to implement this in a jade template as follows:

//Jade template
.div
  p #{firstName}
.div
   !=html

The line p #{firstName} prints the value for firstName, but !=html prints "Hi #{firstName},...".

Is there anything I'm doing wrong or is this just not supported with Jade?

Body:
this is expected behavior. ! is a escape character and expects only text not variables.

you should evaluate pug html in nodejs, pass this string as variable to pug template.

nodejs code

var pug = require('pug');
html = pug.render(html, {firstName:firstName});

pug code

.div
  p #{firstName}
.div
   !=html


问:
Firebase Google users not showing in Firebase Console Authentication
Using Firebase Google Auth, when a user logs in successfully with their google account, they are not showing on our Firebase Console Authentication->Users screen.  Only email/password users are showing up there. </p>

<p>Is there something extra that needs to be done to see the Google Auth users? </p>

答: As indicated by Frank, to fully sign into Firebase the call to signInWithCredential() was needed.  After implementing this functionality, users signing in with Google showed up in the Firebase console.</p>

Body:
Using Firebase Google Auth, when a user logs in successfully with their google account, they are not showing on our Firebase Console Authentication->Users screen.  Only email/password users are showing up there.

Is there something extra that needs to be done to see the Google Auth users?


问:
How to target different element that has same index with pure javascript
I want to make a simple slider using pure javascript that support at least ie8, but got stuck at the moment. The problem is I when I click one of the paging items it should grab current index and then target another div for the slider container item with the same index as the paging. Basically I want to add and remove active class on both div.sliderItems & div.pagingItems based on div.pagingItems index. Here's my code:

window.onload = function(){
    var slider = document.getElementById('slider'),
      sliderItems = slider.children,
      totalItems = sliderItems.length,
      activeSlider = document.querySelector('.activeSlider'),
      pagingSlider = document.getElementById('pagingSlider'),
      pagingItems = pagingSlider.children,
      activePaging = document.querySelector('.activePaging');

    function next(){
      for (var i = 0; i < totalItems; i++) {
        if (i < totalItems - 1) {
          if (sliderItems[i].className.match( /(?:^|\s)activeSlider(?!\S)/ )) {
            sliderItems[i].className = sliderItems[i].className.replace( /(?:^|\s)activeSlider(?!\S)/g , '' );
            sliderItems[i + 1].className += ' activeSlider';

            pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
            pagingItems[i + 1].className += ' activePaging';
            return;
          }
        } else {
          sliderItems[i].className = sliderItems[i].className.replace( /(?:^|\s)activeSlider(?!\S)/g , '' );
          sliderItems[i + 1 - totalItems].className += ' activeSlider';

          pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
          pagingItems[i + 1 - totalItems].className += ' activePaging';
          return;
        }
      }
    }

    for (var i = 0; i < totalItems; i++) {
    (function(index){
     pagingItems[i].onclick = function(){
      pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
      this.className += ' activePaging';
      console.log(index);
     }
    })(i);
   }

   if (activeSlider === null) {
    sliderItems[0].className += ' activeSlider';
    pagingItems[0].className += ' activePaging';
   }

   var start = setInterval(next, 3000);

   pagingSlider.onmouseenter = function(){clearInterval(start);};
   pagingSlider.onmouseleave = function(){start = setInterval(next, 3000);};
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
html, body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}
.wrapperSlider {
  position: relative;
  width: 100%;
  padding-bottom: 35%;
}
#slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
#slider > * {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
  background: red;
  opacity: 0;
  transition: all ease-in-out .5s;
}
#slider > * > * {
  display: table-cell;
  vertical-align: middle;
}
#slider > *.activeSlider {
  z-index: 1;
  background: green;
  opacity: 1;
}
.wrapperPaging {
  text-align: center;
}
#pagingSlider {
  display: inline-block;
  font-size: 0;
}
#pagingSlider > * {
  display: inline-block;
  margin: 0 10px;
  font-size: 14px;
  color: black;
  cursor: pointer;
  transition: all ease-in-out .5s;
}
#pagingSlider > *.activePaging {
  color: red;
  cursor: default;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test File | Vanilla JS</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">

Item 1

Item 2

Item 3

Item 4

Item 5

    1
    2
    3
    4
    5

```

答:
Your onclick function has a closure around the i loop counter, which is causing the "classic" closure bug of all of your event handlers sharing the same value for i and i persisting after its defining scope has ended. At that point, i has the last value set by the loop, which is one more than the number of actual items there are, so when the time comes to click on your slider, no matter which number you click on, you get the same i value that is one more than the highest index used. While your code was set up to avoid this problem by using an immediately invoked function expression that passes itself a copy of i, which it receives as index, your nested onclick functions ignored that and used i anyway. You could just change references to i with index. But, changing the pageSlider[i] reference to this solves the issue as well and doesn't rely on the IIFE.

A couple of other small pieces of advice...

An  is only valid when it has a name or href attribute and, in your case, you really aren't trying to navigate anywhere, so the  tag is inappropriate for what you are doing. In my example below, I've changed those to  elements, which is more appropriate.

Instead of working with the className property, it is simpler (and less error prone) to use classList, which provides .add(), remove() and toggle() and methods. When you use .add(), you don't have to worry about prepending a space in situations when there will be more than one class applied. And, most importantly, you can easily remove a class without regular expressions and String.replace().

window.onload = function(){
  var slider = document.getElementById('slider'),
      sliderItems = slider.children,
      totalItems = sliderItems.length,
      activeSlider = document.querySelector('.activeSlider'),
      pagingSlider = document.getElementById('pagingSlider'),
      pagingItems = pagingSlider.children,
      activePaging = document.querySelector('.activePaging');

  function next(){
    for (var i = 0; i < totalItems; i++) {
      if (i < totalItems - 1) {
        if (sliderItems[i].className.indexOf('activeSlider') > -1) {
          sliderItems[i].classList.remove('activeSlider');
          sliderItems[i + 1].classList.add('activeSlider');

          pagingItems[i].classList.remove('activePaging');
          pagingItems[i + 1].classList.add('activePaging');
        }
      } else {
        sliderItems[i].classList.remove('activeSlider');
        sliderItems[i + 1 - totalItems].classList.add('activeSlider');

        pagingItems[i].classList.remove('activePaging');
        pagingItems[i + 1 - totalItems].classList.add('activePaging');
      }
    }
  }

  for (var i = 0; i < totalItems; i++) {
    pagingItems[i].onclick = function(){
      // You were forming a closure around i in this function. You can reference
      // the element that triggered the event simply with "this"
      this.previousElementSibling.classList.remove('activePaging');
      this.classList.add('activePaging');
    }
  }

  if (activeSlider === null) {
   sliderItems[0].classList.add('activeSlider');
   pagingItems[0].classList.add('activePaging');
  }

  var start = setInterval(next, 3000);

  pagingSlider.onmouseenter = function(){clearInterval(start);};
  pagingSlider.onmouseleave = function(){start = setInterval(next, 3000);};
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
html, body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}
.wrapperSlider {
  position: relative;
  width: 100%;
  padding-bottom: 35%;
}
#slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
#slider > * {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
  background: red;
  opacity: 0;
  transition: all ease-in-out .5s;
}
#slider > * > * {
  display: table-cell;
  vertical-align: middle;
}
#slider > *.activeSlider {
  z-index: 1;
  background: green;
  opacity: 1;
}
.wrapperPaging {
  text-align: center;
}
#pagingSlider {
  display: inline-block;
  font-size: 0;
}
#pagingSlider > * {
  display: inline-block;
  margin: 0 10px;
  font-size: 14px;
  color: black;
  cursor: pointer;
  transition: all ease-in-out .5s;
}
#pagingSlider > *.activePaging {
  color: red;
  cursor: default;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test File | Vanilla JS</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">

Item 1

Item 2

Item 3

Item 4

Item 5

    1
    2
    3
    4
    5

```

Body:
I want to make a simple slider using pure javascript that support at least ie8, but got stuck at the moment. The problem is I when I click one of the paging items it should grab current index and then target another div for the slider container item with the same index as the paging. Basically I want to add and remove active class on both div.sliderItems & div.pagingItems based on div.pagingItems index. Here's my code:

window.onload = function(){
    var slider = document.getElementById('slider'),
      sliderItems = slider.children,
      totalItems = sliderItems.length,
      activeSlider = document.querySelector('.activeSlider'),
      pagingSlider = document.getElementById('pagingSlider'),
      pagingItems = pagingSlider.children,
      activePaging = document.querySelector('.activePaging');

    function next(){
      for (var i = 0; i < totalItems; i++) {
        if (i < totalItems - 1) {
          if (sliderItems[i].className.match( /(?:^|\s)activeSlider(?!\S)/ )) {
            sliderItems[i].className = sliderItems[i].className.replace( /(?:^|\s)activeSlider(?!\S)/g , '' );
            sliderItems[i + 1].className += ' activeSlider';

            pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
            pagingItems[i + 1].className += ' activePaging';
            return;
          }
        } else {
          sliderItems[i].className = sliderItems[i].className.replace( /(?:^|\s)activeSlider(?!\S)/g , '' );
          sliderItems[i + 1 - totalItems].className += ' activeSlider';

          pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
          pagingItems[i + 1 - totalItems].className += ' activePaging';
          return;
        }
      }
    }

    for (var i = 0; i < totalItems; i++) {
    (function(index){
     pagingItems[i].onclick = function(){
      pagingItems[i].className = pagingItems[i].className.replace( /(?:^|\s)activePaging(?!\S)/g , '' );
      this.className += ' activePaging';
      console.log(index);
     }
    })(i);
   }

   if (activeSlider === null) {
    sliderItems[0].className += ' activeSlider';
    pagingItems[0].className += ' activePaging';
   }

   var start = setInterval(next, 3000);

   pagingSlider.onmouseenter = function(){clearInterval(start);};
   pagingSlider.onmouseleave = function(){start = setInterval(next, 3000);};
  }

* {
  box-sizing: border-box;
}
html, body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}
.wrapperSlider {
  position: relative;
  width: 100%;
  padding-bottom: 35%;
}
#slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
#slider > * {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
  background: red;
  opacity: 0;
  transition: all ease-in-out .5s;
}
#slider > * > * {
  display: table-cell;
  vertical-align: middle;
}
#slider > *.activeSlider {
  z-index: 1;
  background: green;
  opacity: 1;
}
.wrapperPaging {
  text-align: center;
}
#pagingSlider {
  display: inline-block;
  font-size: 0;
}
#pagingSlider > * {
  display: inline-block;
  margin: 0 10px;
  font-size: 14px;
  color: black;
  cursor: pointer;
  transition: all ease-in-out .5s;
}
#pagingSlider > *.activePaging {
  color: red;
  cursor: default;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test File | Vanilla JS</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">

Item 1

Item 2

Item 3

Item 4

Item 5

    1
    2
    3
    4
    5

Body:
Your onclick function has a closure around the i loop counter, which is causing the "classic" closure bug of all of your event handlers sharing the same value for i and i persisting after its defining scope has ended. At that point, i has the last value set by the loop, which is one more than the number of actual items there are, so when the time comes to click on your slider, no matter which number you click on, you get the same i value that is one more than the highest index used. While your code was set up to avoid this problem by using an immediately invoked function expression that passes itself a copy of i, which it receives as index, your nested onclick functions ignored that and used i anyway. You could just change references to i with index. But, changing the pageSlider[i] reference to this solves the issue as well and doesn't rely on the IIFE.

A couple of other small pieces of advice...

An <a> is only valid when it has a name or href attribute and, in your case, you really aren't trying to navigate anywhere, so the <a> tag is inappropriate for what you are doing. In my example below, I've changed those to <span> elements, which is more appropriate.

Instead of working with the className property, it is simpler (and less error prone) to use classList, which provides .add(), remove() and toggle() and methods. When you use .add(), you don't have to worry about prepending a space in situations when there will be more than one class applied. And, most importantly, you can easily remove a class without regular expressions and String.replace().

window.onload = function(){
  var slider = document.getElementById('slider'),
      sliderItems = slider.children,
      totalItems = sliderItems.length,
      activeSlider = document.querySelector('.activeSlider'),
      pagingSlider = document.getElementById('pagingSlider'),
      pagingItems = pagingSlider.children,
      activePaging = document.querySelector('.activePaging');

  function next(){
    for (var i = 0; i < totalItems; i++) {
      if (i < totalItems - 1) {
        if (sliderItems[i].className.indexOf('activeSlider') > -1) {
          sliderItems[i].classList.remove('activeSlider');
          sliderItems[i + 1].classList.add('activeSlider');

          pagingItems[i].classList.remove('activePaging');
          pagingItems[i + 1].classList.add('activePaging');
        }
      } else {
        sliderItems[i].classList.remove('activeSlider');
        sliderItems[i + 1 - totalItems].classList.add('activeSlider');

        pagingItems[i].classList.remove('activePaging');
        pagingItems[i + 1 - totalItems].classList.add('activePaging');
      }
    }
  }

  for (var i = 0; i < totalItems; i++) {
    pagingItems[i].onclick = function(){
      // You were forming a closure around i in this function. You can reference
      // the element that triggered the event simply with "this"
      this.previousElementSibling.classList.remove('activePaging');
      this.classList.add('activePaging');
    }
  }

  if (activeSlider === null) {
   sliderItems[0].classList.add('activeSlider');
   pagingItems[0].classList.add('activePaging');
  }

  var start = setInterval(next, 3000);

  pagingSlider.onmouseenter = function(){clearInterval(start);};
  pagingSlider.onmouseleave = function(){start = setInterval(next, 3000);};
}

* {
  box-sizing: border-box;
}
html, body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}
.wrapperSlider {
  position: relative;
  width: 100%;
  padding-bottom: 35%;
}
#slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
#slider > * {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
  background: red;
  opacity: 0;
  transition: all ease-in-out .5s;
}
#slider > * > * {
  display: table-cell;
  vertical-align: middle;
}
#slider > *.activeSlider {
  z-index: 1;
  background: green;
  opacity: 1;
}
.wrapperPaging {
  text-align: center;
}
#pagingSlider {
  display: inline-block;
  font-size: 0;
}
#pagingSlider > * {
  display: inline-block;
  margin: 0 10px;
  font-size: 14px;
  color: black;
  cursor: pointer;
  transition: all ease-in-out .5s;
}
#pagingSlider > *.activePaging {
  color: red;
  cursor: default;
}

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Test File | Vanilla JS</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
 </head>
 <body>

  <div class="wrapperSlider">
   <div id="slider">
    <div class="sliderItems">
     <div>Item 1</div>
    </div>
    <div class="sliderItems">
     <div>Item 2</div>
    </div>
    <div class="sliderItems">
     <div>Item 3</div>
    </div>
    <div class="sliderItems">
     <div>Item 4</div>
    </div>
    <div class="sliderItems">
     <div>Item 5</div>
    </div>
   </div>
  </div>

  <div class="wrapperPaging">
   <div id="pagingSlider">
    <span class="pagingItems">1</span>
    <span class="pagingItems">2</span>
    <span class="pagingItems">3</span>
    <span class="pagingItems">4</span>
    <span class="pagingItems">5</span>
   </div>
  </div>

 </body>
</html>


问:
How to set a cookie to hide a notice bar on second page load?
This is what I wan't:

A new user visits my website. A notice bar fixed to the bottom of the viewport is visible.

The user then clicks on a menu item, to go to another page. A cookie is set on 2nd page load, that hides the notice bar for 60 days (must be 100% hidden and not flash on page load duo to javascript being loaded asynchronous).

The user can also click on the "Ok" button to close the notice bar and set the same cookie.

This is my HTML:

```<code><div id="cookie-message">
    <span>Cookie notice here <a href="#">Read more</a> <a href="#" id="cookie-message-close">Ok</a></span>
</div>
</code>```

How can I do this with jQuery?

Thanks!

答:
Thanks a lot for your response, Henrique. However I couldn't get it to work duo to a "jQuery $.cookie is not a function" error.

I found out that "jQuery Cookie" is deprecated and js-cookie is the new version. By including that and changing the old cookie functions to the new ones it now works perfectly!

This is my final jQuery code, using "js-cookie":

```<code>window.addEventListener('load', function(){
    jQuery('#cookie-message-close').click(function(){
        jQuery('#cookie-message').hide();
    });

    if (!Cookies.get("cookie-message-bar"))
    {
        jQuery('#cookie-message').show();
        Cookies.set('cookie-message-bar', true, { expires: 60 });
    }
});
</code>```

Note that I've changed $ to jQuery because of Wordpress' noConflict() mode, since I'm developing in Wordpress.

Body:
This is what I wan't:

A new user visits my website. A notice bar fixed to the bottom of the viewport is visible.

The user then clicks on a menu item, to go to another page. A cookie is set on 2nd page load, that hides the notice bar for 60 days (must be 100% hidden and not flash on page load duo to javascript being loaded asynchronous).

The user can also click on the "Ok" button to close the notice bar and set the same cookie.

This is my HTML:

    Cookie notice here Read more Ok

How can I do this with jQuery?

Thanks!

Body:
Thanks a lot for your response, Henrique. However I couldn't get it to work duo to a "jQuery $.cookie is not a function" error.

I found out that "jQuery Cookie" is deprecated and js-cookie is the new version. By including that and changing the old cookie functions to the new ones it now works perfectly!

This is my final jQuery code, using "js-cookie":

window.addEventListener('load', function(){
    jQuery('#cookie-message-close').click(function(){
        jQuery('#cookie-message').hide();
    });

    if (!Cookies.get("cookie-message-bar"))
    {
        jQuery('#cookie-message').show();
        Cookies.set('cookie-message-bar', true, { expires: 60 });
    }
});

Note that I've changed $ to jQuery because of Wordpress' noConflict() mode, since I'm developing in Wordpress.


问:
onClickListener only works after several clicks
I know this is not a very good problem description, but I stumbled into unstable behavior of my ListAdapter.

The point is, onItemClickListener in my application only responds if furiously clicked sereral times. Debugger also only responds in such situation. Nevertheless, from time to time clicks work just fine. It seems as if something is preventing internally the onItemClickListener from bein called. Sometimes even the default android click animation is not shown on first click. Although, after 2-5 clicks fast one after another is always works as expected.

Being new to Android development, I have no idea where to start looking for the problem. Problem is not device-specific (tested).

Just in case, some code from my project (although I'm not even sure what to provide):

Some code from OffersListAdapter:

```<code>class ViewHolder {
    private TextView whoandWhom;
    private TextView date;
    private TextView distance;

    private TextView status;
    private TextView place;

    private boolean isMeeting = false;
    private Meeting.Status meetingStatus;

    private void color(int color) {
        for (Field v: this.getClass().getDeclaredFields()) {
            try {
                if (v.getType() == TextView.class) {
                    TextView view = (TextView) v.get(this);
                    view.setTextColor(res.getColor(color));
                }
            } catch (IllegalAccessException e) {
                Log.e("ERROR", "This field does not exist");
            }
        }
    }
}
private View prepareHolder(boolean isMeeting, View convertView, Meeting.Status mStatus, Offer offer) {
    ViewHolder holder = new ViewHolder();

    LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (isMeeting) {
        convertView = li.inflate(R.layout.meetings_item, null);
    } else {
        convertView = li.inflate(R.layout.offers_item, null);
    }
    holder.whoandWhom = (TextView)convertView.findViewById(R.id.datetime);
    holder.date = (TextView)convertView.findViewById(R.id.dateTime);
    holder.distance = (TextView)convertView.findViewById(R.id.distance);

    if (isMeeting) {
        holder.isMeeting = true;
        holder.status = (TextView)convertView.findViewById(status);
        holder.place = (TextView)convertView.findViewById(place);
        holder.meetingStatus = mStatus;
    }

    convertView.setTag(holder);

    holder.whoandWhom.setText(offer.getOwnership());
    holder.date.setText(offer.getDateRepresentation());
    String distance = new DecimalFormat("#####.##").format(offer.getDistance()) + " км";
    holder.distance.setText(distance);

    if (isMeeting) {
        Meeting meeting = (Meeting) offer;
        holder.place.setText(meeting.getPlace_name());
        switch (meeting.getStatus()) {
            case pending:
                holder.status.setText("Очікує підтвердження");
                break;
            case upcoming:
                holder.status.setText("Незабаром");
                holder.color(R.color.colorAccent);
                break;
            case completed:
                holder.status.setText("Завершено");
                holder.color(R.color.colorPrimary);
                break;
        }
    }

    return convertView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    Offer offer = this.getItem(position);
    Boolean isMeeting = offer.getClass() == Meeting.class;

    Meeting.Status status = null;
    if (isMeeting)
        status = ((Meeting) offer).getStatus();

    if (convertView == null) {
        convertView = prepareHolder(isMeeting, convertView, status, offer);
    } else {
        holder = (ViewHolder) convertView.getTag();
        if (isMeeting != holder.isMeeting)
            convertView = prepareHolder(isMeeting, convertView, status, offer);
        else if (isMeeting) {
            if (status != holder.meetingStatus)
                convertView = prepareHolder(true, convertView, status, offer);
        }
    }

    return convertView;
}
</code>```

Some methods from MainActivity:

```<code>private void configureOffersOutput() {
    offersOutput = (ListView) findViewById(R.id.offersOutput);
    offersList = new ArrayList<Offer>();

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    loadingView = li.inflate(R.layout.list_footer_view, null);

    adapter = new OffersListAdapter(getApplicationContext(), offersList, getResources());

    configureOnItemClick();
    offersOutput.setAdapter(adapter);

    offersOutput.setNestedScrollingEnabled(true);
    offersOutput.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {}
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (view.getLastVisiblePosition() >= totalItemCount - 1 && !isLoading) {
                moreOffers();
            }
        }
    });
}

private void configureOnItemClick() {

    final Activity a = this;

    offersOutput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final Offer item = offersList.get(position);
            if (item.getClass() == Offer.class) {

                openActivity(a, SuggestActivity.class, new HashMap<String, String>() {{
                    put("id", item.getId());
                    put("location", item.getLocation());
                    put("datetime", item.getDateRepresentation());
                    put("ownership", item.getOwnership());

                    put("currentCoordinates", coordinates);
                    put("token", user.getToken());
                    put("uid", user.getId());
                }});

            } else if (item.getClass() == Meeting.class) {

                final Meeting meeting = (Meeting) item;
                Class<?> name;

                switch (meeting.getStatus()) {
                    case pending:
                        name = ApproveActivity.class;
                        break;
                    case upcoming:
                        name = UpcomingActivity.class;
                        break;
                    case completed:
                        name = RateActivity.class;
                        break;
                    default:
                        name = MeetingActivity.class;
                        Log.e("ERROR", "Wrong status: " + meeting.getStatus().toString());
                }

                final String distance = new DecimalFormat("#####.##").format(meeting.getDistance()) + " км";

                openActivity(a, name, new HashMap<String, String>(){{
                    put("id", meeting.getId());
                    put("datetime", meeting.getDateRepresentation());
                    put("ownership", meeting.getOwnership());

                    put("tel", meeting.getTel());
                    put("distance", distance);
                    put("place", meeting.getPlace_name());
                    put("place_coordinates", meeting.getPlace_coordinates());

                    put("currentCoordinates", coordinates);
                    put("token", user.getToken());
                    put("uid", user.getId());
                }});

            }
        }
    });

    initRefresh();

    isSetItemOnClick = true;
}
</code>```

答:
Okay, so I figured out an answer just in case someone has the same problem.

Besides all this, I had a method responding to scroll events. It would load the data on scroll down like this:

```<code>ffersOutput.setNestedScrollingEnabled(true);
    offersOutput.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {}
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (view.getLastVisiblePosition() >= totalItemCount - 1 && !isLoading) {
                moreOffers();
            }
        }
    });
</code>```

moreOffers would than send a request to backend and load the rows.

The problem was:

DB ran out of rows very quickly, so it would receive empty results

App sent requests so quickly and tried refreshing rows so often that they most of the time wouldn't be able to respond to touches.

Solution (although ugly):
Add to the method which receives data from DB something like this:

```<code>new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        isLoading = false;
    }
}, 100);
</code>```

That prevents app from making requests so often, so it can respond.

Body:
I know this is not a very good problem description, but I stumbled into unstable behavior of my ListAdapter.

The point is, onItemClickListener in my application only responds if furiously clicked sereral times. Debugger also only responds in such situation. Nevertheless, from time to time clicks work just fine. It seems as if something is preventing internally the onItemClickListener from bein called. Sometimes even the default android click animation is not shown on first click. Although, after 2-5 clicks fast one after another is always works as expected.

Being new to Android development, I have no idea where to start looking for the problem. Problem is not device-specific (tested).

Just in case, some code from my project (although I'm not even sure what to provide):

Some code from OffersListAdapter:

class ViewHolder {
    private TextView whoandWhom;
    private TextView date;
    private TextView distance;

    private TextView status;
    private TextView place;

    private boolean isMeeting = false;
    private Meeting.Status meetingStatus;

    private void color(int color) {
        for (Field v: this.getClass().getDeclaredFields()) {
            try {
                if (v.getType() == TextView.class) {
                    TextView view = (TextView) v.get(this);
                    view.setTextColor(res.getColor(color));
                }
            } catch (IllegalAccessException e) {
                Log.e("ERROR", "This field does not exist");
            }
        }
    }
}
private View prepareHolder(boolean isMeeting, View convertView, Meeting.Status mStatus, Offer offer) {
    ViewHolder holder = new ViewHolder();

    LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (isMeeting) {
        convertView = li.inflate(R.layout.meetings_item, null);
    } else {
        convertView = li.inflate(R.layout.offers_item, null);
    }
    holder.whoandWhom = (TextView)convertView.findViewById(R.id.datetime);
    holder.date = (TextView)convertView.findViewById(R.id.dateTime);
    holder.distance = (TextView)convertView.findViewById(R.id.distance);

    if (isMeeting) {
        holder.isMeeting = true;
        holder.status = (TextView)convertView.findViewById(status);
        holder.place = (TextView)convertView.findViewById(place);
        holder.meetingStatus = mStatus;
    }

    convertView.setTag(holder);

    holder.whoandWhom.setText(offer.getOwnership());
    holder.date.setText(offer.getDateRepresentation());
    String distance = new DecimalFormat("#####.##").format(offer.getDistance()) + " км";
    holder.distance.setText(distance);

    if (isMeeting) {
        Meeting meeting = (Meeting) offer;
        holder.place.setText(meeting.getPlace_name());
        switch (meeting.getStatus()) {
            case pending:
                holder.status.setText("Очікує підтвердження");
                break;
            case upcoming:
                holder.status.setText("Незабаром");
                holder.color(R.color.colorAccent);
                break;
            case completed:
                holder.status.setText("Завершено");
                holder.color(R.color.colorPrimary);
                break;
        }
    }

    return convertView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    Offer offer = this.getItem(position);
    Boolean isMeeting = offer.getClass() == Meeting.class;

    Meeting.Status status = null;
    if (isMeeting)
        status = ((Meeting) offer).getStatus();

    if (convertView == null) {
        convertView = prepareHolder(isMeeting, convertView, status, offer);
    } else {
        holder = (ViewHolder) convertView.getTag();
        if (isMeeting != holder.isMeeting)
            convertView = prepareHolder(isMeeting, convertView, status, offer);
        else if (isMeeting) {
            if (status != holder.meetingStatus)
                convertView = prepareHolder(true, convertView, status, offer);
        }
    }

    return convertView;
}

Some methods from MainActivity:

private void configureOffersOutput() {
    offersOutput = (ListView) findViewById(R.id.offersOutput);
    offersList = new ArrayList<Offer>();

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    loadingView = li.inflate(R.layout.list_footer_view, null);

    adapter = new OffersListAdapter(getApplicationContext(), offersList, getResources());

    configureOnItemClick();
    offersOutput.setAdapter(adapter);

    offersOutput.setNestedScrollingEnabled(true);
    offersOutput.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {}
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (view.getLastVisiblePosition() >= totalItemCount - 1 && !isLoading) {
                moreOffers();
            }
        }
    });
}

private void configureOnItemClick() {

    final Activity a = this;

    offersOutput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final Offer item = offersList.get(position);
            if (item.getClass() == Offer.class) {

                openActivity(a, SuggestActivity.class, new HashMap<String, String>() {{
                    put("id", item.getId());
                    put("location", item.getLocation());
                    put("datetime", item.getDateRepresentation());
                    put("ownership", item.getOwnership());

                    put("currentCoordinates", coordinates);
                    put("token", user.getToken());
                    put("uid", user.getId());
                }});

            } else if (item.getClass() == Meeting.class) {

                final Meeting meeting = (Meeting) item;
                Class<?> name;

                switch (meeting.getStatus()) {
                    case pending:
                        name = ApproveActivity.class;
                        break;
                    case upcoming:
                        name = UpcomingActivity.class;
                        break;
                    case completed:
                        name = RateActivity.class;
                        break;
                    default:
                        name = MeetingActivity.class;
                        Log.e("ERROR", "Wrong status: " + meeting.getStatus().toString());
                }

                final String distance = new DecimalFormat("#####.##").format(meeting.getDistance()) + " км";

                openActivity(a, name, new HashMap<String, String>(){{
                    put("id", meeting.getId());
                    put("datetime", meeting.getDateRepresentation());
                    put("ownership", meeting.getOwnership());

                    put("tel", meeting.getTel());
                    put("distance", distance);
                    put("place", meeting.getPlace_name());
                    put("place_coordinates", meeting.getPlace_coordinates());

                    put("currentCoordinates", coordinates);
                    put("token", user.getToken());
                    put("uid", user.getId());
                }});

            }
        }
    });

    initRefresh();

    isSetItemOnClick = true;
}

Body:
Okay, so I figured out an answer just in case someone has the same problem.

Besides all this, I had a method responding to scroll events. It would load the data on scroll down like this:

ffersOutput.setNestedScrollingEnabled(true);
    offersOutput.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {}
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (view.getLastVisiblePosition() >= totalItemCount - 1 && !isLoading) {
                moreOffers();
            }
        }
    });

moreOffers would than send a request to backend and load the rows.

The problem was:

DB ran out of rows very quickly, so it would receive empty results

App sent requests so quickly and tried refreshing rows so often that they most of the time wouldn't be able to respond to touches.

Solution (although ugly):
Add to the method which receives data from DB something like this:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        isLoading = false;
    }
}, 100);

That prevents app from making requests so often, so it can respond.


问:
replace all word occurrence in list with index of items in another list
I have a list -

```<code>A=["hi how are you","have good day","where are you going ","do you like the place"]
</code>```

and another list -

```<code>B=["how","good","where","going","like","place"]
</code>```

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

```<code>["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]
</code>```

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

```<code>for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)
</code>```

答:
Hi your solution is making (too) many lookups.

here is mine:

```<code>A=["hi how are you",
   "have good day",
   "where are you going ",
   "do you like the place"]

B=["how","good","where","going","like","place"]

# I assume B contains only unique elements.

gg = { word: idx for (idx, word) in enumerate(B, start=1)}
print(gg)

lookup = lambda word: str(gg.get(word, 0)) # Buils your index and gets you efficient search with proper object types.

def translate(str_):
    return ' '.join(lookup(word) for word in str_.split())

print(translate("hi how are you")) # check for one sentence.

translated =  [translate(sentence) for sentence in A] # yey victory.

print(translated)

# Advanced usage

class  missingdict(dict):
    def __missing__(self, key):
        return 0

miss = missingdict(gg)

def tr2(str_):
    return ' '.join(str(miss[word]) for word in str_.split())

print([tr2(sentence) for sentence in A])
</code>```

You may also be using the yield keyword when you will be more self-confident in python.

Body:
I have a list -

A=["hi how are you","have good day","where are you going ","do you like the place"]

and another list -

B=["how","good","where","going","like","place"]

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)

Body:
Hi your solution is making (too) many lookups.

here is mine:

A=["hi how are you",
   "have good day",
   "where are you going ",
   "do you like the place"]

B=["how","good","where","going","like","place"]

# I assume B contains only unique elements.

gg = { word: idx for (idx, word) in enumerate(B, start=1)}
print(gg)

lookup = lambda word: str(gg.get(word, 0)) # Buils your index and gets you efficient search with proper object types.

def translate(str_):
    return ' '.join(lookup(word) for word in str_.split())

print(translate("hi how are you")) # check for one sentence.

translated =  [translate(sentence) for sentence in A] # yey victory.

print(translated)

# Advanced usage

class  missingdict(dict):
    def __missing__(self, key):
        return 0

miss = missingdict(gg)

def tr2(str_):
    return ' '.join(str(miss[word]) for word in str_.split())

print([tr2(sentence) for sentence in A])

You may also be using the yield keyword when you will be more self-confident in python.


问:
How to get total numbers of digits used in an integer in c language?
We all know that we can get numbers of characters in an string using strlen() function, but if I want to get a number of the digits used in an integer, how can I do it?

Like if there is 1000 stored in a variable a and that variable is an integer type, I want to get length of the number and that is 4.

答:
What you're asking for is the number of decimal digits.  Integers are stored in a binary format, so there's no built-in way of determining that.  What you can do to count the decimal digits is count how many times you can divide by 10.

```<code>int count = 1;
while (a >= 10) {
    a /= 10;
    count++;
}
</code>```

Body:
What you're asking for is the number of decimal digits.  Integers are stored in a binary format, so there's no built-in way of determining that.  What you can do to count the decimal digits is count how many times you can divide by 10.

int count = 1;
while (a >= 10) {
    a /= 10;
    count++;
}


问:
Explanation of Offset algorithm
I have a small problem. I am trying to build my own cnc and implement offset algorithm, but i am not able to understand what "TIP", "FIP" mean. This seems so complicated!
This is the link to description this algorithm:
Here's a link
I will be very grateful for your help!</p>

答:
The definitions reads: If the intersection point obtained by extended intersecting is on the line segment/arc, then the point is called a true intersection point (TIP). Otherwise, it is called a false intersection point (FIP).

My interpretation is that a TIP is a point on a segment (line or arc) that intersects with another segment or an extension of it. A FIP is an intersection of two extended segments that does not lie on any of them.

I agree with you, the definition is not clear (which is not good for a definition). Another interpretation (coming from the names rather than from the wording) would be that a TIP is the intersection of two segments and a FIP is the projected intersection of their extensions. My recommendation is to bear both interpretations in mind and keep reading until the definitions become clearer from their actual use.

Title: Explanation of Offset algorithm


问:
mysql lookup table schema
What's a more detailed command for seeing table properties than show tables? In particular, I need to know what storage engines are being used in a database that I've inherited.

答:
```<code>show table status like '<tablename>'
show create table <tablename>
describe <tablename>
show indexes from <tablename>
</code>```

Title: mysql lookup table schema


问:
React: Pass Function with JSON Data
I am trying to generate components from a JSON file with React-Native, and am wondering what is the best way to pass a function to a component as a prop?

Example, button requires the prop onPress, so is there a way to pass in a function to the object onPress as I have done here:

```<code>{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: {() => {Alert.alert("Tapped!")}}
      }
}
</code>```

As this generates an unexpected token error, what is a better way to accomplish this?

答:
You have extra curly brackets around the function declaration that are invalid. Remove those, and you should be good:</p>

```<code>{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: () => {Alert.alert("Tapped!")}
      }
}
</code>```

Title: React: Pass Function with JSON Data

Body:
I am trying to generate components from a JSON file with React-Native, and am wondering what is the best way to pass a function to a component as a prop?

Example, button requires the prop onPress, so is there a way to pass in a function to the object onPress as I have done here:

{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: {() => {Alert.alert("Tapped!")}}
      }
}

As this generates an unexpected token error, what is a better way to accomplish this?

Body:
You have extra curly brackets around the function declaration that are invalid. Remove those, and you should be good:

{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: () => {Alert.alert("Tapped!")}
      }
}


问:
Canvas height and width
When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions.
Why is this happening and how can I fix this?</p>

答:
You can also do this by using pure javascript and set the dimensions of the canvas in javascript depending on your CSS values:

```<code>//Get Canvas
var canvas = document.getElementById("canv");

// Get computed style of the canvas element.
var cstyle = window.getComputedStyle(canvas);

// Returns the width as str in px: e.g. 600px.
// Parse resolves that issue.
canv.width = parseInt(cstyle.width);
canv.height = parseInt(cstyle.height);
</code>```

Demo:
https://jsfiddle.net/ofaghxfq/2/

Title: Canvas height and width

Body:
You can also do this by using pure javascript and set the dimensions of the canvas in javascript depending on your CSS values:

//Get Canvas
var canvas = document.getElementById("canv");

// Get computed style of the canvas element.
var cstyle = window.getComputedStyle(canvas);

// Returns the width as str in px: e.g. 600px.
// Parse resolves that issue.
canv.width = parseInt(cstyle.width);
canv.height = parseInt(cstyle.height);

Demo:
https://jsfiddle.net/ofaghxfq/2/


问:
Library is not writable
I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

```<code>install.packages("randomForest")
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages :
  'lib = "/usr/local/lib/R/site-library"' is not writable
</code>```

How to resolve it?

答:
You can change permission to 'site-library' and all included directories.

sudo chmod 777 -R /usr/local/lib/R/site-library

OwnerDisplayName: Priya

Title: Library is not writable

Body:
I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

install.packages("randomForest")
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages :
  'lib = "/usr/local/lib/R/site-library"' is not writable

How to resolve it?


问:
select column names containing string programmatically
Given a data frame like:

```<code>df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)
</code>```

I can select columns names that contain a character with:

```<code>library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4
</code>```

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

```<code>searchfor <- letters[1:2]
</code>```

Using searchfor, I'd like to make the following expression and use it in a select statement:

```<code>E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)
</code>```

答:
Self answer - here's a solution with select_ and that still uses contains - just in case anyone else is interested:

```<code>library(iterators)
library(dplyr)
s <- paste0("c(", paste0(sapply(iter(searchfor), function(x) paste0("contains(\"", x, "\")")), collapse=","), ")")
df %>% select_(., s)

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4
</code>```

Body:
Given a data frame like:

df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)

I can select columns names that contain a character with:

library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

searchfor <- letters[1:2]

Using searchfor, I'd like to make the following expression and use it in a select statement:

E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)

Body:
Self answer - here's a solution with select_ and that still uses contains - just in case anyone else is interested:

library(iterators)
library(dplyr)
s <- paste0("c(", paste0(sapply(iter(searchfor), function(x) paste0("contains(\"", x, "\")")), collapse=","), ")")
df %>% select_(., s)

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4


问:
Reduce execution time of prime number generator
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

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

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}
</code>```

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?

答:
As @Carcigenicate suggests, you're exceeding the time limit because your prime generator is too slow; and it's too slow since you're using an inefficient algorithm.

Indeed, you should not simply test each consecutive number for primality (which, by the way, you're also doing ineffectively), but rather rule out multiple values at once using known primes (and perhaps additional primes which you compute). For example, you don't need to check multiples of 5 and 10 (other than the actual value 5) for primality, since you know that 5 divides them. So just "mark" the multiples of various primes as irrelevant.

... and of course, that's just for getting you started, there are all sort of tricks you could use for optimization - algorithmic and implementation-related.

Body:
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

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

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?


问:
Make whole page non-interactive except for one element
How would I make a webpage completely non-interactive to the user, but make one div (or other element) interactive?</p>

答:
#blocker {
    position:fixed;
    padding:0;
    margin:0;

    top:0;
    left:0;

    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.2);
    z-index: 1;
}

.allow {
    position:absolute;
    padding:0;
    margin:0;

    top:50%;
    left:50%;

    background:red;
    z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
content to block
</p>
<div id="blocker">

</div>
<div class="allow">

<p>
Content to allow
</p>
</div></code>```

Body:
#blocker {
    position:fixed;
    padding:0;
    margin:0;

    top:0;
    left:0;

    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.2);
    z-index: 1;
}

.allow {
    position:absolute;
    padding:0;
    margin:0;

    top:50%;
    left:50%;

    background:red;
    z-index: 1;
}

<p>
content to block
</p>
<div id="blocker">

</div>
<div class="allow">

<p>
Content to allow
</p>
</div>


问:
Error: Found interface org.apache.hadoop.mapreduce.Counter, but class was expected
I've tried to run Coordinate Descent Tensor Factorization(CDTF) via Hadoop 2.7.2

The CDTF src code can get this page: http://www.cs.cmu.edu/~kijungs/codes/cdtf/

When I run CDTF mr(MapReduce) version algorithm, I get the error in step Start Bias-CDTF

I really don't know why the error occurs.

Is there a good solution to solve this error?

答:
You have an issue with versions of dependencies, one of the libraries that expects org.apache.hadoop.mapreduce.Counter to be a class was most probably compiled against old version of Apache Hadoop, e.g.

version 2.4.1 defines interface https://hadoop.apache.org/docs/r2.4.1/api/org/apache/hadoop/mapreduce/Counter.html

version 1.2.1 defines class https://hadoop.apache.org/docs/r1.2.1/api/org/apache/hadoop/mapreduce/Counter.html

You should either update the version of library that expects Counter to be a class (most probably there is a newer version that already support version Hadoop 2.* and works with interface), or if this is not possible - downgrade your dependencies and use version 1.* of Apache Hadoop library


问:
Generate variant strings based on replacement dictionary for some words only in Python
Given a string and a word replacement dictionary, I'm trying to get python to return all variant strings. E.g. for the string "One went to market", and the replacement dict {'One': ['One','Two','Three'], 'market': ['town','bed']} I want to return: ['One went to town','Two went to town','Three went to town', One went to bed','Two went to bed','Three went to bed']. Currently I have this working only when there are two replacement options.

My partially working approach uses word lists generated from the dictionary, e.g. in the example above, I have ['One,Two,Three','went','to','town,bed']. This this:

```<code>def perm(wordlist):
    a=[[]]
    for i in wordlist:
        if ',' in i:
            wds=i.split(',')
            for alis in a:
                alis.append(wds[0])
            for j in wds[1:]:
                b=[x[:-1] for x in a]
                for alis in b:
                    alis.append(j)
                    a=a+b
        else:
            for alis in a:
                alis.append(i)
    return a
</code>```

for ['One,Two','went','to','town,bed'] I get the required result, but any time there's more than two options it's haywire.

答:
Supposedly you have these:

```<code>string = "One went to market"
dict_repl = {'One':['One','Two','Three'],'market':['town','bed']}
</code>```

you can get your expected result using this one liner using string comprehension and str.replace:

```<code>result = [string.replace('market',v).replace('One',i) for v in dict_repl['market'] for i in dict_repl['One']]
</code>```

output:

```<code>['One went to town', 'Two went to town', 'Three went to town', 'One went to bed', 'Two went to bed', 'Three went to bed']
</code>```

I believe this is what you're asking for.

Body:
Given a string and a word replacement dictionary, I'm trying to get python to return all variant strings. E.g. for the string "One went to market", and the replacement dict {'One': ['One','Two','Three'], 'market': ['town','bed']} I want to return: ['One went to town','Two went to town','Three went to town', One went to bed','Two went to bed','Three went to bed']. Currently I have this working only when there are two replacement options.

My partially working approach uses word lists generated from the dictionary, e.g. in the example above, I have ['One,Two,Three','went','to','town,bed']. This this:

def perm(wordlist):
    a=[[]]
    for i in wordlist:
        if ',' in i:
            wds=i.split(',')
            for alis in a:
                alis.append(wds[0])
            for j in wds[1:]:
                b=[x[:-1] for x in a]
                for alis in b:
                    alis.append(j)
                    a=a+b
        else:
            for alis in a:
                alis.append(i)
    return a

for ['One,Two','went','to','town,bed'] I get the required result, but any time there's more than two options it's haywire.

Body:
Supposedly you have these:

string = "One went to market"
dict_repl = {'One':['One','Two','Three'],'market':['town','bed']}

you can get your expected result using this one liner using string comprehension and str.replace:

result = [string.replace('market',v).replace('One',i) for v in dict_repl['market'] for i in dict_repl['One']]

output:

['One went to town', 'Two went to town', 'Three went to town', 'One went to bed', 'Two went to bed', 'Three went to bed']

I believe this is what you're asking for.


问:
Live jQuery events not firing for dynamic element
Why are none of the live (or dead) events I bind to a dynamic element firing?

```<code>(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);
</code>```

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

```<code>var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});
</code>```

答:
The live method works with selectors, not detached elements.

You can handle the normal (non-live) click event, and it should work fine.

Body:
Why are none of the live (or dead) events I bind to a dynamic element firing?

(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});


答:
Not really sure if I got your question right, but given your example, as far as I could understand you want to know how many digits there are in a given number (for example: 1 has one digit, 10 has two digits, 100 has three digits, so on...). You can achieve it using something like this:</p>

```<code>#include <stdio.h>
int main(void){
    int numberOfDigits = 0, value;
    scanf("%d", &value); //you scan a value
    if (value == 0)
        numberOfDigits = 1;
    else{
        while (value != 0){
            numberOfDigits++;
            value = value / 10;
        }
     }
     printf("Number of digits: %d\n", numberOfDigits);
     return 0;
}
</code>```

Title: How to get total numbers of digits used in an integer in c language?

Body:
We all know that we can get numbers of characters in an string using strlen() function, but if I want to get a number of the digits used in an integer, how can I do it?

Like if there is 1000 stored in a variable a and that variable is an integer type, I want to get length of the number and that is 4.

Body:
Not really sure if I got your question right, but given your example, as far as I could understand you want to know how many digits there are in a given number (for example: 1 has one digit, 10 has two digits, 100 has three digits, so on...). You can achieve it using something like this:

#include <stdio.h>
int main(void){
    int numberOfDigits = 0, value;
    scanf("%d", &value); //you scan a value
    if (value == 0)
        numberOfDigits = 1;
    else{
        while (value != 0){
            numberOfDigits++;
            value = value / 10;
        }
     }
     printf("Number of digits: %d\n", numberOfDigits);
     return 0;
}


问:
how to optimise a view having derived tabels
I have a situation , i have one view , whose structure is like following

```<code>select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid

where x.country =1

  I am calling it like so, select * from view1 where country=1
</code>```

q1) I have seen the plan, it filters on table x but  it takes time in left join, because it gets whole data and then pivot it,

if i could put the filter y.country =1 in side,
then it would have been fast.

```<code> but that can not be done as view does not take parameter.
</code>```

so please suggest is there any way to speed up the view.

yours sincerely

答:
Due to missing of important info regarding this question (full source code of query + estimated/actual execution plan) my best guess/solution is: I would move JOIN predicate inside of PIVOT source thus: instead of

```<code>select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid -- <-- This predicate
...
</code>```

I would use

```<code>select x.*,d.*

from x

outer apply (

select x, y,z,poleid
from (
  select ....
  from ...
  where x.poleid=d.poleid -- <-- This predicate
) AS a--lias
PIVOT ( .... ) -- and pivot is done here

) as d
...
</code>```

Also, check if d.poleid column has an covering index thus:

```<code>CREATE /*UNIQUE*/ INDEX ...
ON d -- replace alias with full table name
(poleid, ... other columns ? ...)
--INCLUDE (... covering columns ...)
</code>```

Body:
I have a situation , i have one view , whose structure is like following

select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid

where x.country =1

  I am calling it like so, select * from view1 where country=1

q1) I have seen the plan, it filters on table x but  it takes time in left join, because it gets whole data and then pivot it,

if i could put the filter y.country =1 in side,
then it would have been fast.

 but that can not be done as view does not take parameter.

so please suggest is there any way to speed up the view.

yours sincerely

Body:
Due to missing of important info regarding this question (full source code of query + estimated/actual execution plan) my best guess/solution is: I would move JOIN predicate inside of PIVOT source thus: instead of

select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid -- <-- This predicate
...

I would use

select x.*,d.*

from x

outer apply (

select x, y,z,poleid
from (
  select ....
  from ...
  where x.poleid=d.poleid -- <-- This predicate
) AS a--lias
PIVOT ( .... ) -- and pivot is done here

) as d
...

Also, check if d.poleid column has an covering index thus:

CREATE /*UNIQUE*/ INDEX ...
ON d -- replace alias with full table name
(poleid, ... other columns ? ...)
--INCLUDE (... covering columns ...)


问:
Get uri parameter with javascript than return it to new url?
im not that familir with javascript but i need some help . Basically i have this scenario : i want to get a parameter from url , lets say http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER here also i have a javascript code which redirects to a second site , lets say mysite2.com/path1 , so what i need is when mysite1 redirects to mysite2 i want it also to return http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER , where #me parameter value is the same.</p>

答:
Check the following code: First you must get the url via window.location.href method. Then I make  a function using regex obj with two arguments. First the url string and second the name of the url parameter that i want to get.

var url_string = "http://localhost:9080/l?state=12345&code=my_code_here";

function getValueUrl(url,name){
   var a=new RegExp(name+'=([^&]+)');
    a=a.exec(url)[1];
      return a;
}

console.log(getValueUrl(url_string, 'code'));```


问:
Refactoring two methods using indexOf
These two methods are almost identical, how could they be refactored into one method?</p>

```<code>method1 = (value) => {
    var example =  array.filter(row => row.key.indexOf(value) > -1);
    this.setState({state: example});
}

method2 = (value) => {
    var example =  array.filter(row => row.otherKey.indexOf(value) > -1);
    this.setState({otherState: example});
}
</code>```

答:
Take what varies between the two functions and separate it from the function by making those items arguments that must be passed into the function:</p>

```<code>var method = (value, key, state) => {
    var example =  array.filter(row => row[key].indexOf(value) > -1);
    this.setState({state: example});
}
</code>```

Title: Refactoring two methods using indexOf

Body:
These two methods are almost identical, how could they be refactored into one method?

method1 = (value) => {
    var example =  array.filter(row => row.key.indexOf(value) > -1);
    this.setState({state: example});
}

method2 = (value) => {
    var example =  array.filter(row => row.otherKey.indexOf(value) > -1);
    this.setState({otherState: example});
}

Body:
Take what varies between the two functions and separate it from the function by making those items arguments that must be passed into the function:

var method = (value, key, state) => {
    var example =  array.filter(row => row[key].indexOf(value) > -1);
    this.setState({state: example});
}


问:
md-table in Angular Material 2
I am working with Angular Material Table. In Html code, there is

<ng-container cdkColumnDef="userId">
  <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
  <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>
```

I found out that cdkHeaderCellDef and cdkCellDef are from CDK Table

I am getting error saying "Can't bind to 'cdkHeaderRowDef' since it isn't a known property of 'md-header-row'."

How can I solve this ?

答:
The cdkHeaderCellDef and cdkCellDef are part of the @angular/cdk library and exported in the CdkTableModule.

Include this module in your app's imports

Title: md-table in Angular Material 2

Body:
I am working with Angular Material Table. In Html code, there is

<ng-container cdkColumnDef="userId">
  <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
  <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>

I found out that cdkHeaderCellDef and cdkCellDef are from CDK Table

I am getting error saying "Can't bind to 'cdkHeaderRowDef' since it isn't a known property of 'md-header-row'."

How can I solve this ?