问:
Need help in JavaScript/JQuery
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?</p>

```<code><html>
<head>
  <style>
  .box{
    border: 1px solid black;
  }
  </style>

  <script>
  window.onload = function() { document.getElementById('myDIV').style.display = 'none'; };
  function showImg(){
    var x = document.getElementById('myDIV');
    if (x.style.display === 'none') { x.style.display = 'block'; }
    else { x.style.display = 'none'; }
  }
  </script>

</head>

<body>
  <div id="show" onclick="showImg()" class="box">
    when this div is select and drag the bin should be shown
  </div>

  <div id="myDIV">
    <img src="img/upload.png"/>
  </div>

</body>
</html>
</code>```

答:
you can use this :</p>

```<code>            // for show element when start drag
            document.addEventListener("dragstart", function (event) {
                if (event.target.className == "box") {
                    var x = document.getElementById('myDIV');
                    x.style.display = 'block';
                }
            });
       // for hide element when drag end
        document.addEventListener("dragend", function (event) {
            if (event.target.className == "box") {
                var x = document.getElementById('myDIV');
                x.style.display = 'none';
            }
        });
</code>```

Title: Need help in JavaScript/JQuery

Body:
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?

    when this div is select and drag the bin should be shown

Body:
you can use this :

            // for show element when start drag
            document.addEventListener("dragstart", function (event) {
                if (event.target.className == "box") {
                    var x = document.getElementById('myDIV');
                    x.style.display = 'block';
                }
            });
       // for hide element when drag end
        document.addEventListener("dragend", function (event) {
            if (event.target.className == "box") {
                var x = document.getElementById('myDIV');
                x.style.display = 'none';
            }
        });


来源: stackexchange

问:
How do I change to whole number instead of % in this codepen
Recently, I happen to come to this page.

I realise the change of the code happen in this function.

And it take data from
A	1
 .

 If the data in  is whole number, it does not have much effect like what % give.

How do I make it accept whole number and provide the effect similar to %?

```<code>function viewGraph() {
  $(".column").css("height", "0");
  $("table tr").each(function(index) {
    var ha = $(this).children("td").eq(1).text();
    $("#col" + index)
      .animate({ height: ha }, 1500)
      .html("<div>" + ha + "</div>");
  });
}
$(document).ready(function() {
  viewGraph();
});
</code>```

https://codepen.io/bobasdasd/pen/bRNzza

答:
```<code>function viewGraph() {
  var height = $("#grafico").height() / 4;
  $(".column").css("height", "0");
  $("table tr").each(function(index) {
  var ha = $(this).children("td").eq(1).text();
  $("#col" + index)
    .animate({ height: (+ha ? ha * height : ha ) }, 1500)
    .html("<div>" + ha + "</div>");
  });
}

                                                ---- A poor English speaker
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Recently, I happen to come to this page.

I realise the change of the code happen in this function.

And it take data from
A	1
 .

 If the data in  is whole number, it does not have much effect like what % give.

How do I make it accept whole number and provide the effect similar to %?

function viewGraph() {
  $(".column").css("height", "0");
  $("table tr").each(function(index) {
    var ha = $(this).children("td").eq(1).text();
    $("#col" + index)
      .animate({ height: ha }, 1500)
      .html("
" + ha + "
");
  });
}
$(document).ready(function() {
  viewGraph();
});

https://codepen.io/bobasdasd/pen/bRNzza


问:
Kotlin equivalent of Optional.map and a method reference

The Java

Consider the following Java:

```<code>private void example() {
  Optional<String> foo = ...
  Optional<String> bar =
      foo.map(this::transform1)
          .map(this::transform2)
}

private String transform1(String s) {
  return s + "!";
}

private String transform2(String s) {
  return "@" + s;
}
</code>```

Note that the transform methods accept non-Optional values.

Question

Does Kotlin have a built-in mechanism to achieve the same thing when using its nullable/non-nullabe types?

The first attempt

I managed to achieve this effect with the following:

```<code>fun <A, B> nullMap(a: A?, mapper: (a: A) -> B?): B? =
  if (a != null) mapper.invoke(a) else null

fun example() {
  val foo: String? = "Space cookies"
  val bar1: String? = nullMap(foo, Example::transform1)
  val bar2: String? = nullMap(bar1, Example::transform2)
}

fun transform(s: String) = s + "!"
fun transform2(s: String) = "@" + s
</code>```

(Again, we note that for the transform methods, s is a non-nullable String.)

So, my question stated another way is: Does a nullMap equivalent already exist in Kotlin's standard library? And/or: is there a different standard way of doing this?

Finally, can the visually cleaner chaining approach be achieved in Kotlin, rather than either separate assignments (above) or nested function calls?  For a moment I considered that you could add nullMap as an extension method on Any, but sometimes the receiver you're trying to invoke a method on is null (so that won't work).

答:
We use safe call operator:

```<code>val foo: Foo? = ...
foo?.toA()?.toB()
</code>```

Or

```<code>foo?.let(this::transform1)?.let(this::transform2)
</code>```

Kotlin emphasis on null safety. There is an entire chapter in its manual describing related technics.

Body:
The Java

Consider the following Java:

private void example() {
  Optional<String> foo = ...
  Optional<String> bar =
      foo.map(this::transform1)
          .map(this::transform2)
}

private String transform1(String s) {
  return s + "!";
}

private String transform2(String s) {
  return "@" + s;
}

Note that the transform methods accept non-Optional values.

Question

Does Kotlin have a built-in mechanism to achieve the same thing when using its nullable/non-nullabe types?

The first attempt

I managed to achieve this effect with the following:

fun  nullMap(a: A?, mapper: (a: A) -> B?): B? =
  if (a != null) mapper.invoke(a) else null

fun example() {
  val foo: String? = "Space cookies"
  val bar1: String? = nullMap(foo, Example::transform1)
  val bar2: String? = nullMap(bar1, Example::transform2)
}

fun transform(s: String) = s + "!"
fun transform2(s: String) = "@" + s

(Again, we note that for the transform methods, s is a non-nullable String.)

So, my question stated another way is: Does a nullMap equivalent already exist in Kotlin's standard library? And/or: is there a different standard way of doing this?

Finally, can the visually cleaner chaining approach be achieved in Kotlin, rather than either separate assignments (above) or nested function calls?  For a moment I considered that you could add nullMap as an extension method on Any, but sometimes the receiver you're trying to invoke a method on is null (so that won't work).

Body:
We use safe call operator:

val foo: Foo? = ...
foo?.toA()?.toB()

Or

foo?.let(this::transform1)?.let(this::transform2)

Kotlin emphasis on null safety. There is an entire chapter in its manual describing related technics.


问:
Hive - time difference in minutes is negative
I need to get time difference in minutes for my analysis in Hive query.

I am using unix_timestamp() to convert dates to seconds and then subtracting to get the diff in seconds and the multiplied by 60 for minutes.

My issue is my recent date - older date difference is coming negative.

here is my query and results

Hive query and result screenshot

processed_ts   create_ts   processed_unix_timestamp    create_unix_timestamp   miniue Diff
2017-03-12 3:01:06  2017-03-12 2:58:36  1489312865  1489316315  -57.5
2017-03-12 3:01:36  2017-03-12 2:59:06  1489312895  1489316345  -57.5
2017-03-12 3:02:12  2017-03-12 2:59:42  1489312932  1489316382  -57.5

Any help is much appreciated.

答:
USA & Canada Start DST on March 12

Published 17-Feb-2017

Most of the United States, Canada, and Mexico's northern border cities
will begin Daylight Saving Time (DST) on Sunday, March 12, 2017.

People in areas that observe DST will spring forward 1 hour from 02:00
(2 am) to 03:00 (3 am), local time.
Standard time will resume on
Sunday, November 5, 2017.

https://www.timeanddate.com/news/time/usa-canada-start-dst-2017.html

```<code>select timestamp '2017-03-12 02:58:36'
</code>```

2017-03-12 03:58:36

Body:
USA & Canada Start DST on March 12

Published 17-Feb-2017

Most of the United States, Canada, and Mexico's northern border cities
will begin Daylight Saving Time (DST) on Sunday, March 12, 2017.

People in areas that observe DST will spring forward 1 hour from 02:00
(2 am) to 03:00 (3 am), local time.
Standard time will resume on
Sunday, November 5, 2017.

https://www.timeanddate.com/news/time/usa-canada-start-dst-2017.html

select timestamp '2017-03-12 02:58:36'

2017-03-12 03:58:36


问:
Deleting part of a string in nested list python
I am trying to keep only a particular part of a string within my nested list.  My code is as follows:

```<code>answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "', ...]
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "', ...]]
</code>```

I want to delete parts of the string so that the only piece that remains are:

```<code>answers = [
    ['person1', 'answer 1', 'answer 0', ...]
    ['person 2', 'answer 3', 'answer 1', ...]]
</code>```

答:
Given:

```<code>answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "',],
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "',]
]
</code>```

You can use regexes to parse each string for the desired pattern p:

```<code>import re

p = re.compile(r'(?!.*\[)(\w+\s*\d)')
new_answers = []
for lst in answers:
    new_answers.append([re.search(p, s).groups(0)[0] for s in lst])
