问:
Invalid datetime format: 1292 Incorrect datetime value - Laravel 5.2
I'm getting this error when I insert these value into my database table:

```
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:
'24/06/2017' for column 'registration_from' at row 1
(SQL: insert into `campus_registrations` (`campus_major_class_id`,
`registration_from`, `registration_to`, `testing`, `announcement`,
`enrollment_from`, `enrollment_to`, `updated_at`, `created_at`) values (3,
24/06/2017, 27/06/2017, 13/07/2017, 01/08/2017, 05/09/2017, 31/01/2018,
 2017-06-07 09:39:31, 2017-06-07 09:39:31))
```

Do I have to intiate the datetime first or what?

答:
Reference

MYSQL recognises date value in either YYYY-MM-DD or YY-MM-DD format. You can use /. This 24/06/2017 considered invalid. Try 2017/06/24

Body:
I'm getting this error when I insert these value into my database table:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:
'24/06/2017' for column 'registration_from' at row 1
(SQL: insert into `campus_registrations` (`campus_major_class_id`,
`registration_from`, `registration_to`, `testing`, `announcement`,
`enrollment_from`, `enrollment_to`, `updated_at`, `created_at`) values (3,
24/06/2017, 27/06/2017, 13/07/2017, 01/08/2017, 05/09/2017, 31/01/2018,
 2017-06-07 09:39:31, 2017-06-07 09:39:31))

Do I have to intiate the datetime first or what?


来源: stackexchange

问:
spring data jpa limit pagesize, how to set to maxSize
I have one requirement is to search by pageable and non-pageable,

and in my Java code, I use spring data jpa Pageable class,

```<code> Pageable pageable = new PageRequest(
                    queryForm.getPageNumber()- 1, queryForm.getPageSize(),Sort.Direction.ASC,"id");
Page page = repository.fullTextSearch(queryForm.getText(), pageable);
</code>```

And I don't want to change the return structure,

So when non-pageable situation (search all), how to set the pageSize value to MAX ?

答:
This works for me:

All pageable request use MyCustomPage and use a default page and size if not found in request.

If size (number of record exceed the max value) i set a default value, which in this case 50.

```<code>public class MyCustomPage extends PageRequest{
    Integer MAX_PAGE_SIZE = 50
    //constructor
    public MyCustomPage(Integer page, Integer size) {
        super(page,(size>MAX_PAGE_SIZE)?MAX_PAGE_SIZE:size);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one requirement is to search by pageable and non-pageable,

and in my Java code, I use spring data jpa Pageable class,

 Pageable pageable = new PageRequest(
                    queryForm.getPageNumber()- 1, queryForm.getPageSize(),Sort.Direction.ASC,"id");
Page page = repository.fullTextSearch(queryForm.getText(), pageable);

And I don't want to change the return structure,

So when non-pageable situation (search all), how to set the pageSize value to MAX ?

Body:
This works for me:

All pageable request use MyCustomPage and use a default page and size if not found in request.

If size (number of record exceed the max value) i set a default value, which in this case 50.

public class MyCustomPage extends PageRequest{
    Integer MAX_PAGE_SIZE = 50
    //constructor
    public MyCustomPage(Integer page, Integer size) {
        super(page,(size>MAX_PAGE_SIZE)?MAX_PAGE_SIZE:size);
    }
}


问:
mysql class not found in dynamic web maven project?
First I created simple java maven project in eclipse. Then I added mysql dependency in pom.xml. Then I wrote a function where I was creating connection and fetching some data from mysql db. I wrote main function in that class to test it. It was working.

Then to accept user request I have added dynamic web facet in maven. Then I wrote a servlet. In that servlet I just copied the code which I wrote in main function(previously defind class).But when I hit the servlet, the user console prints com.mysql.jdbc.driver not found. How is that even possible. Because it's working in other class.

答:
To start with, the jar that I need to connect to MySQL 5.5 should have been mysql-connector-java-5.1.15-bin.jar but not mysql-connector-java-5.1.15.jar. Secondly, this jar is not available in maven repository so I needed to manually add it to my local maven repository and then added it as a dependency in my pom.xml.

Adding mysql-connector-java-5.1.15-bin.jar to the local maven repository by

mvn install:install-file -Dfile=C:\Libraries\mysql-connector-java-5.1.15-bin\mysql-connector-java-5.1.15-bin.jar -DgroupId=mysql -DartifactId=mysql-connector-java -Dversion=5.1.15-bin -Dpackaging=jar

and then adding the following dependency to pom.xml of the project.

```<code><!-- MySql 5.5 Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.15-bin</version>
</dependency>
</code>```

Body:
To start with, the jar that I need to connect to MySQL 5.5 should have been mysql-connector-java-5.1.15-bin.jar but not mysql-connector-java-5.1.15.jar. Secondly, this jar is not available in maven repository so I needed to manually add it to my local maven repository and then added it as a dependency in my pom.xml.

Adding mysql-connector-java-5.1.15-bin.jar to the local maven repository by

mvn install:install-file -Dfile=C:\Libraries\mysql-connector-java-5.1.15-bin\mysql-connector-java-5.1.15-bin.jar -DgroupId=mysql -DartifactId=mysql-connector-java -Dversion=5.1.15-bin -Dpackaging=jar

and then adding the following dependency to pom.xml of the project.

<!-- MySql 5.5 Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.15-bin</version>
</dependency>


问:
find data in json data in Javascript
I want to fetch some data from json file in Javascript

I have json data like this :

```<code>var bib = {
"AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
},
"Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"

},
"Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves",

}
</code>```

how can I fetch data like this in js:

```<code>    var keywords = {
    "keywords-name": { // keywords-name as example : virtual reality
        "repeat": "??"

    },
    "keywords-name2": {
       "repeat": "??"
       },
    "keywords-name3": {
       "repeat": "??"
}, ...
</code>```

I don't know how to do this in javascript..

答:
Using

Object.keys(),

Array.prototype.reduce(),

Array.prototype.forEach() and

String.prototype.split(),

you can do it like this:

var bib = {
  "AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
  },
  "Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"
  },
  "Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves"
  }
};

var keywords = Object.keys(bib).reduce((a, v) => {
  bib[v].keywords.split(/\s*,\s*/).forEach(kw => {
    a[kw] = a[kw] || {repeat: 0};
    a[kw].repeat++;
  });

  return a;
}, {});

console.log(keywords)```

Title: find data in json data in Javascript

Body:
I want to fetch some data from json file in Javascript

I have json data like this :

var bib = {
"AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
},
"Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"

},
"Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves",

}

how can I fetch data like this in js:

    var keywords = {
    "keywords-name": { // keywords-name as example : virtual reality
        "repeat": "??"

    },
    "keywords-name2": {
       "repeat": "??"
       },
    "keywords-name3": {
       "repeat": "??"
}, ...

I don't know how to do this in javascript..


问:
Django - How to add data to a ManyToMany field model?
I have the following models, view and template:

models.py:

```<code>class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id
</code>```

views.py:

```<code>def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})
</code>```

snippet from template:

```<code><form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">
    <table class="table table-striped" id="myTable">
        <tr>
            <th>ID</th>
            <th>Material ID</th>
            <th>Series Title</th>
            <th>Season Tile</th>
            <th>Season Number</th>
            <th>Episode Title</th>
            <th>Episode Number</th>
            <th>Create Batch</th>
        </tr>
        {%  for i in assets %}<tr>
            <td>{{i.pk}}</td>
            <td><a href="/repo/{{ i.id}}">{{i.material_id}}</a></td>
            <td>{{i.series_title}}</td>
            <td>{{i.season_title}}</td>
            <td>{{i.season_number}}</td>
            <td>{{i.episode_title}}</td>
            <td>{{i.episode_number}}</td>
            <td>
                <input type="checkbox" name="batch" value="{{i.pk}}">
            </td>
        </tr>{% endfor %}
    </table>
    </form>
</code>```

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

答:
```<code>info = Batch.objects.create(season_title ='foo', .....)
info2= AssetMetadata.objects.create(material_id ='some')
info.material_id.add(info2)
</code>```

try something like this

Body:
I have the following models, view and template:

models.py:

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

views.py:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})

snippet from template:

<form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">

            ID
            Material ID
            Series Title
            Season Tile
            Season Number
            Episode Title
            Episode Number
            Create Batch

        {%  for i in assets %}

            {{i.pk}}
            {{i.material_id}}
            {{i.series_title}}
            {{i.season_title}}
            {{i.season_number}}
            {{i.episode_title}}
            {{i.episode_number}}

                <input type="checkbox" name="batch" value="{{i.pk}}">

{% endfor %}

    </form>

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