new_answers
# [['person1', 'answer 1', 'answer 0'], ['person2', 'answer 3', 'answer 1']]
</code>```

This particular pattern ignores characters behind the first bracket "[" and finds letters with zero or more spaces and digits.

Body:
I am trying to keep only a particular part of a string within my nested list.  My code is as follows:

answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "', ...]
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "', ...]]

I want to delete parts of the string so that the only piece that remains are:

answers = [
    ['person1', 'answer 1', 'answer 0', ...]
    ['person 2', 'answer 3', 'answer 1', ...]]

Body:
Given:

answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "',],
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "',]
]

You can use regexes to parse each string for the desired pattern p:

import re

p = re.compile(r'(?!.*\[)(\w+\s*\d)')
new_answers = []
for lst in answers:
    new_answers.append([re.search(p, s).groups(0)[0] for s in lst])
new_answers
# [['person1', 'answer 1', 'answer 0'], ['person2', 'answer 3', 'answer 1']]

This particular pattern ignores characters behind the first bracket "[" and finds letters with zero or more spaces and digits.


问:
When the dereference operator (*) is overloaded, is the usage of *this affected?
For example,

```<code>class Person{
        string name;
    public:
        T& operator*(){
            return name;
        }
        bool operator==(const Person &rhs){
            return this->name == rhs.name;
        }
        bool operator!=(const Person &rhs){
            return !(*this == rhs); // Will *this be the string name or the Person?
        }
}
</code>```

If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

It would be quite a hindrance if I couldn't overload * without giving up usage of *this.

答:
You need an object of the class rather than the pointer to class object to invoke the overloaded * operator.

```<code>Person *ptr = new Person;
Person p1 = *ptr;   // does not invoke * operator but returns the object pointed by ptr
string str = *p1 // invokes the overloaded operator as it is called on an object.
</code>```

Same is the case with this pointer. To invoke * operator with this pointer, you will have to dereference twice:

```<code>std::string str = *(*this);
</code>```

Body:
For example,

class Person{
        string name;
    public:
        T& operator*(){
            return name;
        }
        bool operator==(const Person &rhs){
            return this->name == rhs.name;
        }
        bool operator!=(const Person &rhs){
            return !(*this == rhs); // Will *this be the string name or the Person?
        }
}

If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

It would be quite a hindrance if I couldn't overload * without giving up usage of *this.

Body:
You need an object of the class rather than the pointer to class object to invoke the overloaded * operator.

Person *ptr = new Person;
Person p1 = *ptr;   // does not invoke * operator but returns the object pointed by ptr
string str = *p1 // invokes the overloaded operator as it is called on an object.

Same is the case with this pointer. To invoke * operator with this pointer, you will have to dereference twice:

std::string str = *(*this);


问:
Remove the first par of bracket from an Array Swift 3
I have this array with double pairs of bracket [["0": 5, "2": 10]] and I want to convert it to ["5","10"] or [5,10]</p>

答:
This will do the trick. We're just extracting the dictionary values and creating an array. If you had a long list you could put your dictionary through a for-loop.</p>

```<code>    let dictionary = [["0": 5, "2": 10]]
    let array = [dictionary[0]["0"]!,dictionary[0]["2"]!]
    print("array: \(array)")
</code>```

Body:
This will do the trick. We're just extracting the dictionary values and creating an array. If you had a long list you could put your dictionary through a for-loop.

    let dictionary = [["0": 5, "2": 10]]
    let array = [dictionary[0]["0"]!,dictionary[0]["2"]!]
    print("array: \(array)")


问:
Update with percentage calculation on the same table
I have a table like this:

```<code>ItemID      PersonID  Score      Percentage
==========================================
1             1       10         [ = 10 / 10+30 = 25%]
1             2       30         [ = 30 / 10+30 = 75%]
2             1       20         [ = 20 / 20+40 = 33%]
2             2       40         [ = 40 / 20+40 = 67%]
</code>```

The data on "Percentage" is not entered but is auto-calculated at certain time interval.
The calculation is Percentage = Score / Total Score of the ItemID

Instead of using "SELECT-do the maths-UPDATE" method, I'm trying to write a single SQL to update the "Percentage".

What I tried is like this:

```<code>UPDATE tb_temp AS t1
    SET t1.Percentage =
        CEIL( t1.Score /
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID)
        );
</code>```

But it doesn't work.(Error Code : 1093 You can't specify target table 't1' for update in FROM clause).

Any idea?

答:
```<code>UPDATE tb_temp AS t1
    SET t1.Percentage =
        CEIL( t1.Score /
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 left join tb_temp AS t3 on t2.ItemID = t3.ItemID)
        );
</code>```

Body:
I have a table like this:

ItemID      PersonID  Score      Percentage
==========================================
1             1       10         [ = 10 / 10+30 = 25%]
1             2       30         [ = 30 / 10+30 = 75%]
2             1       20         [ = 20 / 20+40 = 33%]
2             2       40         [ = 40 / 20+40 = 67%]

The data on "Percentage" is not entered but is auto-calculated at certain time interval.
The calculation is Percentage = Score / Total Score of the ItemID

Instead of using "SELECT-do the maths-UPDATE" method, I'm trying to write a single SQL to update the "Percentage".

What I tried is like this:

UPDATE tb_temp AS t1
    SET t1.Percentage =
        CEIL( t1.Score /
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID)
        );

But it doesn't work.(Error Code : 1093 You can't specify target table 't1' for update in FROM clause).

Any idea?

ContentLicense: CC BY-SA 2.5


问:
Multilayer perceptron in scikit-learn
I am trying to code a multilayer perceptron in scikit learn 0.18dev using MLPClassifier. I have used the solver lbgfs, however it gives me the warning :
ConvergenceWarning: Stochastic Optimizer: Maximum iterations reached and the optimization hasn't converged yet.
  % (), ConvergenceWarning)

How can I fix this?

答:
How about setting hidden_layer_sizes and max_iter parameters?

```<code>mlp = MLPClassifier(solver='lbfgs', hidden_layer_sizes=[100], max_iter=2000, activation='logistic')
</code>```

Title: Multilayer perceptron in scikit-learn

Body:
How about setting hidden_layer_sizes and max_iter parameters?

mlp = MLPClassifier(solver='lbfgs', hidden_layer_sizes=[100], max_iter=2000, activation='logistic')


问:
Column count of mysql.user is wrong. Expected 42, found 44. The table is probably corrupted
Currently I'm using the newest version of ISPConfig 3. Today I wanted to add a db and user. It didn't work. Then I tried it on PHPmyadmin and it didn't work.

When I tried to add a user in PHPMyadmin Users Panel I received the following error message:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '* TO 'test'@'localhost'' at line 1

The output from /var/log/mysql/error.log:

[ERROR] Column count of mysql.user is wrong. Expected 42, found 44.
  The table is probably corrupted

Mysql Version: 5.5.55-0+deb8u1
PHPMyadmin Version: 4:4.2.12-2+deb8u2

Debian Linux 8

答:
Today I ran into the same problem after I did a dist-upgrade of a Debian Jessie 8 staging box. After some Investigation I found out, that the mysql table structure differs from what mysql-5.5.55 expects to find. I just compared the corrupted mysql database with a freshly installed one and created a little patch file, that should correct the error. Not sure if this works under other conditions, too. So, be careful using this patch and backup /var/lib/mysql and /etc/mysql before doing something nasty ;) I'll take no responsibility for any kind of damages possibly arising by this patch. Use it at your very own risk.

First of all MAKE BACKUPS!! and even more BACKUPS!! e.g. you could give mysqlsafebackup a try (Look at https://github.com/VerboteneZone/MySQLSafeBackup), an encrypting and compressing MySQL backup solution, written by me.

Download the following patch to your box:

```<code># wget https://download.rent-an.expert/mysql-patch-5.5.55.sql.gz
</code>```

Make sure, that no instance is currently accessing your MySQL server (stop services like apache2, postfix or whatever normally accesses the MySQL server). If you made yourself sure, that you are alone in the dark, apply the patch and force a mysql upgrade with the following commands:

```<code># zcat mysql-patch-5.5.55.sql.gz | mysql -uroot -p mysql
# mysql_upgrade --force -uroot -p
</code>```

If anything worked without any error, restart your MySQL service:

```<code># service mysql stop
# service mysql start
</code>```

After that, try to create a testuser to see, if the patch has been applied correctly:

```<code># mysql -uroot -p
</code>```

CREATE USER 'Testuser123'@'localhost' IDENTIFIED BY 'Pass0worZ';

You should get a message like:

Query OK, 0 rows affected (0.00 sec)

Now, you can safely delete your testuser again, with:

DROP USER 'Testuser123'@'localhost';

Anyway, if something went wrong, restore your backup and try again ;)

Hope that helps.

Body:
Today I ran into the same problem after I did a dist-upgrade of a Debian Jessie 8 staging box. After some Investigation I found out, that the mysql table structure differs from what mysql-5.5.55 expects to find. I just compared the corrupted mysql database with a freshly installed one and created a little patch file, that should correct the error. Not sure if this works under other conditions, too. So, be careful using this patch and backup /var/lib/mysql and /etc/mysql before doing something nasty ;) I'll take no responsibility for any kind of damages possibly arising by this patch. Use it at your very own risk.

First of all MAKE BACKUPS!! and even more BACKUPS!! e.g. you could give mysqlsafebackup a try (Look at https://github.com/VerboteneZone/MySQLSafeBackup), an encrypting and compressing MySQL backup solution, written by me.

Download the following patch to your box:

# wget https://download.rent-an.expert/mysql-patch-5.5.55.sql.gz

Make sure, that no instance is currently accessing your MySQL server (stop services like apache2, postfix or whatever normally accesses the MySQL server). If you made yourself sure, that you are alone in the dark, apply the patch and force a mysql upgrade with the following commands:

# zcat mysql-patch-5.5.55.sql.gz | mysql -uroot -p mysql
# mysql_upgrade --force -uroot -p

If anything worked without any error, restart your MySQL service:

# service mysql stop
# service mysql start

After that, try to create a testuser to see, if the patch has been applied correctly:

# mysql -uroot -p

CREATE USER 'Testuser123'@'localhost' IDENTIFIED BY 'Pass0worZ';

You should get a message like:

Query OK, 0 rows affected (0.00 sec)

Now, you can safely delete your testuser again, with:

DROP USER 'Testuser123'@'localhost';

Anyway, if something went wrong, restore your backup and try again ;)

Hope that helps.


答:
Simply add this to your code and it should work the way you want it to

```<code>if(!ha.includes("%")) {
  ha = ha + "%";
}
</code>```

Applied to your code:

```<code>function viewGraph() {
  $(".column").css("height", "0");
  $("table tr").each(function(index) {
    var ha = $(this).children("td").eq(1).text();

    // Simply add this.
    if(!ha.includes("%")) {
      ha = ha + "%";
    }

    $("#col" + index)
      .animate({ height: ha }, 1500)
      .html("<div>" + ha + "</div>");
  });
}
$(document).ready(function() {
  viewGraph();
});
</code>```

Hopefully this helps you out.

Title: How do I change to whole number instead of % in this codepen

Body:
Simply add this to your code and it should work the way you want it to

if(!ha.includes("%")) {
  ha = ha + "%";
}

Applied to your code:

function viewGraph() {
  $(".column").css("height", "0");
  $("table tr").each(function(index) {
    var ha = $(this).children("td").eq(1).text();

    // Simply add this.
    if(!ha.includes("%")) {
      ha = ha + "%";
    }

    $("#col" + index)
      .animate({ height: ha }, 1500)
      .html("<div>" + ha + "</div>");
  });
}
$(document).ready(function() {
  viewGraph();
});

Hopefully this helps you out.


问:
Dependency conflict on fresh installed laravel
I've been trying to create a new project using laravel composer CLI, with no success...

When i try to make it, i get the following error:

```<code>➜  larapjs export PATH="$PATH:$HOME/.composer/vendor/bin"
➜  larapjs laravel new testp
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
  Problem 2
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires ext-dom * -> the requested PHP extension dom is missing from your system.

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.0/cli/php.ini
    - /etc/php/7.0/cli/conf.d/10-mysqlnd.ini
    - /etc/php/7.0/cli/conf.d/10-opcache.ini
    - /etc/php/7.0/cli/conf.d/10-pdo.ini
    - /etc/php/7.0/cli/conf.d/20-calendar.ini
    - /etc/php/7.0/cli/conf.d/20-ctype.ini
    - /etc/php/7.0/cli/conf.d/20-exif.ini
    - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.0/cli/conf.d/20-ftp.ini
    - /etc/php/7.0/cli/conf.d/20-gd.ini
    - /etc/php/7.0/cli/conf.d/20-gettext.ini
    - /etc/php/7.0/cli/conf.d/20-iconv.ini
    - /etc/php/7.0/cli/conf.d/20-json.ini
    - /etc/php/7.0/cli/conf.d/20-mbstring.ini
    - /etc/php/7.0/cli/conf.d/20-mcrypt.ini
    - /etc/php/7.0/cli/conf.d/20-mysqli.ini
    - /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/7.0/cli/conf.d/20-phar.ini
    - /etc/php/7.0/cli/conf.d/20-posix.ini
    - /etc/php/7.0/cli/conf.d/20-readline.ini
    - /etc/php/7.0/cli/conf.d/20-shmop.ini
    - /etc/php/7.0/cli/conf.d/20-sockets.ini
    - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.0/cli/conf.d/20-zip.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
Application ready! Build something amazing.
</code>```

Since i am new to composer, i don't know where to start to solve this conflict issue.

Any suggestions would be appreciated.

答:
```<code>sudo apt-get install php-xml
</code>```

Solved the issue.

Body:
I've been trying to create a new project using laravel composer CLI, with no success...

When i try to make it, i get the following error:

➜  larapjs export PATH="$PATH:$HOME/.composer/vendor/bin"
➜  larapjs laravel new testp
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
  Problem 2
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires ext-dom * -> the requested PHP extension dom is missing from your system.

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.0/cli/php.ini
    - /etc/php/7.0/cli/conf.d/10-mysqlnd.ini
    - /etc/php/7.0/cli/conf.d/10-opcache.ini
    - /etc/php/7.0/cli/conf.d/10-pdo.ini
    - /etc/php/7.0/cli/conf.d/20-calendar.ini
    - /etc/php/7.0/cli/conf.d/20-ctype.ini
    - /etc/php/7.0/cli/conf.d/20-exif.ini
    - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.0/cli/conf.d/20-ftp.ini
    - /etc/php/7.0/cli/conf.d/20-gd.ini
    - /etc/php/7.0/cli/conf.d/20-gettext.ini
    - /etc/php/7.0/cli/conf.d/20-iconv.ini
    - /etc/php/7.0/cli/conf.d/20-json.ini
    - /etc/php/7.0/cli/conf.d/20-mbstring.ini
    - /etc/php/7.0/cli/conf.d/20-mcrypt.ini
    - /etc/php/7.0/cli/conf.d/20-mysqli.ini
    - /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/7.0/cli/conf.d/20-phar.ini
    - /etc/php/7.0/cli/conf.d/20-posix.ini
    - /etc/php/7.0/cli/conf.d/20-readline.ini
    - /etc/php/7.0/cli/conf.d/20-shmop.ini
    - /etc/php/7.0/cli/conf.d/20-sockets.ini
    - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.0/cli/conf.d/20-zip.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
Application ready! Build something amazing.

Since i am new to composer, i don't know where to start to solve this conflict issue.

Any suggestions would be appreciated.

Body:
sudo apt-get install php-xml

Solved the issue.


问:
Load every objects saved as json
I'm saving my playlists as json file, but oncreate I want to load every playlist already saved.

This is my save function;

```<code>void Kaydet(PLAYLIST liste_mp3)
{

    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(liste_mp3);
    prefsEditor.putString(liste_mp3.ad, json);
    prefsEditor.commit();
}
</code>```

And this is PLAYLIST class,

```<code>public class PLAYLIST
    {
        public String ad;
        public ArrayList<MP3> liste;

        public PLAYLIST(String ad1,ArrayList<MP3> liste1)
        {
            ad = ad1;
            liste = liste1;
        }
        public String toString()
        {
            return ad;
        }
        public ArrayList<MP3> LISTE()
        {
            return liste;
        }
    }
</code>```

This where I load specific one;

```<code>if(Yukle("A liste") != null) {
        playlist.add(Yukle("A liste"));
    } else { playlist.add(new PLAYLIST("A liste",a_liste)); }
</code>```

and this is Load function,

```<code>PLAYLIST Yukle(String playlist_name)
{
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    Gson gson = new Gson();
    String json = appSharedPrefs.getString(playlist_name, "");
    PLAYLIST p = gson.fromJson(json, PLAYLIST.class);
    return p;
}
</code>```

答:
I fixed my problem with that idea, I created a new function that saves names of all playlists as string arraylist, and load string arraylist of playlists' names then make a for-loop and load per playlist with name.

This is in onCreate()

```<code>ArrayList<String> yukleniyor = YukleHepsi();
        if(yukleniyor != null) {
            for (String isimler : yukleniyor) {
               playlist.add(Yukle(isimler));
            }
        }
</code>```

This function loads names:

```<code>ArrayList<String> YukleHepsi()
    {
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        Gson gson = new Gson();
        String json = appSharedPrefs.getString("isimler", "");
        ArrayList<String> p = gson.fromJson(json, ArrayList.class);
        return p;
    }
</code>```

And this function saves the names of all playlits,

```<code>void KaydetHepsi()
    {
        ArrayList<String> isimler = new ArrayList<String>();
        for(PLAYLIST p: playlist)
        {
            if(p.ad != "None") {
                isimler.add(p.ad);
            }
        }
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(isimler);
        prefsEditor.putString("isimler", json);
        prefsEditor.commit();
    }