Body:
info = Batch.objects.create(season_title ='foo', .....)
info2= AssetMetadata.objects.create(material_id ='some')
info.material_id.add(info2)

try something like this


问:
Simplifying or improving a method
The following code is executed before the model is saved. It checks a has_many association for change before looping through and setting a value on each. It checks through each answer option whether the correct_answer is changed on any of the answers. If so, it looks for which was changed and was true.

```<code>if self.answer_options.select{|a| a.correct_answer_changed?}.any?
  self.answer_options.each do |answer_option|
    if answer_option.correct_answer_changed? && !answer_option.correct_answer_was
      answer_option.correct_answer = true
    else
      answer_option.correct_answer = false
    end
  end
end
</code>```

How could I simplify or improve this method?

答:
Assuming the code you have shared is working, I would dry it up a bit as..</p>

```<code>self.answer_options.map{|a| a if a.correct_answer_changed?}.compact.each do |answer_option|
  answer_option.toggle(:correct_answer)
end
</code>```

Title: Simplifying or improving a method

Body:
The following code is executed before the model is saved. It checks a has_many association for change before looping through and setting a value on each. It checks through each answer option whether the correct_answer is changed on any of the answers. If so, it looks for which was changed and was true.

if self.answer_options.select{|a| a.correct_answer_changed?}.any?
  self.answer_options.each do |answer_option|
    if answer_option.correct_answer_changed? && !answer_option.correct_answer_was
      answer_option.correct_answer = true
    else
      answer_option.correct_answer = false
    end
  end
end

How could I simplify or improve this method?

Body:
Assuming the code you have shared is working, I would dry it up a bit as..

self.answer_options.map{|a| a if a.correct_answer_changed?}.compact.each do |answer_option|
  answer_option.toggle(:correct_answer)
end


问:
Sorting pandas dataframe by multiple columns ignoring case
I have a dataframe in a Python script (using pandas) that needs to be sorted by multiple columns, but the case of the values currently messes up the sorting. For example a and A are not equally sorted. First, the upper-case letters are sorted and then the lower-case ones. Is there any easy way to sort them ignoring case. Currently I have something like this:

```<code>df = df.sort(['column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'column7'], ascending=[True, True, True, True, True, True, True])
</code>```

It is important that the case needs to be ignored for all of the columns and the values mustn't change their case in the final sorted dataframe.

For example column 1 could be sorted like this (ignoring case):

```<code>Aaa
aaB
aaC
Bbb
bBc
bbD
CCc
ccd
</code>```

Also, it would be awesome, if the functionality would work with x number of columns (no hard-coding).

答:
if you just want to sort according to lower, you could use something like this:

```<code>def sort_naive_lowercase(df, columns, ascending=True):
    df_temp = pd.DataFrame(index = df.index, columns=columns)

    for kol in columns:
        df_temp[kol] = df[kol].str.lower()
    new_index = df_temp.sort_values(columns, ascending=ascending).index
    return df.reindex(new_index)
</code>```

If you expect unicode problems, you might do something like this (borrowing from @nick-hale's comment):

```<code>def sort_by_caseless_columns(df, columns, ascending=True):
    # https://stackoverflow.com/a/29247821/1562285
    import unicodedata

    def normalize_caseless(text):
        return unicodedata.normalize("NFKD", text.casefold())
    df_temp = pd.DataFrame(index = df.index, columns=columns)

    for kol in columns:
        df_temp[kol] = df[kol].apply(normalize_caseless)
    new_index = df_temp.sort_values(columns, ascending=ascending).index
    return df.reindex(new_index)
</code>```

If you have more possible arguments to pass to the sort_values, you can use **kwargs

If not all the columns are strings, but some are numerical, you might have to include an additional mask or set for the non-numerical columns

Body:
I have a dataframe in a Python script (using pandas) that needs to be sorted by multiple columns, but the case of the values currently messes up the sorting. For example a and A are not equally sorted. First, the upper-case letters are sorted and then the lower-case ones. Is there any easy way to sort them ignoring case. Currently I have something like this:

df = df.sort(['column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'column7'], ascending=[True, True, True, True, True, True, True])

It is important that the case needs to be ignored for all of the columns and the values mustn't change their case in the final sorted dataframe.

For example column 1 could be sorted like this (ignoring case):

Aaa
aaB
aaC
Bbb
bBc
bbD
CCc
ccd

Also, it would be awesome, if the functionality would work with x number of columns (no hard-coding).

Body:
if you just want to sort according to lower, you could use something like this:

def sort_naive_lowercase(df, columns, ascending=True):
    df_temp = pd.DataFrame(index = df.index, columns=columns)

    for kol in columns:
        df_temp[kol] = df[kol].str.lower()
    new_index = df_temp.sort_values(columns, ascending=ascending).index
    return df.reindex(new_index)

If you expect unicode problems, you might do something like this (borrowing from @nick-hale's comment):

def sort_by_caseless_columns(df, columns, ascending=True):
    # https://stackoverflow.com/a/29247821/1562285
    import unicodedata

    def normalize_caseless(text):
        return unicodedata.normalize("NFKD", text.casefold())
    df_temp = pd.DataFrame(index = df.index, columns=columns)

    for kol in columns:
        df_temp[kol] = df[kol].apply(normalize_caseless)
    new_index = df_temp.sort_values(columns, ascending=ascending).index
    return df.reindex(new_index)

If you have more possible arguments to pass to the sort_values, you can use **kwargs

If not all the columns are strings, but some are numerical, you might have to include an additional mask or set for the non-numerical columns


问:
Rewrite https-URL before encryption
I need to rewrite URLs like *.lang.domain.com to lang.domain.com and I successfully did it using nginx rewrite module. I have wildcard certificate *.domain.com and it can't secure 4 level domain like test.lang.domain.com
Main problem is when users type https://bla-bla.lang.domain.com in their browser they firstly get a notice about connection is not secure. Then they need to click advanced and proceed https://bla-bla.lang.domain.com (unsafe). After that they will be redirected to https://lang.domain.com.
So my question is whether it is possible to do redirect before https-connection has been established in nginx? Or can it be achieved on some upper-level?

```<code>server {
    listen       80 default;
    server_name  www.domain.com domain.com *.domain.com;

    if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
      rewrite ^(.*)$ https://$domain$uri permanent;
    }

    return 301 https://$host$request_uri;
}

server {
    listen       443 default;
    server_name  www.domain.com domain.com *.domain.com;

      if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
    rewrite ^(.*)$ https://$domain$uri permanent;
    }

    ssl                  on;
    ssl_certificate     /etc/ssl/domain.com/domain.com.ca-bundle;
    ssl_certificate_key /etc/ssl/domain.com/domain.com.key;

    include "conf.d/ssl_settings.default";
    include "conf.d/redirect.ssl.default";
    include "conf.d/logger_front.default";

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HTTPS on;
        proxy_pass https://somestream;
    }
}
</code>```

答: Redirects happen after a secure connection is established. So no, you cannot have a redirect to handle your particular case.</p>

Title: Rewrite https-URL before encryption

Body:
I need to rewrite URLs like *.lang.domain.com to lang.domain.com and I successfully did it using nginx rewrite module. I have wildcard certificate *.domain.com and it can't secure 4 level domain like test.lang.domain.com
Main problem is when users type https://bla-bla.lang.domain.com in their browser they firstly get a notice about connection is not secure. Then they need to click advanced and proceed https://bla-bla.lang.domain.com (unsafe). After that they will be redirected to https://lang.domain.com.
So my question is whether it is possible to do redirect before https-connection has been established in nginx? Or can it be achieved on some upper-level?

server {
    listen       80 default;
    server_name  www.domain.com domain.com *.domain.com;

    if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
      rewrite ^(.*)$ https://$domain$uri permanent;
    }

    return 301 https://$host$request_uri;
}

server {
    listen       443 default;
    server_name  www.domain.com domain.com *.domain.com;

      if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
    rewrite ^(.*)$ https://$domain$uri permanent;
    }

    ssl                  on;
    ssl_certificate     /etc/ssl/domain.com/domain.com.ca-bundle;
    ssl_certificate_key /etc/ssl/domain.com/domain.com.key;

    include "conf.d/ssl_settings.default";
    include "conf.d/redirect.ssl.default";
    include "conf.d/logger_front.default";

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HTTPS on;
        proxy_pass https://somestream;
    }
}


问:
Add value in Object Ionic 2
I have an Object:

```<code>public countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
    ]
}];
</code>```

My Final Object must be:

```<code>countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
        {text: 'Contractor', value: '2'},
    ]
}];
</code>```

How i can add from Controller? I try this:

```<code>this.countriesSignup['options'] = [{text: 'Contractor', value: '2'}] ;
</code>```

答:
Mistake#1

You are using Array of object, so you have to mention index also

So it should be

```<code>this.countriesSignup[0]
</code>```

Mistake #2
Since options is array, you should use push

```<code>countriesSignup[0].options.push({})
</code>```

Title: Add value in Object Ionic 2

Body:
I have an Object:

public countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
    ]
}];