</code>```

Title: Load every objects saved as json

Body:
I'm saving my playlists as json file, but oncreate I want to load every playlist already saved.

This is my save function;

void Kaydet(PLAYLIST liste_mp3)
{

    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(liste_mp3);
    prefsEditor.putString(liste_mp3.ad, json);
    prefsEditor.commit();
}

And this is PLAYLIST class,

public class PLAYLIST
    {
        public String ad;
        public ArrayList<MP3> liste;

        public PLAYLIST(String ad1,ArrayList<MP3> liste1)
        {
            ad = ad1;
            liste = liste1;
        }
        public String toString()
        {
            return ad;
        }
        public ArrayList<MP3> LISTE()
        {
            return liste;
        }
    }

This where I load specific one;

if(Yukle("A liste") != null) {
        playlist.add(Yukle("A liste"));
    } else { playlist.add(new PLAYLIST("A liste",a_liste)); }

and this is Load function,

PLAYLIST Yukle(String playlist_name)
{
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    Gson gson = new Gson();
    String json = appSharedPrefs.getString(playlist_name, "");
    PLAYLIST p = gson.fromJson(json, PLAYLIST.class);
    return p;
}

Body:
I fixed my problem with that idea, I created a new function that saves names of all playlists as string arraylist, and load string arraylist of playlists' names then make a for-loop and load per playlist with name.

This is in onCreate()

ArrayList<String> yukleniyor = YukleHepsi();
        if(yukleniyor != null) {
            for (String isimler : yukleniyor) {
               playlist.add(Yukle(isimler));
            }
        }

This function loads names:

ArrayList<String> YukleHepsi()
    {
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        Gson gson = new Gson();
        String json = appSharedPrefs.getString("isimler", "");
        ArrayList<String> p = gson.fromJson(json, ArrayList.class);
        return p;
    }

And this function saves the names of all playlits,

void KaydetHepsi()
    {
        ArrayList<String> isimler = new ArrayList<String>();
        for(PLAYLIST p: playlist)
        {
            if(p.ad != "None") {
                isimler.add(p.ad);
            }
        }
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(isimler);
        prefsEditor.putString("isimler", json);
        prefsEditor.commit();
    }


答:
```<code>let dict = [["0": 5, "2": 10]]
let dict0 = dict[0]
var array: [Int] = []
array.append(dict0["0"]!)
array.append(dict0["2"]!)
</code>```

Title: Remove the first par of bracket from an Array Swift 3

Body: I have this array with double pairs of bracket [["0": 5, "2": 10]] and I want to convert it to ["5","10"] or [5,10]


问:
How to dynamically load a component with settings in CakePHP 2?
I understand that we can pass settings for a component when we define the component at the start of a controller. Example from the CakePHP 2.0 Cookbook

```<code>public $components = array(
    'Auth' => array(
        'authorize' => array('controller'),
        'loginAction' => array(
            'controller' => 'users',
            'action' => 'login'
        )
    ),
    'Cookie' => array('name' => 'CookieMonster')
);
</code>```

But I usually load components on the fly like so (also from the Cookbook)

```<code>$this->OneTimer = $this->Components->load('OneTimer');
</code>```

While using the second method (loading a component on the fly), how can I pass settings to it so that I can use them in the constructor to correctly setup the component based on the settings?

Any help would be greatly appreciated.

答:
2 minutes after asking the question I looked at the load function in the library and found that settings is the second argument for the function.

```<code>public function load($component, $settings = array())
</code>```

So I just need to supply the settings as the second parameter when I load components on the fly.

Body:
I understand that we can pass settings for a component when we define the component at the start of a controller. Example from the CakePHP 2.0 Cookbook

public $components = array(
    'Auth' => array(
        'authorize' => array('controller'),
        'loginAction' => array(
            'controller' => 'users',
            'action' => 'login'
        )
    ),
    'Cookie' => array('name' => 'CookieMonster')
);

But I usually load components on the fly like so (also from the Cookbook)

$this->OneTimer = $this->Components->load('OneTimer');

While using the second method (loading a component on the fly), how can I pass settings to it so that I can use them in the constructor to correctly setup the component based on the settings?

Any help would be greatly appreciated.

Body:
2 minutes after asking the question I looked at the load function in the library and found that settings is the second argument for the function.

public function load($component, $settings = array())

So I just need to supply the settings as the second parameter when I load components on the fly.


问:
How to update multiple a rows in mysql
I have a database table like :

```<code>        +---+-------------+
        |id |ship_method  |
        +---+-------------+
        | 1 |freeshipping |
        | 1 | flatrate    |
        | 2 |    DHL      |
        | 3 | matrixrate  |
        | 1 |    courier  |
        +---+-------------+
</code>```

So, I want to update ship_method from frontend form based on multi option selected.
For eg : if Id 1 selects freeshipping , DHL , matrixrate then the corresponding values of ship_method should be updated.

What is the mysql query to update in this case. I tried but couldn't find how to update such multiple rows at once.

答:
Delete previous data and insert new all</p>

```<code>delete from table where id=1;
insert into table_name(id,ship_method) values(1,'freeshipping'),(1,'DHL'),(1,'matrixrate');
</code>```

Title: How to update multiple a rows in mysql

Body:
I have a database table like :

        +---+-------------+
        |id |ship_method  |
        +---+-------------+
        | 1 |freeshipping |
        | 1 | flatrate    |
        | 2 |    DHL      |
        | 3 | matrixrate  |
        | 1 |    courier  |
        +---+-------------+

So, I want to update ship_method from frontend form based on multi option selected.
For eg : if Id 1 selects freeshipping , DHL , matrixrate then the corresponding values of ship_method should be updated.

What is the mysql query to update in this case. I tried but couldn't find how to update such multiple rows at once.

Body:
Delete previous data and insert new all

delete from table where id=1;
insert into table_name(id,ship_method) values(1,'freeshipping'),(1,'DHL'),(1,'matrixrate');


问:
an error during a type conversion in Swift 3
I’m studying Swift Animation. Its material is written in Swift 2, so I had to convert its original code into Swift 3. I have learned from it along, but now I have a big problem. Xcode successfully built this code but produced a runtime error message. (I attached the image file.)

I can’t solve this at all on my own as I guess I have little experience. How can I fix this? Help.

```<code>func setQuote() {

    //fadeOut

    //getting data from API
    let dataService = DataService()
    dataService.getQuoteData {(quote, author) -> Void in

        UIView.animate(withDuration: 0.5, animations: {

            //fadeIn and backgroundColor

            //quote
            self.quoteLabel.text = quote

            //author - optional binding

            //if no author

            }, completion:nil)

    }
}

class DataService {

    func getQuoteData(_ completion: @escaping (_ quote: String, _ author: String?) -> ()) {

        let url = URL(string: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json")!

        URLSession.shared.dataTask(with: url, completionHandler: { ( data: Data?, response: URLResponse?, error: NSError?) -> Void in

            do {
                let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

                let aQuote = jsonDictionary["quoteText"] as! String
                let aAuthor = jsonDictionary["quoteAuthor"] as! String

                DispatchQueue.main.async(execute: { () -> Void in
                    completion(aQuote, aAuthor)
                })

            } catch {
                print("invalid json query")
            }
        } as! (Data?, URLResponse?, Error?) -> Void).resume()
    }

}
</code>```

答:
You can try rewrite it like this

```<code>    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        do {
            let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

            let aQuote = jsonDictionary["quoteText"] as! String
            let aAuthor = jsonDictionary["quoteAuthor"] as! String

            DispatchQueue.main.async(execute: { () -> Void in
                completion(aQuote, aAuthor)
            })

        } catch {
            print("invalid json query")
        }
    }

    task.resume()
</code>```

or simply change the ( data: Data?, response: URLResponse?, error: NSError?) -> Void to ( data, response, error) -> Void and remove the as! ...

Body:
I’m studying Swift Animation. Its material is written in Swift 2, so I had to convert its original code into Swift 3. I have learned from it along, but now I have a big problem. Xcode successfully built this code but produced a runtime error message. (I attached the image file.)

I can’t solve this at all on my own as I guess I have little experience. How can I fix this? Help.

func setQuote() {

    //fadeOut

    //getting data from API
    let dataService = DataService()
    dataService.getQuoteData {(quote, author) -> Void in

        UIView.animate(withDuration: 0.5, animations: {

            //fadeIn and backgroundColor

            //quote
            self.quoteLabel.text = quote

            //author - optional binding

            //if no author

            }, completion:nil)

    }
}

class DataService {

    func getQuoteData(_ completion: @escaping (_ quote: String, _ author: String?) -> ()) {

        let url = URL(string: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json")!

        URLSession.shared.dataTask(with: url, completionHandler: { ( data: Data?, response: URLResponse?, error: NSError?) -> Void in

            do {
                let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

                let aQuote = jsonDictionary["quoteText"] as! String
                let aAuthor = jsonDictionary["quoteAuthor"] as! String

                DispatchQueue.main.async(execute: { () -> Void in
                    completion(aQuote, aAuthor)
                })

            } catch {
                print("invalid json query")
            }
        } as! (Data?, URLResponse?, Error?) -> Void).resume()
    }

}

Body:
You can try rewrite it like this

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        do {
            let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

            let aQuote = jsonDictionary["quoteText"] as! String
            let aAuthor = jsonDictionary["quoteAuthor"] as! String

            DispatchQueue.main.async(execute: { () -> Void in
                completion(aQuote, aAuthor)
            })

        } catch {
            print("invalid json query")
        }
    }

    task.resume()

or simply change the ( data: Data?, response: URLResponse?, error: NSError?) -> Void to ( data, response, error) -> Void and remove the as! ...


问:
Angular 2 .Replace Pipe
I've created a replace pipe as follows:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    let newValue = value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, '<br>');
    return `${newValue}`;
  }
}
</code>```

I declared it in @NgModule section of app.module. I am using it on the page as follows:

```<code><ion-card-content [innerHtml]="Message | linky | replace"></ion-card-content>
</code>```

I can't figure out where I am making the mistake because I can't get it to work. I tried removing linky pipe but no luck. Any help is much appriciated. Thanks Guys

答:
So It turns out my replace pipe works with everything example "value.replace('bit', '
');" but whatever I try to do It doesn't not work for "value.replace('/\n/g', '
');" Any Ideas?

Title: Angular 2 .Replace Pipe

Body:
I've created a replace pipe as follows:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    let newValue = value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, '
');
    return `${newValue}`;
  }
}

I declared it in @NgModule section of app.module. I am using it on the page as follows:

<ion-card-content [innerHtml]="Message | linky | replace"></ion-card-content>

I can't figure out where I am making the mistake because I can't get it to work. I tried removing linky pipe but no luck. Any help is much appriciated. Thanks Guys

Body: So It turns out my replace pipe works with everything example "value.replace('bit', '<br>');" but whatever I try to do It doesn't not work for "value.replace('/\n/g', '<br>');" Any Ideas?


问:
Alternative for System.out.print in Android
Could someone tell me what is the alternative for System.out.print in Android?

答: You can also use System.out.println(). You will see the output in the Logcat.


问:
?? Operator - Using in one liner condition
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.</p>

```<code>return file?.ImportStatus ?? ImportStatusEnum.Unknown;
</code>```

答:
Actually, the compiler will generate different code based on whether the ImportStatus is nullable or not. If it is NOT nullable, so like this:

```<code>public ImportStatusEnum ImportStatus {get; set;}
</code>```

then the compiler will generate this:

```<code>return file != null ? file.ImportStatus : ImportStatusEnum.Unknown;
</code>```

which is the same as

```<code>if (file != null)
    return file.ImportStatus;
return ImportStatusEnum.Unknown;
</code>```

If the property is nullable, so like this:

```<code>public ImportStatusEnum? ImportStatus {get; set;}
//OR
public Nullable<ImportStatusEnum> ImportStatus {get; set;}
</code>```

then it will do what @dasblinkenlight and @garethb have indicated in their answers.

Body:
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.

return file?.ImportStatus ?? ImportStatusEnum.Unknown;

Body:
Actually, the compiler will generate different code based on whether the ImportStatus is nullable or not. If it is NOT nullable, so like this:

public ImportStatusEnum ImportStatus {get; set;}

then the compiler will generate this:

return file != null ? file.ImportStatus : ImportStatusEnum.Unknown;

which is the same as

if (file != null)
    return file.ImportStatus;
return ImportStatusEnum.Unknown;

If the property is nullable, so like this:

public ImportStatusEnum? ImportStatus {get; set;}
//OR
public Nullable<ImportStatusEnum> ImportStatus {get; set;}

then it will do what @dasblinkenlight and @garethb have indicated in their answers.


问:
UILabel get Frame width or height
```<code>`lblAddress.frame.width`
`lblAddress.frame.size.width`
</code>```

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

答:
They are (almost) the same.
One is width of CGRect, the other one is width of CGSize.

The only difference is that frame.width will always return positive values, as frame.size.width may return in some circumstances negative values.

I would use the shorthand frame.width directly if I only care about standardized geometry.

Title: UILabel get Frame width or height

Body:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.


问:
why session_start in php is throwing warning saying file large
I didn't change any code, all of a sudden when I visited one of the webpages, I see

Warning: session_start() [function.session-start]: open(..)Failed: File too large .. index.php on line 2.

Another error is:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent`

Line1 : <?php

Line2 : session_start ();

Questions:

what is the reason for error that tells File too large? what file is large?

why all-of a sudden there is an error without any file modification being done?

why it is throwing 'headers already sent', when there is nothing defined before session_start, not even a space ?

How to fix this issue?

答:
1. what is the reason for error that tells File too large? what file is large?

This seems to be the hosting provider issue, as the original file was never modified, and the webpage has been tried from multiple browsers even after clearing the cache.
When you do session_save_path("../_session1001"); that is mentioned below, you can see that your session is written to that path, so may be that this file was becoming too large in your shared memory,and now that I explicitly mentioned a physical space to write the session files to, this error is no more.

4. How to fix this issue?

Create a directory named say '_session1001' and give chmod 755 so your webserver (app) can write to it.

Add this line before session_start
session_save_path("../_session1001");

Ensure you protect the directory via .htaccess file.

ie:
<?php
session_save_path("../_session1001");
session_start();

Read more here : http://php.net/session_save_path

Note:

Debian does not use the default garbage collector for sessions. Instead, it sets session.gc_probability to zero and it runs a cron job to clean up old session data in the default directory.

As a result, if your site sets a custom location with session_save_path() you also need to set a value for session.gc_probability,

e.g.:

<?php
session_save_path('/home/example.com/sessions');
ini_set('session.gc_probability', 1);
?>

Otherwise, old files in '/home/example.com/sessions' will never get removed!


问:
Python kafka consumer group id issue
AFAIK,

The concept of partitions and (consumer) groups in kafka was introduced to implement parallelism. I am working with kafka through python. I have a certain topic, which has (say) 2 partitions. This means, if I start a consumer group with 2 consumers in it, they will be mapped(subscribed) to different partitions.

But, using kafka library in python, I came across a weird issue. I started 2 consumers with essentially the same group-ids, and started the threads for them to consume messages.

But, every message in the kafka-stream is being consumed by both of them !! This seems ridiculous to me, and even conceptually incorrect. Is there anyway I can map the consumers to certain (distinct) partitions manually (if they are not mapped to different partitions automatically)?

Here is the code:

```<code>from kafka import KafkaConsumer
import thread

def con1(consumer):
    for msg in consumer:
        print msg

consumer1 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])
consumer2 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])

thread.start_new_thread(con1, (consumer1,))
thread.start_new_thread(con1, (consumer2,))
</code>```

Here is the output for some messages that I produced using kafka-console-producer:

```<code>ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
</code>```

while expected was one of each. BTW, this topic k-test has 2 partitions.

答:
```<code>from kafka import KafkaConsumer
from kafka import TopicPartition

TOPIC = "k-test"
PARTITION_0 = 0
PARTITION_1 = 1

consumer_0 = KafkaConsumer(
    TOPIC, group_id='grp1', bootstrap_servers=['10.50.23.120:9092']
)
consumer_1 = KafkaConsumer(
    TOPIC, group_id='grp1', bootstrap_servers=['10.50.23.120:9092']
)
topic_partition_0 = TopicPartition(TOPIC, PARTITION_0)
topic_partition_1 = TopicPartition(TOPIC, PARTITION_1)
# format: topic, partition
consumer_0.assign([topic_partition_0])
consumer_1.assign([topic_partition_1])
</code>```

assign() might be work for you, but once you use it, kafka will not balance consumers automatically when there is consumer stop working.

Title: Python kafka consumer group id issue

Body:
AFAIK,

The concept of partitions and (consumer) groups in kafka was introduced to implement parallelism. I am working with kafka through python. I have a certain topic, which has (say) 2 partitions. This means, if I start a consumer group with 2 consumers in it, they will be mapped(subscribed) to different partitions.

But, using kafka library in python, I came across a weird issue. I started 2 consumers with essentially the same group-ids, and started the threads for them to consume messages.

But, every message in the kafka-stream is being consumed by both of them !! This seems ridiculous to me, and even conceptually incorrect. Is there anyway I can map the consumers to certain (distinct) partitions manually (if they are not mapped to different partitions automatically)?

Here is the code:

from kafka import KafkaConsumer
import thread

def con1(consumer):
    for msg in consumer:
        print msg

consumer1 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])
consumer2 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])

thread.start_new_thread(con1, (consumer1,))
thread.start_new_thread(con1, (consumer2,))

Here is the output for some messages that I produced using kafka-console-producer:

ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')

while expected was one of each. BTW, this topic k-test has 2 partitions.

Body:
from kafka import KafkaConsumer
from kafka import TopicPartition

TOPIC = "k-test"
PARTITION_0 = 0
PARTITION_1 = 1

consumer_0 = KafkaConsumer(
    TOPIC, group_id='grp1', bootstrap_servers=['10.50.23.120:9092']
)
consumer_1 = KafkaConsumer(
    TOPIC, group_id='grp1', bootstrap_servers=['10.50.23.120:9092']
)
topic_partition_0 = TopicPartition(TOPIC, PARTITION_0)
topic_partition_1 = TopicPartition(TOPIC, PARTITION_1)
# format: topic, partition
consumer_0.assign([topic_partition_0])
consumer_1.assign([topic_partition_1])

assign() might be work for you, but once you use it, kafka will not balance consumers automatically when there is consumer stop working.


问:
How to fetch data to multiple entity objects using single Linq statement
I have two entity classes

```<code>[Table("Payment")]
public class Payment
{
    public Payment()
    {
        this.SchemeMember = new HashSet<SchemeMember>();
    }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long PaymentUid { get; set; }

    /// <summary>
    /// Member U id
    /// </summary>
    public int MemberUid { get; set; }

    public  ICollection<SchemeMember> SchemeMember { get; set; }
}

public class SchemeMember
{
    /// <summary>
    /// Gets or sets Member UID
    /// </summary>
    public int MemberUid { get; set; }
}
</code>```

These two entities are related by MemberUid. Now when I try to fetch the data using the below LINQ, SchemeMember count is always 0. I have already disabled Lazyloading to false.

```<code>var result =  (from payment in this.DbContext.Payment
             join schemeMember in this.DbContext.SchemeMember on
                                   Payment.MemberUid equals
                                   schemeMember.MemberUid
             select payment).ToList();
</code>```

Can any one kindly help me to figure out the issue? Thanks in advance.

答:
If your mappings are set up correctly, you shouldn't need to do any of that, use the references and let EF do the work.

Assuming you wanted to find payments with schema members that had a Value = "X":

var payments = DbContext.Payment.Where(p=>p.SchemeMember.Any(s=>s.Value == "X")).ToList();

Note: I've used the Fluent Linq methods, never did find the Linq-like-SQL syntax very intuitive. :)

I'd recommend using plural naming convention for child collection classes: I.e. Payment.SchemeMembers as it makes it very easy to visually resolve your single associations (I have a scheme member) from your multi ones. (I have a number of scheme members)

Body:
I have two entity classes

[Table("Payment")]
public class Payment
{
    public Payment()
    {
        this.SchemeMember = new HashSet<SchemeMember>();
    }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long PaymentUid { get; set; }

    ///
    /// Member U id
    ///
    public int MemberUid { get; set; }

    public  ICollection<SchemeMember> SchemeMember { get; set; }
}

public class SchemeMember
{
    ///
    /// Gets or sets Member UID
    ///
    public int MemberUid { get; set; }
}

These two entities are related by MemberUid. Now when I try to fetch the data using the below LINQ, SchemeMember count is always 0. I have already disabled Lazyloading to false.

var result =  (from payment in this.DbContext.Payment
             join schemeMember in this.DbContext.SchemeMember on
                                   Payment.MemberUid equals
                                   schemeMember.MemberUid
             select payment).ToList();

Can any one kindly help me to figure out the issue? Thanks in advance.


问:
adjust output with input field and add/minus button AngularJS
it is my first time to use angularjs
i am trying to make a sample code wherein the user can put a number on the field or he can use the button to increase/ decrease the number but not less than 0.

```<code>  <div data-ng-app='CountApp' data-ng-controller='CountCtrl'>
  <div class="outside-border">
    <input id="output_test" type="text" ng-model="count" style="width: 150px;">
    <div class="minus">
      <button class="button" id="test_sample" data-ng-click='count = count - 1'>-</button>
    </div>
    <div class="add">
      <button class="button" data-ng-click='count = count + 1'>+</button>
    </div>
  </div>
</div>

var app = angular.module('CountApp', []);