My Final Object must be:

countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
        {text: 'Contractor', value: '2'},
    ]
}];

How i can add from Controller? I try this:

this.countriesSignup['options'] = [{text: 'Contractor', value: '2'}] ;

Body:
Mistake#1

You are using Array of object, so you have to mention index also

So it should be

this.countriesSignup[0]

Mistake #2
Since options is array, you should use push

countriesSignup[0].options.push({})


问:
Setting parameter invoked Method
I have a question about .Net CF 3.5 Reflection.I am invoking expected something method like this,

```<code>        object n=  instance.Type.GetMethod("DoSome"
            ).Invoke(instance.Instance,
            new object[] { commandKeys }
            );
</code>```

commandKey is my parameter list, instance.Type and instance.Instance is not null.
Methods invokes normally but, when I set any property(belongs to which I am calling class) in "DoSome" method, property dont have a value(default value).

```<code> public class CSet:ITask
{
  public void DoSome
{
   SomeProperty=true;
   OnTaskCompleted(this);

}
}
</code>```

I am catching "OnTaskCompleted" delegate which contains "ITask" interface but like i said ITask SomeProperty has not my given value

Thx your answers.

答:
You say that the "Methods invokes normally", but at the same time you claim that the code inside the method is not executed. How do you know that the method is invoked at all?

Are you sure that instance.Instace is the same instance you check SomeProperty on, and catch OnTaskCompleted from?

ContentLicense: CC BY-SA 2.5

Title: Setting parameter invoked Method

Body:
I have a question about .Net CF 3.5 Reflection.I am invoking expected something method like this,

        object n=  instance.Type.GetMethod("DoSome"
            ).Invoke(instance.Instance,
            new object[] { commandKeys }
            );

commandKey is my parameter list, instance.Type and instance.Instance is not null.
Methods invokes normally but, when I set any property(belongs to which I am calling class) in "DoSome" method, property dont have a value(default value).

 public class CSet:ITask
{
  public void DoSome
{
   SomeProperty=true;
   OnTaskCompleted(this);

}
}

I am catching "OnTaskCompleted" delegate which contains "ITask" interface but like i said ITask SomeProperty has not my given value

Thx your answers.


问:
Dynamically add buttons in swift
I am writing an iOS app. Server gives me buttons array to draw on view. So, the number of buttons can vary according to server response,
example:

```<code>let buttonArray=["Button 1","Button 2","Button 3"]
or
let buttonArray=["Button 1","Button 2","Button 3"," Button 4", "Button 5"]
</code>```

I have to stack these buttons vertically.
I created a stackview, add constraints to it, and then add buttons to this stackview as arrangedsubviews.
Buttons should have gap of 5 points between them:

Using stackview:

```<code>func addButtonsUsingStackView()
    {
        //create stackview:
        let stackView=UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 5
        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)

        //stackview constraints:
        let viewsDictionary = ["stackView":stackView]
        let stackView_H = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-20-[stackView]-20-|",
            options: NSLayoutFormatOptions(rawValue: 0),
            metrics: nil,
            views: viewsDictionary)
        let stackView_V = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-30-[stackView]-30-|",
            options: NSLayoutFormatOptions(rawValue:0),
            metrics: nil,
            views: viewsDictionary)
        view.addConstraints(stackView_H)
        view.addConstraints(stackView_V)

        //adding buttons to stackview:

        //let buttonArray=["Button 1","Button 2","Button 3"]
        let buttonArray=["Button 1","Button 2","Button 3"," Button 4"]

        for buttonName in buttonArray{

            let button=UIButton()
            button.setTitle(buttonName, for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor=UIColor.blue
            button.translatesAutoresizingMaskIntoConstraints=false

            stackView.addArrangedSubview(button)

        }

    }
</code>```

Without stackview:

```<code>var buttonArray=["Button 1","Button 2","Button 3"," Button 4"," Button 5"," Button 6"," Button 7"]

    func addButtonsLoop()
    {

        for _view in view.subviews{
            _view.removeFromSuperview()
        }

        var i=0
        var buttonY = 20
        let buttonGap=5

        for btn in buttonArray {

            let buttonHeight=Int(Int(view.frame.height) - 40 - (buttonArray.count * buttonGap))/buttonArray.count
            print(buttonHeight)
            let buttonWidth=Int(view.frame.width - 40)

            let button = UIButton()
            button.backgroundColor = UIColor.orange
            button.setTitle(btn, for: .normal)
            button.titleLabel?.textColor = UIColor.white
            button.frame = CGRect(x: 20, y: buttonY, width:buttonWidth , height:buttonHeight)
            button.contentMode = UIViewContentMode.scaleToFill
            buttonY += buttonHeight + buttonGap
            button.tag = i
            button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
            view.addSubview(button)

            i+=1

        }
    }

    func buttonTapped( _ button : UIButton)
    {
        buttonArray.remove(at: button.tag)
        addButtonsLoop()
    }
</code>```

My question is that instead of above code, how to apply NSLayoutConstraints or LayoutAnchors to solve this?

答:
you can use scroll view to add buttons.</p>

```<code>var btnY = 5
let btnHeight = 40
func addButtonsUsingStackView()
        {
    for view in self.view.subviews{
                view.removeFromSuperview()
            }

            for i in 0..< buttonArray.count {

                let btnFloor = UIButton()
                btnFloor.backgroundColor = Orange
                btnFloor.titleLabel?.textColor = UIColor.white
                btnFloor.frame = CGRect(x: 10, y: btnY, width: Int(scrView.frame.width - 20), height: btnHeight)
                btnFloor.contentMode = UIViewContentMode.scaleToFill
                btnY += btnHeight + 5
                btnFloor.tag = buttonArray.index(of: i)
                btnFloor.addTarget(self, action: #selector(self.btnTappedFloor(_:)), for: UIControlEvents.touchUpInside)
                self.view.addSubview(btnFloor)
            }
            return cell
        }

 func btnTappedFloor( _ button : UIButton)
 {
      buttonArray.remove(at: button.tag)
      addButtonsUsingStackView()
}
</code>```

Title: Dynamically add buttons in swift

Body:
I am writing an iOS app. Server gives me buttons array to draw on view. So, the number of buttons can vary according to server response,
example:

let buttonArray=["Button 1","Button 2","Button 3"]
or
let buttonArray=["Button 1","Button 2","Button 3"," Button 4", "Button 5"]

I have to stack these buttons vertically.
I created a stackview, add constraints to it, and then add buttons to this stackview as arrangedsubviews.
Buttons should have gap of 5 points between them:

Using stackview:

func addButtonsUsingStackView()
    {
        //create stackview:
        let stackView=UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 5
        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)

        //stackview constraints:
        let viewsDictionary = ["stackView":stackView]
        let stackView_H = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-20-[stackView]-20-|",
            options: NSLayoutFormatOptions(rawValue: 0),
            metrics: nil,
            views: viewsDictionary)
        let stackView_V = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-30-[stackView]-30-|",
            options: NSLayoutFormatOptions(rawValue:0),
            metrics: nil,
            views: viewsDictionary)
        view.addConstraints(stackView_H)
        view.addConstraints(stackView_V)

        //adding buttons to stackview:

        //let buttonArray=["Button 1","Button 2","Button 3"]
        let buttonArray=["Button 1","Button 2","Button 3"," Button 4"]

        for buttonName in buttonArray{

            let button=UIButton()
            button.setTitle(buttonName, for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor=UIColor.blue
            button.translatesAutoresizingMaskIntoConstraints=false

            stackView.addArrangedSubview(button)

        }

    }

Without stackview:

var buttonArray=["Button 1","Button 2","Button 3"," Button 4"," Button 5"," Button 6"," Button 7"]

    func addButtonsLoop()
    {

        for _view in view.subviews{
            _view.removeFromSuperview()
        }

        var i=0
        var buttonY = 20
        let buttonGap=5

        for btn in buttonArray {

            let buttonHeight=Int(Int(view.frame.height) - 40 - (buttonArray.count * buttonGap))/buttonArray.count
            print(buttonHeight)
            let buttonWidth=Int(view.frame.width - 40)

            let button = UIButton()
            button.backgroundColor = UIColor.orange
            button.setTitle(btn, for: .normal)
            button.titleLabel?.textColor = UIColor.white
            button.frame = CGRect(x: 20, y: buttonY, width:buttonWidth , height:buttonHeight)
            button.contentMode = UIViewContentMode.scaleToFill
            buttonY += buttonHeight + buttonGap
            button.tag = i
            button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
            view.addSubview(button)

            i+=1

        }
    }

    func buttonTapped( _ button : UIButton)
    {
        buttonArray.remove(at: button.tag)
        addButtonsLoop()
    }