app.controller('CountCtrl', function($scope) {
  $scope.count = 1;
});
</code>```

Currently what is happening is that whenever there is no number on the field and user click  + button, the output is 1111111
or if the user enter a number (e.g. 35) the output becomes 3511111
can someone explain or help me with regards to this.

here is what i have done so far https://jsfiddle.net/wbuh2hrd/

答:
There are many ways to solve this, one of them is changing your input type to type="number"

If you don't like the buttons that appears when you mouseover on certain browsers, you can hide it using css (http://www.thatstevensguy.com/programming/disable-arrows-on-number-inputs/)

Edit: You can use min=0 to control minimum value in number type input.

Body:
it is my first time to use angularjs
i am trying to make a sample code wherein the user can put a number on the field or he can use the button to increase/ decrease the number but not less than 0.

    <input id="output_test" type="text" ng-model="count" style="width: 150px;">

      <button class="button" id="test_sample" data-ng-click='count = count - 1'>-</button>

      <button class="button" data-ng-click='count = count + 1'>+</button>

var app = angular.module('CountApp', []);

app.controller('CountCtrl', function($scope) {
  $scope.count = 1;
});

Currently what is happening is that whenever there is no number on the field and user click  + button, the output is 1111111
or if the user enter a number (e.g. 35) the output becomes 3511111
can someone explain or help me with regards to this.

here is what i have done so far https://jsfiddle.net/wbuh2hrd/


问:
Java - extract date from string using regex- failing
I'm trying to extract 2 dates from a string using regex- and for some reason - the regex doesn't extract dates- this is my code:

```<code>private  String[] getDate(String desc) {
    int count=0;
    String[] allMatches = new String[2];
    Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)").matcher(desc);
    while (m.find()) {
        allMatches[count] = m.group();
    }
    return allMatches;
}
</code>```

My string- desc is: "coming from the 11/25/2009 to the 11/30/2009"
and I get back a null array...

答:
A date pattern recognition algorithm to not only identify date pattern but also fetches probable date in Java date format. This algorithm is very fast and lightweight. The processing time is linear and all dates are identified in a single pass. Algorithm resolves date using tree traverse mechanism. Tree data structures are custom created to build supported date, time and month patterns.

The algorithm also acknowledges multiple space characters in between Date literals. E.g. DD DD DD and DD DD DD are considered as valid dates.

Following date-patterns are considered as valid and are identifiable using this algorithm.

dd MM(MM) yy(yy) yy(yy) MM(MM) dd MM(MM) dd yy(yy)

Where M is month literal is alphabet format like Jan or January

Allowed delimiters between dates are '/', '\', ' ', ',', '|', '-', ' '

It also recognizes trailing time pattern in following format hh(24):mm:ss.SSS am / pm hh(24):mm:ss am / pm hh(24):mm:ss am / pm

Resolution time is linear, no pattern matching or brute force is used. This algorithm is based on tree traversal and returns back, the list of date with following three components - date string identified in the text - converted & formatted date string - SimpleDateFormat

Using date string and the format string, users are free to convert the string into objects based on their requirements.

The algorithm library is available at maven central.

```<code><dependency>
    <groupId>net.rationalminds</groupId>
    <artifactId>DateParser</artifactId>
    <version>0.3.0</version>
</dependency>
</code>```

The sample code to use this is below.

```<code>import java.util.List;
 import net.rationalminds.LocalDateModel;
 import net.rationalminds.Parser;
 public class Test {
   public static void main(String[] args) throws Exception {
        Parser parser=new Parser();
        List<LocalDateModel> dates=parser.parse("Identified date :'2015-January-10 18:00:01.704', converted");
        System.out.println(dates);
   }
 }
</code>```

Output: [LocalDateModel{originalText=2015-january-10 18:00:01.704, dateTimeString=2015-1-10 18:00:01.704, conDateFormat=yyyy-MM-dd HH:mm:ss.SSS, start=18, end=46}]

Detailed blog at http://coffeefromme.blogspot.com/2015/10/how-to-extract-date-object-from-given.html

The complete source is available on GitHub at https://github.com/vbhavsingh/DateParser

Body:
I'm trying to extract 2 dates from a string using regex- and for some reason - the regex doesn't extract dates- this is my code:

private  String[] getDate(String desc) {
    int count=0;
    String[] allMatches = new String[2];
    Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)").matcher(desc);
    while (m.find()) {
        allMatches[count] = m.group();
    }
    return allMatches;
}

My string- desc is: "coming from the 11/25/2009 to the 11/30/2009"
and I get back a null array...

Body:
A date pattern recognition algorithm to not only identify date pattern but also fetches probable date in Java date format. This algorithm is very fast and lightweight. The processing time is linear and all dates are identified in a single pass. Algorithm resolves date using tree traverse mechanism. Tree data structures are custom created to build supported date, time and month patterns.

The algorithm also acknowledges multiple space characters in between Date literals. E.g. DD DD DD and DD DD DD are considered as valid dates.

Following date-patterns are considered as valid and are identifiable using this algorithm.

dd MM(MM) yy(yy) yy(yy) MM(MM) dd MM(MM) dd yy(yy)

Where M is month literal is alphabet format like Jan or January

Allowed delimiters between dates are '/', '\', ' ', ',', '|', '-', ' '

It also recognizes trailing time pattern in following format hh(24):mm:ss.SSS am / pm hh(24):mm:ss am / pm hh(24):mm:ss am / pm

Resolution time is linear, no pattern matching or brute force is used. This algorithm is based on tree traversal and returns back, the list of date with following three components - date string identified in the text - converted & formatted date string - SimpleDateFormat

Using date string and the format string, users are free to convert the string into objects based on their requirements.

The algorithm library is available at maven central.

<dependency>
    <groupId>net.rationalminds</groupId>
    <artifactId>DateParser</artifactId>
    <version>0.3.0</version>
</dependency>

The sample code to use this is below.

import java.util.List;
 import net.rationalminds.LocalDateModel;
 import net.rationalminds.Parser;
 public class Test {
   public static void main(String[] args) throws Exception {
        Parser parser=new Parser();
        List<LocalDateModel> dates=parser.parse("Identified date :'2015-January-10 18:00:01.704', converted");
        System.out.println(dates);
   }
 }

Output: [LocalDateModel{originalText=2015-january-10 18:00:01.704, dateTimeString=2015-1-10 18:00:01.704, conDateFormat=yyyy-MM-dd HH:mm:ss.SSS, start=18, end=46}]

Detailed blog at http://coffeefromme.blogspot.com/2015/10/how-to-extract-date-object-from-given.html

The complete source is available on GitHub at https://github.com/vbhavsingh/DateParser


问:
Using Visual C++ with R
I am wondering if there was a workaround for using the R package Rcpp within a Visual C++ project within Visual Studio. According to the Rcpp FAQ, this is not possible. I also came across another R package called R.NET. Can this only work with C# but there seems to be no examples from within Visual C++? Is there another option for this that I am missing? Even if I am forced to work with C#, can anyone envision latency issues with this for a high frequency trading environment?
Thanks for any feedback </p>

答:
Visual Studio works just fine with Rcpp. Has done for years. I disagree with Dirk Eddelbuettel.

This is an important fact - For example, there are very important libraries (Intels MKL, QT graphics framework) which are actually not compatible with minGW.

I maintain a (patched and cut-down) fork of Rcpp on github (https://github.com/rohan-shah/Rcpp) suitable for compilation with Visual Studio with cmake. The patch is something like five lines, I believe.

Disclaimer: It's fiddly to use, and you have to know what you're doing. If you do know what you're doing though, I've done quite a bit of the work for you. See https://github.com/rohan-shah/mpMap2 for an example of how to use patched Rcpp with Visual Studio.

Title: Using Visual C++ with R


问:
Get data from link in Ionic 3 Web App
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

```<code>this.cell = this.navParams.get('cell');
</code>```

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

答:
You could try plain old javascript. I dont think this is anything specific to ionic. And because it is not primarily navigation based then the NavParams would not work, i am guessing, you can do split like so

```<code>let myParam = location.search.split('cell=')[1];
</code>```

Ref: here

Title: Get data from link in Ionic 3 Web App

Body:
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

this.cell = this.navParams.get('cell');

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

Body:
You could try plain old javascript. I dont think this is anything specific to ionic. And because it is not primarily navigation based then the NavParams would not work, i am guessing, you can do split like so

let myParam = location.search.split('cell=')[1];

Ref: here


问:
Error: $injector:unpr Unknown Provider when try delete a record
I am going to delete a record in my asp.net mvc project by using angular js 1.3.13.

```<code> <tr ng-repeat="emp in employees track by $index">
            <td>
                <a href="#" class="btn btn-default btn-sm">
                    <i class="glyphicon glyphicon-edit"></i>
                </a>
            </td>
            <td>
                {{emp.EmployeeId}}
            </td>
            <td>
                {{emp.EmployeeName}}
            </td>
            <td>
                {{emp.Address}}
            </td>
            <td>
                {{emp.EmailId}}
            </td>
            <td>
                <a href="#"
                   ng-click="delFn($index)"
                   class="btn btn-default btn-sm">
                    <i class="glyphicon glyphicon-trash"></i>
                </a>
            </td>
        </tr>
</code>```

My controller.js code

```<code>app.controller("EmpCtrl", function ($scope, EmployeeService) {

GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
}
    $scope.delFn = function (index) {
        var response = confirm('Delete this Employee?');
        if (response) {
           $scope.employees.splice(index, 1);
           EmployeeService.deleteEmployee(index);
        }
     }
});
</code>```

In my service.js, I have

```<code>    app.service("EmployeeService", function ($http,id) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    this.deleteEmployee = function () {
        var url = "/Employee/DeleteEmployee/" + id;
        $http.delete(url)
            .success(function (result) {
                alert("Delete Successfully");
            })
            .error(function () {
                alert("Something wrong!");
            })
            .then(function () {
                window.location = '#/';
            })
    }
});
</code>```

In my asp.net controller, I Have the delete method

```<code> [HttpDelete]
    public void DeleteEmployee(int id)
    {
       // blah
    }
</code>```

But I get the error when debugging it in chrome.

angular.min.js:102 Error: [$injector:unpr] http://errors.angularjs.org/1.3.13/$injector/unpr?p0=idProvider%20%3C-%20id%20%3C-%20EmployeeService

So would you please advise me what is wrong?

答:
Move the id argument from the service construction function to the deleteEmployee function:

```<code>    //REMOVE `id` argument
    //app.service("EmployeeService", function ($http,id) {
    app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    //ADD `id` here
    //this.deleteEmployee = function () {
    this.deleteEmployee = function (id) {
        var url = "/Employee/DeleteEmployee" + id;
        return $http.delete(url)
            .then(function (response) {
                alert("Delete Successfully");
                return response;
            })
            .catch(function (errorResponse) {
                alert("Something wrong!");
                throw errorResponse;
            })
            .then(function () {
                window.location = '#/';
            })
    }
});
</code>```

From the error message link:

```<code>Unknown provider: idProvider <- id <- EmployeeService
</code>```

The injector was erroneously trying to inject a service named id.

Body:
I am going to delete a record in my asp.net mvc project by using angular js 1.3.13.

                {{emp.EmployeeId}}

                {{emp.EmployeeName}}

                {{emp.Address}}

                {{emp.EmailId}}

My controller.js code

app.controller("EmpCtrl", function ($scope, EmployeeService) {

GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
}
    $scope.delFn = function (index) {
        var response = confirm('Delete this Employee?');
        if (response) {
           $scope.employees.splice(index, 1);
           EmployeeService.deleteEmployee(index);
        }
     }
});

In my service.js, I have

    app.service("EmployeeService", function ($http,id) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    this.deleteEmployee = function () {
        var url = "/Employee/DeleteEmployee/" + id;
        $http.delete(url)
            .success(function (result) {
                alert("Delete Successfully");
            })
            .error(function () {
                alert("Something wrong!");
            })
            .then(function () {
                window.location = '#/';
            })
    }
});

In my asp.net controller, I Have the delete method

 [HttpDelete]
    public void DeleteEmployee(int id)
    {
       // blah
    }

But I get the error when debugging it in chrome.

angular.min.js:102 Error: [$injector:unpr] http://errors.angularjs.org/1.3.13/$injector/unpr?p0=idProvider%20%3C-%20id%20%3C-%20EmployeeService

So would you please advise me what is wrong?

Body:
Move the id argument from the service construction function to the deleteEmployee function:

    //REMOVE `id` argument
    //app.service("EmployeeService", function ($http,id) {
    app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    //ADD `id` here
    //this.deleteEmployee = function () {
    this.deleteEmployee = function (id) {
        var url = "/Employee/DeleteEmployee" + id;
        return $http.delete(url)
            .then(function (response) {
                alert("Delete Successfully");
                return response;
            })
            .catch(function (errorResponse) {
                alert("Something wrong!");
                throw errorResponse;
            })
            .then(function () {
                window.location = '#/';
            })
    }
});

From the error message link:

Unknown provider: idProvider <- id <- EmployeeService

The injector was erroneously trying to inject a service named id.


问:
Print out same format with escape characters in HTML from JSON?
I'm having a problem with printing out JSON data in HTML

```<code>var a = "We are the world.\n \tWelcome to our place.";
</code>```

let's assume that I have this json data from the backend and I wanna print out something like this.

```<code><div>
We are the world.
  Welcome to our place.
</div>
</code>```

I've tried with ng-bind-html but it shows all string inline.

Thanks.

答:
You cannot do it simply. Because \n and \t are not recognized encoding for Html. You have to replace it with the recognized Html encoding first. You can do this by the following way:

```<code>$scope.a = "We are the world.\n \tWelcome to our place."
$scope.a.replace(/(?:\r\n|\r|\n)/g, '<br />');
</code>```

But now if you bind this text into Html it will omit the extra spaces before the word Welcome and leave only one space.

So, to solve this problem you have to bind this Html inside a pre tag. It will preserve your formatting.

```<code>```{{a}}```
</code>```

I have added a demo here: https://plnkr.co/edit/2twWjmWPCKGxcrh7QEgf?p=preview

Body:
I'm having a problem with printing out JSON data in HTML

var a = "We are the world.\n \tWelcome to our place.";

let's assume that I have this json data from the backend and I wanna print out something like this.

We are the world.
  Welcome to our place.

I've tried with ng-bind-html but it shows all string inline.

Thanks.

Body:
You cannot do it simply. Because \n and \t are not recognized encoding for Html. You have to replace it with the recognized Html encoding first. You can do this by the following way:

$scope.a = "We are the world.\n \tWelcome to our place."
$scope.a.replace(/(?:\r\n|\r|\n)/g, '<br />');

But now if you bind this text into Html it will omit the extra spaces before the word Welcome and leave only one space.

So, to solve this problem you have to bind this Html inside a pre tag. It will preserve your formatting.

<pre>{{a}}<pre>

I have added a demo here: https://plnkr.co/edit/2twWjmWPCKGxcrh7QEgf?p=preview

ContentLicense: CC BY-SA 4.0


问:
Java generics 2 set of <K,V> or <T> in method declaration
I have been seeing the following methods declaration but I do not understand how <K, V> and <T> are being used.

What does public <K, V> does in this method?

```<code>public <K, V> void add(K k, V v)
</code>```

What does static <T> does in this method?

```<code>public static <T> int countGreaterThan(T[] anArray, T elem)
</code>```

答:
Recall, that in Java, all methods MUST be inside a class, so this method will be in some sort of class, lets say "Clazz".

public indicates that this method can be accessed from outside the class, by absolutely anyone.

static indicated that when you call this method, you don't need to call it from a specific object, but rather you can call it just by using the class name.  So you would be able to call countGreaterThen by typing Clazz.countGreaterThan instead of using a specific object created as an instance of Clazz

Body:
I have been seeing the following methods declaration but I do not understand how <K, V> and <T> are being used.

What does public <K, V> does in this method?

public <K, V> void add(K k, V v)

What does static <T> does in this method?

public static <T> int countGreaterThan(T[] anArray, T elem)


问:
Having Issues with JSF Backing Managed Bean Not Updating in the View
This question relates to a question I asked earlier and in order not to include the same code snippets, I would be glad if you would view it here.

I deploy the application on Tomcat 8.5. and now I see the return value of getMessage() from the HelloWorld managed bean displayed in the browser.

Now when I edit the value in the getMessage() function for instance instead of "Hello World!" I use "Hello World!................" and save and redeploy, the old value keeps displaying in the browser. Even if I restart Tomcat, it is the same old value. I just don't understand why.

I don't know if the problem is a cache problem or what. What I don't understand it is even after shutting down the server and restart it, I get the same old value.

答:
I can think of few thing;

clear tomcat cache
(Tomcat - want to clear cache of app being undeployed)

You may be compiling or deploying wrong archive (Verify the .class
    file generated is latest one, you can even use a de-compiler to
    verify this)


问:
Fixing Apparent Anaconda Python Corruption Fix
I am developing in Windows 7.0 Professional using Anaconda Python 2.7 in Spyder 3.1.4. I am also using Pandas.

After considerable work on a program I got a consistent strange problem.  Python / Pandas started treating two identical dataframes with different names the same way.

I defined the dataframes as follows:

```<code>dfa = pd.DataFrame(np.empty(0,dtype=[('Date','datetime64[ns]'),
                                    ('column1', 'string'),
                                    ('column2','string'),
                                    ('column3','string')]))
</code>```

I now duplicate this (empty) dataframe:

```<code>dfb = dfa
</code>```

Just after this I append to dfa as follows:

```<code>dfa.loc[indexvalue,:] = ([item1,item2,item3....])
</code>```

This worked properly until after many runs involved (to test other parts of the code) this command ALSO started identically updating dfb at the same time.  Similar operations using dfb results in identical updates to dfa

I am not an expert at package installation and have extensively examined my code.  This appears to be a corruption.

Can someone advise on how best to handle this?  I don't want to start ripping apart my Anaconda installation.  If this is indeed a corruption on the environment, what is the best way to repair/reinstall Anaconda and Spyder?

Thanks in advance.

答:
dfb = dfa just sets to variable to point to the same object.  If you update dfa you are updating the same object as dfb. This is how Pandas works.

If you really want to create a copy of dfa use:

```<code>dfc = dfa.copy()
</code>```

How do you check to see if your variable is point a copy of the dataframe of is it pointed to the same dataframe:

```<code>dfb is dfa
True