My question is that instead of above code, how to apply NSLayoutConstraints or LayoutAnchors to solve this?

Body:
you can use scroll view to add buttons.

var btnY = 5
let btnHeight = 40
func addButtonsUsingStackView()
        {
    for view in self.view.subviews{
                view.removeFromSuperview()
            }

            for i in 0..< buttonArray.count {

                let btnFloor = UIButton()
                btnFloor.backgroundColor = Orange
                btnFloor.titleLabel?.textColor = UIColor.white
                btnFloor.frame = CGRect(x: 10, y: btnY, width: Int(scrView.frame.width - 20), height: btnHeight)
                btnFloor.contentMode = UIViewContentMode.scaleToFill
                btnY += btnHeight + 5
                btnFloor.tag = buttonArray.index(of: i)
                btnFloor.addTarget(self, action: #selector(self.btnTappedFloor(_:)), for: UIControlEvents.touchUpInside)
                self.view.addSubview(btnFloor)
            }
            return cell
        }

 func btnTappedFloor( _ button : UIButton)
 {
      buttonArray.remove(at: button.tag)
      addButtonsUsingStackView()
}


问:
The expected message formats for the operation are 'Xml', 'Json'
I create a wcf rest service .as you  can see the details of that :

```<code>  [ServiceContract]
    public interface INewsRepository
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Add(News entity);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/DeleteNews/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Remove(string id);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/EditNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Edit(News entity);

    }
</code>```

I call this service in my client like this :

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Script.Serialization;
using CMSManagement.Domain.Entity;
using UPTO.UI.Infrastructure.Configuration;
using System.Text;

namespace UPTO.UI.Services
{
    public class NewsRepository : IServiceRepository<News>
    {
        private WebClient ClientRequest;
        private MemoryStream ms;
        private DataContractJsonSerializer serializerToUplaod;
        public string ServiceHostName = "http://cmsmanagement"+ ServiceServer.Address;
        public NewsRepository()
        {
            ClientRequest = new WebClient();
            ClientRequest.Headers["Content-type"] = "application/json";
            ms=   new MemoryStream();
        }

        public bool Add(News data)
        {

            serializerToUplaod = new DataContractJsonSerializer(typeof(News));
            serializerToUplaod.WriteObject(ms, data);
            string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/AddNews", "POST", ms.ToArray()));
            return Result.ToLower().Equals("true");

        }

        public bool Delete(string id)
        {
            byte[] data = ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/DeleteNews/"+id, "POST", ms.ToArray());
            string Result = System.Text.Encoding.UTF8.GetString(data);
            return Result.ToLower().Equals("true");
        }

        public bool Edit(News data)
        {
            serializerToUplaod = new DataContractJsonSerializer(typeof(News));
            serializerToUplaod.WriteObject(ms, data);

            string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData("http://localhost:47026/NewsRepository.svc/EditNews", "POST", ms.ToArray()));
            return Result.ToLower().Equals("true");
        }

    }
}
</code>```

The problem is the edit part of my service :
When i call my edit method i get this error in my wcf log :

```<code>The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.
</code>```

答:
Finally i found that i should move

```<code>  ClientRequest.Headers["Content-type"] = "application/json";
</code>```

from constructor to my Edit method .Why ?

Body:
I create a wcf rest service .as you  can see the details of that :

  [ServiceContract]
    public interface INewsRepository
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Add(News entity);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/DeleteNews/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Remove(string id);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/EditNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool Edit(News entity);

    }

I call this service in my client like this :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Script.Serialization;
using CMSManagement.Domain.Entity;
using UPTO.UI.Infrastructure.Configuration;
using System.Text;

namespace UPTO.UI.Services
{
    public class NewsRepository : IServiceRepository<News>
    {
        private WebClient ClientRequest;
        private MemoryStream ms;
        private DataContractJsonSerializer serializerToUplaod;
        public string ServiceHostName = "http://cmsmanagement"+ ServiceServer.Address;
        public NewsRepository()
        {
            ClientRequest = new WebClient();
            ClientRequest.Headers["Content-type"] = "application/json";
            ms=   new MemoryStream();
        }

        public bool Add(News data)
        {

            serializerToUplaod = new DataContractJsonSerializer(typeof(News));
            serializerToUplaod.WriteObject(ms, data);
            string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/AddNews", "POST", ms.ToArray()));
            return Result.ToLower().Equals("true");

        }

        public bool Delete(string id)
        {
            byte[] data = ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/DeleteNews/"+id, "POST", ms.ToArray());
            string Result = System.Text.Encoding.UTF8.GetString(data);
            return Result.ToLower().Equals("true");
        }

        public bool Edit(News data)
        {
            serializerToUplaod = new DataContractJsonSerializer(typeof(News));
            serializerToUplaod.WriteObject(ms, data);

            string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData("http://localhost:47026/NewsRepository.svc/EditNews", "POST", ms.ToArray()));
            return Result.ToLower().Equals("true");
        }

    }
}

The problem is the edit part of my service :
When i call my edit method i get this error in my wcf log :

The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.

Body:
Finally i found that i should move

  ClientRequest.Headers["Content-type"] = "application/json";

from constructor to my Edit method .Why ?


问:
CSS Star outline
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

```<code>    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}
</code>```

Working example here: jsfiddle

But what about a transparent fill with a red outline?

答:
I know this isn't quite the answer you were looking for, but I'm gonna post it anyway. For my knowledge there's no way of doing this with pure CSS. However, in my website I took a more easy approach. I had to style a rating bar with stars. Instead of creating the star with CSS, I simply did this:

```<code><span>☆</span>
</code>```

You can style this star however you like (and even fill it with the CSS content property).

Hope this help, and looking forward to see the other answers here.

Title: CSS Star outline

Body:
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}

Working example here: jsfiddle

But what about a transparent fill with a red outline?

Body:
I know this isn't quite the answer you were looking for, but I'm gonna post it anyway. For my knowledge there's no way of doing this with pure CSS. However, in my website I took a more easy approach. I had to style a rating bar with stars. Instead of creating the star with CSS, I simply did this:

<span>☆</span>

You can style this star however you like (and even fill it with the CSS content property).

Hope this help, and looking forward to see the other answers here.


问:
How can I avoid method swizzling pollution through class hierarchy?
```<code>@interface TestView: UIView
@end
</code>```

I want to replace TestView's(inherited from UIView) layoutSubviews method for some particular reason. But don't want to effect the origin UIView's lifecycle, just want it to work within class TestView.

I simply implement it like this:

```<code>@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}
</code>```

But something went wrong. It seems that UIWindow called customLayout too. I guess it's been polluted. How can I avoid that?

IDE: xCode 8.2.1

OS:  10.12.4

Here's the test code:

```<code>#import "ViewController.h"
#import <objc/runtime.h>

@interface TestView: UIView