dfc is dfa
False
</code>```

This is not corruption.

Body:
I am developing in Windows 7.0 Professional using Anaconda Python 2.7 in Spyder 3.1.4. I am also using Pandas.

After considerable work on a program I got a consistent strange problem.  Python / Pandas started treating two identical dataframes with different names the same way.

I defined the dataframes as follows:

dfa = pd.DataFrame(np.empty(0,dtype=[('Date','datetime64[ns]'),
                                    ('column1', 'string'),
                                    ('column2','string'),
                                    ('column3','string')]))

I now duplicate this (empty) dataframe:

dfb = dfa

Just after this I append to dfa as follows:

dfa.loc[indexvalue,:] = ([item1,item2,item3....])

This worked properly until after many runs involved (to test other parts of the code) this command ALSO started identically updating dfb at the same time.  Similar operations using dfb results in identical updates to dfa

I am not an expert at package installation and have extensively examined my code.  This appears to be a corruption.

Can someone advise on how best to handle this?  I don't want to start ripping apart my Anaconda installation.  If this is indeed a corruption on the environment, what is the best way to repair/reinstall Anaconda and Spyder?

Thanks in advance.

Body:
dfb = dfa just sets to variable to point to the same object.  If you update dfa you are updating the same object as dfb. This is how Pandas works.

If you really want to create a copy of dfa use:

dfc = dfa.copy()

How do you check to see if your variable is point a copy of the dataframe of is it pointed to the same dataframe:

dfb is dfa
True

dfc is dfa
False

This is not corruption.


问:
Xamarin IOS - 'An unhandled exception occured' during start
I'm working on a Xamarin IOS project. And after I updated it to the latest version, suddenly receive this error:

```<code>An unhandled exception occurred.
</code>```

When I try to run it in debug mode.

It doesn't give me anything else, not even the slightest clue. So I have no idea why it breaks. Has anyone else stumbled onto this problem?

答:
https://forums.xamarin.com/discussion/58002/what-is-the-preferred-way-to-catch-all-unhandled-exceptions-on-xamarin-forms</p>

```<code> AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
</code>```

Body:
I'm working on a Xamarin IOS project. And after I updated it to the latest version, suddenly receive this error:

An unhandled exception occurred.

When I try to run it in debug mode.

It doesn't give me anything else, not even the slightest clue. So I have no idea why it breaks. Has anyone else stumbled onto this problem?

Body:
https://forums.xamarin.com/discussion/58002/what-is-the-preferred-way-to-catch-all-unhandled-exceptions-on-xamarin-forms

 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


问:
Passing info through an Activity switch
I'm having trouble figuring out how to pass information through an Activity switch.

I currently have an Activity where I can add a client to the database, and I have an Activity to view all clients in a ListView.

What I want is that when the user clicks on a client in the ListView for it to go back to the addclient Activity, with all the fields filled in from the database.

here is the Activity where the user views the clients

```<code>public class ViewClientActivity extends Activity
{
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewclient_activity);

    DBHandler handler = new DBHandler(this, null, null, 1);
    SQLiteDatabase db = handler.getWritableDatabase();
    final Cursor ClientCursor = db.rawQuery("SELECT  * FROM clients", null);
    ListView allClients = (ListView) findViewById(R.id.allClients);
    final ClientCursorAdapter clientAdapter = new ClientCursorAdapter(this, ClientCursor);

    allClients.setAdapter(clientAdapter);

    allClients.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent AddClientActivity = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(AddClientActivity);
        }
    });

}
}
</code>```

答:
This is what i ended up doing to pass the information i needed</p>

```<code>gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            IMAGES = imagesPath[0] + "|" + imagesPath[1] + "|" + imagesPath[2] + "|" +
                        imagesPath[3] + "|" + imagesPath[4] + "|" + imagesPath[5];

            Intent intent = new Intent(AddClientActivity.this, ImageViewActivity.class);
            intent.putExtra("IMAGES", IMAGES);
            intent.putExtra("POSITION", position);
            startActivity(intent);
        }
    });
</code>```

Title: Passing info through an Activity switch

Body:
I'm having trouble figuring out how to pass information through an Activity switch.

I currently have an Activity where I can add a client to the database, and I have an Activity to view all clients in a ListView.

What I want is that when the user clicks on a client in the ListView for it to go back to the addclient Activity, with all the fields filled in from the database.

here is the Activity where the user views the clients

public class ViewClientActivity extends Activity
{
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewclient_activity);

    DBHandler handler = new DBHandler(this, null, null, 1);
    SQLiteDatabase db = handler.getWritableDatabase();
    final Cursor ClientCursor = db.rawQuery("SELECT  * FROM clients", null);
    ListView allClients = (ListView) findViewById(R.id.allClients);
    final ClientCursorAdapter clientAdapter = new ClientCursorAdapter(this, ClientCursor);

    allClients.setAdapter(clientAdapter);

    allClients.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent AddClientActivity = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(AddClientActivity);
        }
    });

}
}

Body:
This is what i ended up doing to pass the information i needed

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            IMAGES = imagesPath[0] + "|" + imagesPath[1] + "|" + imagesPath[2] + "|" +
                        imagesPath[3] + "|" + imagesPath[4] + "|" + imagesPath[5];

            Intent intent = new Intent(AddClientActivity.this, ImageViewActivity.class);
            intent.putExtra("IMAGES", IMAGES);
            intent.putExtra("POSITION", position);
            startActivity(intent);
        }
    });


问:
Run two different simultaneous animations on a loop with CSS?
I am using images that float across, then fade out. (Some do the opposite, fade in.) It works the first time through the loop, but when it comes through the second time the fading just cuts out.

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite, 3s fadeOut 12s ease-in;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="candycane candycane_drift"></div></code>```

答:
I would research the animation shorthand property you're using.  The basic values are as follows: /* @keyframes duration | timing-function | delay |
iteration-count | direction | fill-mode | play-state | name */

The delay start applies to the first iteration of all the animations, so I've used a cubic-bezier to apply the late fade-out effect you're looking for. But there are other ways to structure your animation, for example, you could use a multi-step keyframe that would begin your animation for fade out at the 80% keyframe progress point. A multi-step animation has this format:

```<code>@keyframes late-fade {
  0% {
    opacity: 1;
  }
  /* Adding a step in the middle */
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</code>```

This is just one solution for getting this effect, the solution below is using a cubic-bezier rather than the ease-in timing function.

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
/* @keyframes duration | timing-function | delay |
iteration-count | direction | fill-mode | play-state | name */
  animation: drift 15s linear infinite, fadeOut 15s cubic-bezier(.75,0,1,0) infinite;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="candycane candycane_drift"></div></code>```

Body:
I would research the animation shorthand property you're using.  The basic values are as follows: /* @keyframes duration | timing-function | delay |
iteration-count | direction | fill-mode | play-state | name */

The delay start applies to the first iteration of all the animations, so I've used a cubic-bezier to apply the late fade-out effect you're looking for. But there are other ways to structure your animation, for example, you could use a multi-step keyframe that would begin your animation for fade out at the 80% keyframe progress point. A multi-step animation has this format:

@keyframes late-fade {
  0% {
    opacity: 1;
  }
  /* Adding a step in the middle */
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

This is just one solution for getting this effect, the solution below is using a cubic-bezier rather than the ease-in timing function.

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
/* @keyframes duration | timing-function | delay |
iteration-count | direction | fill-mode | play-state | name */
  animation: drift 15s linear infinite, fadeOut 15s cubic-bezier(.75,0,1,0) infinite;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

<div class="candycane candycane_drift"></div>


问:
python sql query with variable
```<code>testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, testid)
print cur.fetchone()
</code>```

I am getting an integer error when attempting this. I have tried converting testid to a string with no luck.

答:
I prefer this method of inserting parameters since it's very clear:</p>

```<code>query = "SELECT * FROM basic_info WHERE ownerid = %(testid)s"
cur.execute(query, params = { 'testid': testid })
</code>```

Title: python sql query with variable

Body:
testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, testid)
print cur.fetchone()

I am getting an integer error when attempting this. I have tried converting testid to a string with no luck.

Body:
I prefer this method of inserting parameters since it's very clear:

query = "SELECT * FROM basic_info WHERE ownerid = %(testid)s"
cur.execute(query, params = { 'testid': testid })


问:
How can I add uib-tooltip from within an attribute directive?
Instead of adding uib-tooltip="tooltip text" to the element I want to add only a tooltip attribute.

In the tooltip directive I want to do something along the lines of "on mouseenter if a condition is met then show my full text content in uib-tooltip"

答:
You can use tooltip-enable.

JS

```<code>.controller("ctrl", function($scope){

  $scope.isToolTipEnabled = false;

  $scope.toggleToolTip = function(){
    $scope.isToolTipEnabled = !$scope.isToolTipEnabled;
  }

});
</code>```

HTML

```<code><div ng-controller="ctrl">
  <div class="label label-info" class="btn btn-default"
          tooltip-enable="isToolTipEnabled"
          uib-tooltip="This is a conditional tooltip">Conditional Tooltip here</div>
  <button type="button" class="btn btn-default" ng-click="toggleToolTip()" ng-class="{'btn-success': isToolTipEnabled, 'btn-danger': !isToolTipEnabled}">Tooltip is {{isToolTipEnabled ? 'enabled' : 'disabled'}}</button>
</div>
</code>```

Body:
You can use tooltip-enable.

JS

.controller("ctrl", function($scope){

  $scope.isToolTipEnabled = false;

  $scope.toggleToolTip = function(){
    $scope.isToolTipEnabled = !$scope.isToolTipEnabled;
  }

});

HTML

<div ng-controller="ctrl">
  <div class="label label-info" class="btn btn-default"
          tooltip-enable="isToolTipEnabled"
          uib-tooltip="This is a conditional tooltip">Conditional Tooltip here</div>
  <button type="button" class="btn btn-default" ng-click="toggleToolTip()" ng-class="{'btn-success': isToolTipEnabled, 'btn-danger': !isToolTipEnabled}">Tooltip is {{isToolTipEnabled ? 'enabled' : 'disabled'}}</button>
</div>


问:
Data Encryption Standard
We were asked to write a Java implementation of the DES algorithm (which is used for encryption and decryption). I had a couple of questions:

DES specifies that there should be 64 bits of plain text or cipher text and an exactly 56 bit shared key. what is the method that gives the number of bytes ,

The algorithm uses a lot of bit level manipulations, such as splitting the 64 bits into two 32 bit sections. How can this be done?

答:
You should know by now that 8 bits = 1 byte. Everything in crypto works on bits, you never really need bytes except to define a buffer.

Splitting uses bitwise operations. Mask off the top bits for the bottom half, shift over the top bits for the top half. I assume you have the reference already, and while they're an invaluable resource, you absolutely have to know how bitwise ops work. A good resource that won't spoil the project is a compression algorithm, such as CABAC, since they're likewise bit-oriented. Then close the tab and try to use the spec to make your own.

Title: Data Encryption Standard