@end

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    TestView* view = [[TestView alloc] initWithFrame: CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

Here's the runtime log:

```<code>2017-06-07 14:51:38.240 swizzleTest[37908:28470016] -[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00
2017-06-07 14:51:38.242 swizzleTest[37908:28470016] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000111450d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f00021e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001114c0f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00000001113d6005 ___forwarding___ + 1013
    4   CoreFoundation                      0x00000001113d5b88 _CF_forwarding_prep_0 + 120
    5   swizzleTest                         0x000000010ea2b3fb -[TestView customLayout] + 43
    6   UIKit                               0x000000010f594ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
    7   QuartzCore                          0x0000000114296bf8 -[CALayer layoutSublayers] + 146
    8   QuartzCore                          0x000000011428a440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    9   QuartzCore                          0x000000011428a2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    10  QuartzCore                          0x0000000114218318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
    11  QuartzCore                          0x00000001142453ff _ZN2CA11Transaction6commitEv + 475
    12  QuartzCore                          0x0000000114245d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
    13  CoreFoundation                      0x00000001113f5267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    14  CoreFoundation                      0x00000001113f51d7 __CFRunLoopDoObservers + 391
    15  CoreFoundation                      0x00000001113d98a6 CFRunLoopRunSpecific + 454
    16  UIKit                               0x000000010f4c9aea -[UIApplication _run] + 434
    17  UIKit                               0x000000010f4cfc68 UIApplicationMain + 159
    18  swizzleTest                         0x000000010ea2b9af main + 111
    19  libdyld.dylib                       0x000000011240068d start + 1
    20  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

答:
The usual pattern found for swizzling in the docs is:

look up the method in the subclass

2a. If the method exists, swizzle

2b. If the method doesn't exist in the subclass (is inherited from a superclass), add the method as a new method.

Body:
@interface TestView: UIView
@end

I want to replace TestView's(inherited from UIView) layoutSubviews method for some particular reason. But don't want to effect the origin UIView's lifecycle, just want it to work within class TestView.

I simply implement it like this:

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

But something went wrong. It seems that UIWindow called customLayout too. I guess it's been polluted. How can I avoid that?

IDE: xCode 8.2.1

OS:  10.12.4

Here's the test code:

#import "ViewController.h"
#import <objc/runtime.h>

@interface TestView: UIView

@end

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    TestView* view = [[TestView alloc] initWithFrame: CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Here's the runtime log:

2017-06-07 14:51:38.240 swizzleTest[37908:28470016] -[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00
2017-06-07 14:51:38.242 swizzleTest[37908:28470016] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000111450d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f00021e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001114c0f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00000001113d6005 ___forwarding___ + 1013
    4   CoreFoundation                      0x00000001113d5b88 _CF_forwarding_prep_0 + 120
    5   swizzleTest                         0x000000010ea2b3fb -[TestView customLayout] + 43
    6   UIKit                               0x000000010f594ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
    7   QuartzCore                          0x0000000114296bf8 -[CALayer layoutSublayers] + 146
    8   QuartzCore                          0x000000011428a440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    9   QuartzCore                          0x000000011428a2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    10  QuartzCore                          0x0000000114218318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
    11  QuartzCore                          0x00000001142453ff _ZN2CA11Transaction6commitEv + 475
    12  QuartzCore                          0x0000000114245d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
    13  CoreFoundation                      0x00000001113f5267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    14  CoreFoundation                      0x00000001113f51d7 __CFRunLoopDoObservers + 391
    15  CoreFoundation                      0x00000001113d98a6 CFRunLoopRunSpecific + 454
    16  UIKit                               0x000000010f4c9aea -[UIApplication _run] + 434
    17  UIKit                               0x000000010f4cfc68 UIApplicationMain + 159
    18  swizzleTest                         0x000000010ea2b9af main + 111
    19  libdyld.dylib                       0x000000011240068d start + 1
    20  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException


问:
How to add an extra textfield when user clicks on a button?
I have this code

<input type="text" name="search" placeholder="Author...">

I want a button and when I click on it, it should show this textfield and the button should disappear.

答:
You can use Javascript / jquery for that.There are so many ways for doing that.
Here is an example with jquery

$('#button').click(function(){

 $(this).hide();

   var html ='<input type="text" name="search" placeholder="Author...">'

  $('#holder').html(html);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">

</div>

<button id="button">Cick to add textbox</button></code>```

Another method using hide and show

$('#button').click(function(){
   $(this).hide();
   $('#holder').show();

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#holder{
  display:none;
}</code>```

  <input type="text" name="search" placeholder="Author...">
  <select>
      <option>Test</option>
      <option>Test</option>
      <option>Test</option>
      <option>Test</option>
  </select>

<button id="button">Cick to add textbox</button>```

You can learn more about javascript here

Body:
You can use Javascript / jquery for that.There are so many ways for doing that.
Here is an example with jquery

$('#button').click(function(){

 $(this).hide();

   var html ='<input type="text" name="search" placeholder="Author...">'

  $('#holder').html(html);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">

</div>

<button id="button">Cick to add textbox</button>

Another method using hide and show

$('#button').click(function(){
   $(this).hide();
   $('#holder').show();

})

#holder{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">
  <input type="text" name="search" placeholder="Author...">
  <select>
      <option>Test</option>
      <option>Test</option>
      <option>Test</option>
      <option>Test</option>
  </select>
</div>

<button id="button">Cick to add textbox</button>

You can learn more about javascript here


问:
Repeat element from a 2D matrix to a 3D matrix with numpy
I have a 2-D numpy matrix, an example

```<code>M = np.matrix([[1,2],[3,4],[5,6]])
</code>```

I would like, starting from M, to have a matrix like:

```<code>M = np.matrix([[[1,2],[1,2],[1,2]],[[3,4],[3,4],[3,4]],[[5,6],[5,6],[5,6]]])
</code>```

thus, the new matrix has 3 dimensions. How can I do?

答:
NumPy matrix class can't hold 3D data. So, assuming you are okay with NumPy array as output, we can extend the array version of it to 3D with None/np.newaxis and then use np.repeat -

```<code>np.repeat(np.asarray(M)[:,None],3,axis=1)
</code>```

Sample run -

```<code>In [233]: M = np.matrix([[1,2],[3,4],[5,6]])

In [234]: np.repeat(np.asarray(M)[:,None],3,axis=1)
Out[234]:
array([[[1, 2],
        [1, 2],
        [1, 2]],

       [[3, 4],
        [3, 4],
        [3, 4]],

       [[5, 6],
        [5, 6],
        [5, 6]]])
</code>```

Alternatively, with np.tile -

```<code>np.tile(np.asarray(M),3).reshape(-1,3,M.shape[-1])
</code>```

Body:
I have a 2-D numpy matrix, an example

M = np.matrix([[1,2],[3,4],[5,6]])

I would like, starting from M, to have a matrix like:

M = np.matrix([[[1,2],[1,2],[1,2]],[[3,4],[3,4],[3,4]],[[5,6],[5,6],[5,6]]])

thus, the new matrix has 3 dimensions. How can I do?

Body:
NumPy matrix class can't hold 3D data. So, assuming you are okay with NumPy array as output, we can extend the array version of it to 3D with None/np.newaxis and then use np.repeat -

np.repeat(np.asarray(M)[:,None],3,axis=1)

Sample run -

In [233]: M = np.matrix([[1,2],[3,4],[5,6]])

In [234]: np.repeat(np.asarray(M)[:,None],3,axis=1)
Out[234]:
array([[[1, 2],
        [1, 2],
        [1, 2]],

       [[3, 4],
        [3, 4],
        [3, 4]],

       [[5, 6],
        [5, 6],
        [5, 6]]])

Alternatively, with np.tile -

np.tile(np.asarray(M),3).reshape(-1,3,M.shape[-1])


问:
Joining 2 lists of objects based on object id
In my web application I am fetching 2 lists of objects from database.

First list of objects Employee

```<code>1
  Name: Tom
  Week1: 1
  Week2: 3
  Week3: 7
2
  Name: Mike
  Week1: 2
  Week2: 1
  Week3: 7
</code>```

Second list of objects listOfId

```<code>1
  id: 1
  color: green
  symbol: AT
2
  id: 2
  color: red
  symbol: TB
3
  id: 3
  color: blue
  symbol: TD
</code>```

I would like to be able now to display it in a form of table, where for each of the weeks, I display this weeks color and symbol (each week matched on Employee.Week# = listOfId.id)

Something like this

```<code>Name | Week1 | Week1 Color | Week1 Symbol | Week2 | Week 2 Color etc...
Tom      1       green           AT           3         blue
Mike     2       red             TB           1         green
</code>```

In total I will have constant 20 weeks for each employee.

I considered writing a SQL query which would take in week id, and return color and symbol. But for 50 people * 20 weeks... I would need to run this query 1000 times.

I am looking for better approach to solving this issue

my Models:

```<code> public class WeekViewModel
    {
        public int Id{ get; set; }
        public string ShortNAme { get; set; }
        public string Description { get; set; }
        public int Color { get; set; }
    }
}

public class EmployeeWeekViewModel
{
    public string full_name { get; set; }
    public string location { get; set; }
   public int week1 { get; set; }
    public int week2 { get; set; }
    public int week3 { get; set; }

}
</code>```

答:
If I'm getting your correct, you have two lists coming from DB:

employeesList which represents the employees with their corresponding weeks ID

weeksList which represents the weeks for an employee.

Now, you want to join these two lists to display the information in a simple table format. I would do something like that:

```<code>public class EmployeeWeekViewModel{
  public string EmployeeName{get;set;}
  public WeekViewModel Week1 {get;set;}
  public WeekViewModel Week2 {get;set;}
  ...
  public WeekViewModel Week20 {get;set;}
}

public class WeekViewModel{
  public int Id{get;set;}
  public string Color{get;set;}
  public string Symbol{get;set;}
}

employeesList.Select(t=> new EmployeeWeekViewModel(){
  EmployeeName = t.Name,
  Week1 = weeksList.FirstOrDefault(w => w.id == t.Week1).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  Week2 = weeksList.FirstOrDefault(w => w.id == t.Week2).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  ...
});
</code>```

In order to not make a request for each week, I would suggest send to you query a list of week Ids to get them once (checkout this example).

Body:
In my web application I am fetching 2 lists of objects from database.

First list of objects Employee

1
  Name: Tom
  Week1: 1
  Week2: 3
  Week3: 7
2
  Name: Mike
  Week1: 2
  Week2: 1
  Week3: 7

Second list of objects listOfId

1
  id: 1
  color: green
  symbol: AT
2
  id: 2
  color: red
  symbol: TB
3
  id: 3
  color: blue
  symbol: TD

I would like to be able now to display it in a form of table, where for each of the weeks, I display this weeks color and symbol (each week matched on Employee.Week# = listOfId.id)

Something like this

Name | Week1 | Week1 Color | Week1 Symbol | Week2 | Week 2 Color etc...
Tom      1       green           AT           3         blue
Mike     2       red             TB           1         green

In total I will have constant 20 weeks for each employee.

I considered writing a SQL query which would take in week id, and return color and symbol. But for 50 people * 20 weeks... I would need to run this query 1000 times.

I am looking for better approach to solving this issue

my Models:

 public class WeekViewModel
    {
        public int Id{ get; set; }
        public string ShortNAme { get; set; }
        public string Description { get; set; }
        public int Color { get; set; }
    }
}

public class EmployeeWeekViewModel
{
    public string full_name { get; set; }
    public string location { get; set; }
   public int week1 { get; set; }
    public int week2 { get; set; }
    public int week3 { get; set; }

}

Body:
If I'm getting your correct, you have two lists coming from DB:

employeesList which represents the employees with their corresponding weeks ID

weeksList which represents the weeks for an employee.

Now, you want to join these two lists to display the information in a simple table format. I would do something like that:

public class EmployeeWeekViewModel{
  public string EmployeeName{get;set;}
  public WeekViewModel Week1 {get;set;}
  public WeekViewModel Week2 {get;set;}
  ...
  public WeekViewModel Week20 {get;set;}
}

public class WeekViewModel{
  public int Id{get;set;}
  public string Color{get;set;}
  public string Symbol{get;set;}
}

employeesList.Select(t=> new EmployeeWeekViewModel(){
  EmployeeName = t.Name,
  Week1 = weeksList.FirstOrDefault(w => w.id == t.Week1).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  Week2 = weeksList.FirstOrDefault(w => w.id == t.Week2).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  ...
});

In order to not make a request for each week, I would suggest send to you query a list of week Ids to get them once (checkout this example).


问:
Better Way to use Laravel old and Vue.js
Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views  without lost the value, overwrite by the v-model

Because after charge vue.js this take the value in data that is define in this way

```<code>data: {
    ciudad:'',
}
</code>```

If I try to do something like that

```<code> <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ $documento->ciudad }}" >
</code>```

I lost the value sending by the controller

答:
The easy way to do this for me was in this way:

Laravel Controller

```<code>  $documento = ReduJornada::where("id_documento",$id)->first();

  return view('documentos.redujornada')->with(compact('documento'));
</code>```

Laravel View

```<code> <input  class="form-control"  id="ciudad"  v-model="documento.ciudad"   value="{{ old('ciudad',  isset($documento->ciudad) ? $documento->ciudad : null) }}" >
</code>```

Vue.js

data: {

```<code>ibanIsInvalid : false,

documento: {
  ciudad: $('#ciudad').val(),
}
</code>```

In this way I can use the same view to create and edit an object, using the same form, even use laravel validation without lost the data after refresh.

If you know a better way to do that please tell me... Thanks

Body:
Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views  without lost the value, overwrite by the v-model

Because after charge vue.js this take the value in data that is define in this way

data: {
    ciudad:'',
}

If I try to do something like that

 <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ $documento->ciudad }}" >

I lost the value sending by the controller

Body:
The easy way to do this for me was in this way:

Laravel Controller

  $documento = ReduJornada::where("id_documento",$id)->first();

  return view('documentos.redujornada')->with(compact('documento'));

Laravel View

 <input  class="form-control"  id="ciudad"  v-model="documento.ciudad"   value="{{ old('ciudad',  isset($documento->ciudad) ? $documento->ciudad : null) }}" >

Vue.js

data: {

ibanIsInvalid : false,

documento: {
  ciudad: $('#ciudad').val(),
}

In this way I can use the same view to create and edit an object, using the same form, even use laravel validation without lost the data after refresh.

If you know a better way to do that please tell me... Thanks


问:
Decrement or increment a variable in the robot framework
I just want to decrement the variable N_groups in the last line.
This is my robot file:

```<code>Preconditions - Delete Groups But Not First
    ${N_groups}    Setup Groups Count Groups
    Log to console    N_groups: ${N_groups}
    : FOR    ${INDEX}    IN RANGE    1    20
    \    Run Keyword If    '${N_groups}' == '1'    Exit For Loop
    \    Setup Groups Delete Group    ${group}
    \    ${N_groups}=    ${N_groups}-1
</code>```

I get the error:

No keyword with name '${N_groups}-1' found.

What I am doing wrong here?

答:
If the variable is already a number, you can use:

${N_groups}=    ${N_groups-1}

To do this you need to coerce it to a number (otherwise you'll get an error saying failed: TypeError: coercing to Unicode: need string or buffer, int found), e.g.

*** Variables ***
${N_groups}=    ${0}  # ${} notation coerces value to a number

Alternatively, you can use Evaluate like this, which works whether ${N_groups} has been coerced to a number or not:

${N_groups}=    Evaluate    ${N_groups} - 1

Body:
I just want to decrement the variable N_groups in the last line.
This is my robot file:

Preconditions - Delete Groups But Not First
    ${N_groups}    Setup Groups Count Groups
    Log to console    N_groups: ${N_groups}
    : FOR    ${INDEX}    IN RANGE    1    20
    \    Run Keyword If    '${N_groups}' == '1'    Exit For Loop
    \    Setup Groups Delete Group    ${group}
    \    ${N_groups}=    ${N_groups}-1

I get the error:

No keyword with name '${N_groups}-1' found.

What I am doing wrong here?


答:
This should work for you:</p>

```<code>np.array([list(np.array(i)) * 3 for i in M])
</code>```

Title: Repeat element from a 2D matrix to a 3D matrix with numpy

Body:
This should work for you:

np.array([list(np.array(i)) * 3 for i in M])


问:
UITabBarController apears after changing window rootViewController
I'm developing an app, where you have LoginVC presented as rootVC and launch. After successful login, I change window rootVC to TabBarVC I created. It works fine. Problem is that when I logout and change window rootVC to LoginVC it appears for a second and then it is covered by distorted TabBarVC with first view selected. My TabBarVC consists of 3 VCs that are embedded in NavCon. I also use SideMenu as second navigation to tabbar. How can I prevent overlapping LoginVC by TabBarVC after logout?</p>

答: I don't have enough info about your code, but I guess your problem happens because of animations interference, try to disable animation when you want to change window from rootVC to LoginVC , i.e use: animated: false to see if helps or not :S


问:
Fixed Header area not working
I have a header that I need to fixed to top and change it's background while scroll down. Do I need to use jQuery? I tried to use position:fixed but it's not working properly.

Here are my code samples,

header {
  padding: 20px 0;
  position: fixed;
}

.logo-div {
  margin: 30px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="header-panel">
    <div class="col-xs-6 col-md-4  col-sm-4 logo-div">
       <img id="headerLogo" src="images/logo.png" alt="logo">
    </div>
    <div class="col-xs-6 col-md-5 col-sm-6  menu pull-right">
      <nav class="navbar navbar-default pull-right">
        <div class="container-fluid">
          <div class=" navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
              <li class="">Sign In <i class="fa fa-user-o user-icon" aria-hidden="true"></i></li>
              <li>Retrieve Quotes</li>
              <li>
                <i class="fa fa-bars menu-icon" aria-hidden="true"></i></li>
            </ul>
          </div>
          <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
      </nav>
    </div>
  </div>
</header></code>```

Original look.

It just looks this way now.

答:
You can use position: fixed; on the header, and use this function:

```<code>$(document).scroll(function() {
   if($(window).scrollTop() != 0) {
     $("header").css('background-color', 'transparent');
   }
   if($(window).scrollTop() == 0) {
     $("header").css('background-color', 'darkgrey');
   }
});
</code>```

To change the header colour if the div's not at the top.

$(document).scroll(function() {
   if($(window).scrollTop() != 0) {
     $("header").css('background-color', 'transparent');
   }
   if($(window).scrollTop() == 0) {
     $("header").css('background-color', 'darkgrey');
   }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>header {
  height: 50px;
  background-color: darkgrey;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
}

div {
  margin-top: 50px;
}</code>```

stuff stuff

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed et neque erat. Etiam pulvinar metus augue, nec facilisis
  ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor, nisi sit amet vehicula fringilla, ex orci aliquam neque, in fermentum velit diam ac purus. Nunc
  sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque. Cras tincidunt tortor feugiat libero facilisis mattis. Etiam facilisis est eu massa bibendum porttitor.
  Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor tincidunt. Quisque sit amet ullamcorper dolor. Cras scelerisque congue vehicula. Nam aliquet suscipit
  ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque, diam mi facilisis quam, et vehicula nisi nisl faucibus dui. Aenean id malesuada velit. Sed pellentesque,
  nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam neque. Integer nec urna odio. Suspendisse maximus molestie sem pharetra elementum. Vestibulum at elit
  id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque nisl pharetra ut. Praesent consectetur eleifend lectus, in ornare ipsum. Cras aliquam quis
  urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit ante quis, vulputate sapien. Mauris mollis odio id dolor pharetra, nec volutpat nibh cursus.
  Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies. Ut nec neque vestibulum, varius augue quis, feugiat libero. Sed feugiat lectus id rhoncus
  laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit neque vel blandit gravida. Aenean congue facilisis elit, a eleifend quam pharetra nec.
  Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus nulla lobortis venenatis. Maecenas venenatis pretium diam, quis laoreet libero dictum eu.
  Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor. Sed sodales dolor a leo ultricies, id mollis augue convallis. Duis at egestas lectus.
  Nunc ultricies magna quis justo euismod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed et neque
  erat. Etiam pulvinar metus augue, nec facilisis ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor, nisi sit amet vehicula fringilla, ex orci aliquam
  neque, in fermentum velit diam ac purus. Nunc sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque. Cras tincidunt tortor feugiat libero facilisis mattis.
  Etiam facilisis est eu massa bibendum porttitor. Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor tincidunt. Quisque sit amet ullamcorper dolor. Cras
  scelerisque congue vehicula. Nam aliquet suscipit ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque, diam mi facilisis quam, et vehicula nisi nisl faucibus
  dui. Aenean id malesuada velit. Sed pellentesque, nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam neque. Integer nec urna odio. Suspendisse maximus
  molestie sem pharetra elementum. Vestibulum at elit id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque nisl pharetra ut. Praesent consectetur
  eleifend lectus, in ornare ipsum. Cras aliquam quis urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit ante quis, vulputate sapien. Mauris mollis
  odio id dolor pharetra, nec volutpat nibh cursus. Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies. Ut nec neque vestibulum, varius augue
  quis, feugiat libero. Sed feugiat lectus id rhoncus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit neque vel blandit gravida. Aenean
  congue facilisis elit, a eleifend quam pharetra nec. Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus nulla lobortis venenatis. Maecenas
  venenatis pretium diam, quis laoreet libero dictum eu. Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor. Sed sodales dolor a leo ultricies,
  id mollis augue convallis. Duis at egestas lectus. Nunc ultricies magna quis justo euismod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada
  fames ac ante ipsum primis in faucibus. Sed et neque erat. Etiam pulvinar metus augue, nec facilisis ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor,
  nisi sit amet vehicula fringilla, ex orci aliquam neque, in fermentum velit diam ac purus. Nunc sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque.
  Cras tincidunt tortor feugiat libero facilisis mattis. Etiam facilisis est eu massa bibendum porttitor. Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor
  tincidunt. Quisque sit amet ullamcorper dolor. Cras scelerisque congue vehicula. Nam aliquet suscipit ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque,
  diam mi facilisis quam, et vehicula nisi nisl faucibus dui. Aenean id malesuada velit. Sed pellentesque, nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam
  neque. Integer nec urna odio. Suspendisse maximus molestie sem pharetra elementum. Vestibulum at elit id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque
  nisl pharetra ut. Praesent consectetur eleifend lectus, in ornare ipsum. Cras aliquam quis urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit
  ante quis, vulputate sapien. Mauris mollis odio id dolor pharetra, nec volutpat nibh cursus. Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies.
  Ut nec neque vestibulum, varius augue quis, feugiat libero. Sed feugiat lectus id rhoncus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit
  neque vel blandit gravida. Aenean congue facilisis elit, a eleifend quam pharetra nec. Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus
  nulla lobortis venenatis. Maecenas venenatis pretium diam, quis laoreet libero dictum eu. Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor.
  Sed sodales dolor a leo ultricies, id mollis augue convallis. Duis at egestas lectus. Nunc ultricies magna quis justo euismod tempor.

```

Title: Fixed Header area not working

Body:
I have a header that I need to fixed to top and change it's background while scroll down. Do I need to use jQuery? I tried to use position:fixed but it's not working properly.

Here are my code samples,

header {
  padding: 20px 0;
  position: fixed;
}

.logo-div {
  margin: 30px 0;
}

Sign In

Retrieve Quotes

Original look.

It just looks this way now.

Body:
You can use position: fixed; on the header, and use this function:

$(document).scroll(function() {
   if($(window).scrollTop() != 0) {
     $("header").css('background-color', 'transparent');
   }
   if($(window).scrollTop() == 0) {
     $("header").css('background-color', 'darkgrey');
   }
});

To change the header colour if the div's not at the top.

$(document).scroll(function() {
   if($(window).scrollTop() != 0) {
     $("header").css('background-color', 'transparent');
   }
   if($(window).scrollTop() == 0) {
     $("header").css('background-color', 'darkgrey');
   }
});

header {
  height: 50px;
  background-color: darkgrey;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
}

div {
  margin-top: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>stuff stuff</header>
<div id="scrollable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed et neque erat. Etiam pulvinar metus augue, nec facilisis
  ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor, nisi sit amet vehicula fringilla, ex orci aliquam neque, in fermentum velit diam ac purus. Nunc
  sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque. Cras tincidunt tortor feugiat libero facilisis mattis. Etiam facilisis est eu massa bibendum porttitor.
  Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor tincidunt. Quisque sit amet ullamcorper dolor. Cras scelerisque congue vehicula. Nam aliquet suscipit
  ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque, diam mi facilisis quam, et vehicula nisi nisl faucibus dui. Aenean id malesuada velit. Sed pellentesque,
  nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam neque. Integer nec urna odio. Suspendisse maximus molestie sem pharetra elementum. Vestibulum at elit
  id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque nisl pharetra ut. Praesent consectetur eleifend lectus, in ornare ipsum. Cras aliquam quis
  urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit ante quis, vulputate sapien. Mauris mollis odio id dolor pharetra, nec volutpat nibh cursus.
  Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies. Ut nec neque vestibulum, varius augue quis, feugiat libero. Sed feugiat lectus id rhoncus
  laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit neque vel blandit gravida. Aenean congue facilisis elit, a eleifend quam pharetra nec.
  Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus nulla lobortis venenatis. Maecenas venenatis pretium diam, quis laoreet libero dictum eu.
  Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor. Sed sodales dolor a leo ultricies, id mollis augue convallis. Duis at egestas lectus.
  Nunc ultricies magna quis justo euismod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed et neque
  erat. Etiam pulvinar metus augue, nec facilisis ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor, nisi sit amet vehicula fringilla, ex orci aliquam
  neque, in fermentum velit diam ac purus. Nunc sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque. Cras tincidunt tortor feugiat libero facilisis mattis.
  Etiam facilisis est eu massa bibendum porttitor. Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor tincidunt. Quisque sit amet ullamcorper dolor. Cras
  scelerisque congue vehicula. Nam aliquet suscipit ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque, diam mi facilisis quam, et vehicula nisi nisl faucibus
  dui. Aenean id malesuada velit. Sed pellentesque, nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam neque. Integer nec urna odio. Suspendisse maximus
  molestie sem pharetra elementum. Vestibulum at elit id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque nisl pharetra ut. Praesent consectetur
  eleifend lectus, in ornare ipsum. Cras aliquam quis urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit ante quis, vulputate sapien. Mauris mollis
  odio id dolor pharetra, nec volutpat nibh cursus. Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies. Ut nec neque vestibulum, varius augue
  quis, feugiat libero. Sed feugiat lectus id rhoncus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit neque vel blandit gravida. Aenean
  congue facilisis elit, a eleifend quam pharetra nec. Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus nulla lobortis venenatis. Maecenas
  venenatis pretium diam, quis laoreet libero dictum eu. Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor. Sed sodales dolor a leo ultricies,
  id mollis augue convallis. Duis at egestas lectus. Nunc ultricies magna quis justo euismod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet ultricies sapien, a volutpat risus. In nec tempus diam. Interdum et malesuada
  fames ac ante ipsum primis in faucibus. Sed et neque erat. Etiam pulvinar metus augue, nec facilisis ipsum semper vitae. Maecenas tincidunt feugiat ex, sit amet eleifend orci placerat vel. Vivamus ac ullamcorper ipsum, vehicula lacinia lacus. Nam auctor,
  nisi sit amet vehicula fringilla, ex orci aliquam neque, in fermentum velit diam ac purus. Nunc sed efficitur dui. Curabitur enim metus, rutrum ut mattis non, molestie a nisi. Vivamus non fermentum purus. Integer ornare enim ut commodo scelerisque.
  Cras tincidunt tortor feugiat libero facilisis mattis. Etiam facilisis est eu massa bibendum porttitor. Proin tincidunt orci ut pellentesque euismod. Donec pretium velit ac dolor rhoncus, eu scelerisque nisl blandit. Pellentesque dapibus et lacus auctor
  tincidunt. Quisque sit amet ullamcorper dolor. Cras scelerisque congue vehicula. Nam aliquet suscipit ex, id pulvinar augue suscipit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque bibendum, turpis eget suscipit scelerisque,
  diam mi facilisis quam, et vehicula nisi nisl faucibus dui. Aenean id malesuada velit. Sed pellentesque, nulla at pulvinar fringilla, augue neque suscipit augue, non porta nulla erat in leo. Nunc sollicitudin dolor quis posuere lobortis. Donec at aliquam
  neque. Integer nec urna odio. Suspendisse maximus molestie sem pharetra elementum. Vestibulum at elit id lorem venenatis finibus. Sed luctus nulla dignissim mauris euismod, quis blandit augue rutrum. Nulla facilisi. Nullam bibendum arcu risus, nec scelerisque
  nisl pharetra ut. Praesent consectetur eleifend lectus, in ornare ipsum. Cras aliquam quis urna quis commodo. Cras fermentum lacinia risus, quis fringilla turpis vestibulum eu. Pellentesque luctus iaculis efficitur. Nam et mauris condimentum, blandit
  ante quis, vulputate sapien. Mauris mollis odio id dolor pharetra, nec volutpat nibh cursus. Nam sed lacinia libero, eget hendrerit elit. Donec laoreet sapien non dolor congue, nec pellentesque libero semper. Vestibulum efficitur at ipsum vitae ultricies.
  Ut nec neque vestibulum, varius augue quis, feugiat libero. Sed feugiat lectus id rhoncus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ac malesuada justo, pharetra maximus nunc. Nam hendrerit
  neque vel blandit gravida. Aenean congue facilisis elit, a eleifend quam pharetra nec. Integer id luctus ipsum, id aliquet nunc. Integer pulvinar iaculis eros, ultrices ullamcorper tellus congue in. Suspendisse blandit ullamcorper ipsum, sed cursus
  nulla lobortis venenatis. Maecenas venenatis pretium diam, quis laoreet libero dictum eu. Fusce elementum mattis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ut cursus libero. Integer eget tempor dui, ut volutpat tortor.
  Sed sodales dolor a leo ultricies, id mollis augue convallis. Duis at egestas lectus. Nunc ultricies magna quis justo euismod tempor.

</div>


答:
HTML:

```<code><input class="input" type="text" name="search" placeholder="Author...">
<button class="btn" type="button">
  click
</button>
</code>```

CSS:

```<code>.input {
  display: none;
}
</code>```

JS:

```<code>$('.btn').on('click', function() {
    $('.input').show();
  $(this).hide();
})
</code>```

working example: https://jsfiddle.net/n05reomv/

Title: How to add an extra textfield when user clicks on a button?

Body:
I have this code

<input type="text" name="search" placeholder="Author...">

I want a button and when I click on it, it should show this textfield and the button should disappear.

Body:
HTML:

<input class="input" type="text" name="search" placeholder="Author...">
<button class="btn" type="button">
  click
</button>

CSS:

.input {
  display: none;
}

JS:

$('.btn').on('click', function() {
    $('.input').show();
  $(this).hide();
})

working example: https://jsfiddle.net/n05reomv/


问:
How to find the css version?
How do I find the version of CSS that I am using?</p>

答: As far as I know, there's nothing in CSS code that specifies the version.  Browsers are designed to interpret one or more versions of CSS at runtime.  Therefore, I would imagine that you would need to get the version of the browser via javascript and then determine what version of CSS is understood by the browser.</p>

ContentLicense: CC BY-SA 4.0

Title: How to find the css version?


问:
Assigning a size to a Deque in Java
I'm having trouble assigning a limit to the size of my double ended queue (Deque). It seems that my queue never gets full and just resizes whenever I add or offer a value unto it. My simple code just accepts a string value, splits it by space " ", loops everything and adds it to the queue.

```<code>evaluate("A B C D E F");

public static int evaluate(final String input){
    final Deque<String> stack = new ArrayDeque<>(3);
    final String[] tokens = input.split(" ");

    for (String token:tokens){
        System.out.println(stack.offer(token));
    }

    System.out.println(stack.size());
 }
</code>```

returns:

```<code> true
 true
 true
 true
 true
 true
 6
</code>```

I was expecting that the queue will be full since I have not removed or read any value from it. Is there something that I'm missing here? Or am I just using the queue wrong? Thanks!

答:
When you do

```<code>Deque<String> stack = new ArrayDeque<>(3);
</code>```

3 is not the size but the initial capacity as the doc explains here

the ArrayDeque can grow as much as you need, and you are not limiting the size with that parameter in the constructor.

you can handle a work around dont exposing the array but instead checking everytime you want to add/offer an object in the deque

```<code>if (stack.size()<3) {
    stack.offer(token);
}
</code>```

Title: Assigning a size to a Deque in Java

Body:
I'm having trouble assigning a limit to the size of my double ended queue (Deque). It seems that my queue never gets full and just resizes whenever I add or offer a value unto it. My simple code just accepts a string value, splits it by space " ", loops everything and adds it to the queue.

evaluate("A B C D E F");

public static int evaluate(final String input){
    final Deque<String> stack = new ArrayDeque<>(3);
    final String[] tokens = input.split(" ");

    for (String token:tokens){
        System.out.println(stack.offer(token));
    }

    System.out.println(stack.size());
 }

returns:

 true
 true
 true
 true
 true
 true
 6

I was expecting that the queue will be full since I have not removed or read any value from it. Is there something that I'm missing here? Or am I just using the queue wrong? Thanks!

Body:
When you do

Deque<String> stack = new ArrayDeque<>(3);

3 is not the size but the initial capacity as the doc explains here

the ArrayDeque can grow as much as you need, and you are not limiting the size with that parameter in the constructor.

you can handle a work around dont exposing the array but instead checking everytime you want to add/offer an object in the deque

if (stack.size()<3) {
    stack.offer(token);
}


问:
PhantomJS page.includeJs Not Working
I want to create sample script to login at my website.

My script like this :

```<code>var page   = require("webpage").create();
var system = require("system");
var data   = {
    "username": system.args[1],
    "password": system.args[2]
}

function login(data){
    page.open("http://localhost/mywebsite/login.php", function(){
        page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
            console.log("Come in here.");
            phantom.exit();
        )}
    )}
}
login(data);
</code>```

When I run phantomjs in terminal, example : phantomjs myscript.js admin admin

i dont get anything in my terminal.

what's wrong in my code?

答:
The way you closing callbacks is wrong. you are closing like this )}.it should be });

Your code here

```<code>var page   = require("webpage").create();
var system = require("system");
var data   = {
    "username": system.args[1],
    "password": system.args[2]
}

function login(data){
    page.open("http://localhost/mywebsite/login.php", function(){
        page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
            console.log("Come in here.");
            phantom.exit();
        });
    })
}
login(data);
</code>```

Title: PhantomJS page.includeJs Not Working

Body:
I want to create sample script to login at my website.

My script like this :

var page   = require("webpage").create();
var system = require("system");
var data   = {
    "username": system.args[1],
    "password": system.args[2]
}

function login(data){
    page.open("http://localhost/mywebsite/login.php", function(){
        page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
            console.log("Come in here.");
            phantom.exit();
        )}
    )}
}
login(data);

When I run phantomjs in terminal, example : phantomjs myscript.js admin admin

i dont get anything in my terminal.

what's wrong in my code?

Body:
The way you closing callbacks is wrong. you are closing like this )}.it should be });

Your code here

var page   = require("webpage").create();
var system = require("system");
var data   = {
    "username": system.args[1],
    "password": system.args[2]
}

function login(data){
    page.open("http://localhost/mywebsite/login.php", function(){
        page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
            console.log("Come in here.");
            phantom.exit();
        });
    })
}
login(data);