问:
No matching call function error for fstream
I am trying to make a program that will read from one file and output to another file a different value than read in, based on a input integer. I am getting errors on opening files. No matching call function

```<code>#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;

int main()
{

char option, m, c;
int amount, n, k;
string fname, dname, ename;

ofstream nstream;
ifstream istream;

cout << "Do you want to encrypt of decrypt? Enter D or E.";
cin >> option;
cout << endl;

while (option != 'D' && option != 'E')
{
    cout << "That is not acceptable" << endl;
    cout << "Do you want to encrypt of decrypt? Enter D or E.";
    cin >> option;
    cout << endl;
}

if (option == 'E')
{
    cout << "Enter the name of the file that you want to encrypt: ";
    cin >> fname;
    istream.open(fname);
    cout<<endl;
    cout << "Enter the name of the file that you want to output: ";
    cin >> ename;
    nstream.open(ename);
    cout<<endl;
}

if (option == 'D')
{
    cout << "Enter the name of the file that you want to decrypt: ";
    cin >> dname;
    istream.open(dname);
    cout<<endl;
    cout << "Enter the name of the file that you want to output: ";
    cin >> ename;
    nstream.open(ename);
    cout<<endl;

}
cout << "Enter the number of digits that you want to de/encrypt(integers): ";
cin >> k;

istream >> m;
while (m >= 0);
{
    if (m > 65 && m < 90);
    {
        c = m + k;
        while (c > 90)
        {
            c = c - 26;
        }

    }
    if (m > 97 && m < 122);
    {(c = m + k);
    while (c > 122)
    {
        c = c - 26;
    }
    }

     if(m >= 0)
    {
        c = m + k;
    }

}

nstream << c;
return 0;

}
</code>```

error messages

```<code>In function ‘int main()’:
homework4.cpp:39:21: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
  istream.open(fname);
                    ^
homework4.cpp:39:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:541:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s, ios_base::openmode __mode = ios_base::in)
      ^
/usr/include/c++/4.9/fstream:541:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:43:21: error: no matching function for call to ‘std::basic_ofstream<char>::open(std::string&)’
  nstream.open(ename);
                    ^
homework4.cpp:43:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:716:7: note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s,
      ^
/usr/include/c++/4.9/fstream:716:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:51:21: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
  istream.open(dname);
                    ^
homework4.cpp:51:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:541:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s, ios_base::openmode __mode = ios_base::in)
      ^
/usr/include/c++/4.9/fstream:541:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:55:21: error: no matching function for call to ‘std::basic_ofstream<char>::open(std::string&)’
  nstream.open(ename);
                    ^
homework4.cpp:55:21: note: candidate is:

In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:716:7: note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s,
^ /usr/include/c++/4.9/fstream:716:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
</code>```

答:
In your code, fname, dname, and ename are variables of type std::string, by default. However, the fstream::open requires a const char * value passed to it for a filename.

Here is how the function should be used:

```<code>void open (const char* filename,
            ios_base::openmode mode = ios_base::in | ios_base::out);
</code>```

Obtained from C++ Reference: std::fstream::open

To do this, add the .c_str() function to the end of the filename variable:

istream.open(fname.c_str());

nstream.open(ename.c_str());

istream.open(dname.c_str());

This will remove that error.

Body:
I am trying to make a program that will read from one file and output to another file a different value than read in, based on a input integer. I am getting errors on opening files. No matching call function

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;

int main()
{

char option, m, c;
int amount, n, k;
string fname, dname, ename;

ofstream nstream;
ifstream istream;

cout << "Do you want to encrypt of decrypt? Enter D or E.";
cin >> option;
cout << endl;

while (option != 'D' && option != 'E')
{
    cout << "That is not acceptable" << endl;
    cout << "Do you want to encrypt of decrypt? Enter D or E.";
    cin >> option;
    cout << endl;
}

if (option == 'E')
{
    cout << "Enter the name of the file that you want to encrypt: ";
    cin >> fname;
    istream.open(fname);
    cout<<endl;
    cout << "Enter the name of the file that you want to output: ";
    cin >> ename;
    nstream.open(ename);
    cout<<endl;
}

if (option == 'D')
{
    cout << "Enter the name of the file that you want to decrypt: ";
    cin >> dname;
    istream.open(dname);
    cout<<endl;
    cout << "Enter the name of the file that you want to output: ";
    cin >> ename;
    nstream.open(ename);
    cout<<endl;

}
cout << "Enter the number of digits that you want to de/encrypt(integers): ";
cin >> k;

istream >> m;
while (m >= 0);
{
    if (m > 65 && m < 90);
    {
        c = m + k;
        while (c > 90)
        {
            c = c - 26;
        }

    }
    if (m > 97 && m < 122);
    {(c = m + k);
    while (c > 122)
    {
        c = c - 26;
    }
    }

     if(m >= 0)
    {
        c = m + k;
    }

}

nstream << c;
return 0;

}

error messages

In function ‘int main()’:
homework4.cpp:39:21: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
  istream.open(fname);
                    ^
homework4.cpp:39:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:541:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s, ios_base::openmode __mode = ios_base::in)
      ^
/usr/include/c++/4.9/fstream:541:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:43:21: error: no matching function for call to ‘std::basic_ofstream<char>::open(std::string&)’
  nstream.open(ename);
                    ^
homework4.cpp:43:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:716:7: note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s,
      ^
/usr/include/c++/4.9/fstream:716:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:51:21: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
  istream.open(dname);
                    ^
homework4.cpp:51:21: note: candidate is:
In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:541:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s, ios_base::openmode __mode = ios_base::in)
      ^
/usr/include/c++/4.9/fstream:541:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
homework4.cpp:55:21: error: no matching function for call to ‘std::basic_ofstream<char>::open(std::string&)’
  nstream.open(ename);
                    ^
homework4.cpp:55:21: note: candidate is:

In file included from homework4.cpp:4:0:
/usr/include/c++/4.9/fstream:716:7: note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
      open(const char* __s,
^ /usr/include/c++/4.9/fstream:716:7: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’

Body:
In your code, fname, dname, and ename are variables of type std::string, by default. However, the fstream::open requires a const char * value passed to it for a filename.

Here is how the function should be used:

void open (const char* filename,
            ios_base::openmode mode = ios_base::in | ios_base::out);

Obtained from C++ Reference: std::fstream::open

To do this, add the .c_str() function to the end of the filename variable:

istream.open(fname.c_str());

nstream.open(ename.c_str());

istream.open(dname.c_str());

This will remove that error.


来源: stackexchange

问:
list buttons responsive design
How can I put this button inline to be responsive?
had tried doing  but doesnt work.

```<code><div class="form-group btn-group"  >
    <ul class="btn-group list-inline social "  style="display: flex;">
      <li class="col-xs-12">
        <button type="submit" class="btn  btn-default" name="btn-login" id="btn-login">
          <span class="glyphicon glyphicon-log-in"></span>   Sign In
        </button>
      </li>
      <li class="col-xs-12">
        <a href="<?=$fbLoginUrl ?>" class="btn btn-social btn-facebook" style="float:left;margin-right:5px, color:#3B5998">Sign in with Facebook </a>
      </li>
      <li class="col-xs-12">
        <a href="register.php" class="btn btn-social btn-default" style="float:right;">Sign UP Here </a>
      </li>
    </ul>

  </div>
</code>```

答:
You've placed style="display: flex;" on your ul. By default flex containers do not wrap. If you want it to wrap, you need to add

```<code>flex-wrap:wrap;
</code>```

...to it.

Or, if you only want it to apply on some screen widths, move that declaration in a CSS file, where you'll be able to use @media queries.

Not being able to add responsiveness rules to it is one of the main reasons inline style is considered very bad practice (the other is because it's hard to maintain).

ContentLicense: CC BY-SA 3.0

Title: list buttons responsive design

Body:
How can I put this button inline to be responsive?
had tried doing  but doesnt work.

        <button type="submit" class="btn  btn-default" name="btn-login" id="btn-login">
             Sign In
        </button>

        <a href="<?=$fbLoginUrl ?>" class="btn btn-social btn-facebook" style="float:left;margin-right:5px, color:#3B5998">Sign in with Facebook

        Sign UP Here

Body:
You've placed style="display: flex;" on your ul. By default flex containers do not wrap. If you want it to wrap, you need to add

flex-wrap:wrap;

...to it.

Or, if you only want it to apply on some screen widths, move that declaration in a CSS file, where you'll be able to use @media queries.

Not being able to add responsiveness rules to it is one of the main reasons inline style is considered very bad practice (the other is because it's hard to maintain).


问:
Tips of making a list in email
I am designing an email template. I have a running list of brand names hyperlinked to their websites. I would like it to be displayed inline for full-width, and stacked for narrow screens. I had separators in the past like a bullet or a vertical rule such as this: "|". But in mobile it's awkward considering only one name appears per line.

The next thing I tried was to enclose each list item in a border, but Outlook10/13 aren't handling the padding and margin as you know. I want a simple solution that I can show to novices when they populate the template. Any ideas? I'm adding screenshots of what I tried with the borders. But any other idea is welcome.

Thanks!!!

Full Width:

Mobile:

答: I have tried a lot of ways myself and one thing i found out was having logos in place of links often work better. I know images have to be downloaded but once they are downloaded it looks good. If you do go with images, you can style the alt tags to look like above when its not loaded.</p>

Title: Tips of making a list in email


问:
Minimize sum of weights such that weighted sum is zero
Given n <= 1000 integers x(1), x(2), ..., x(n) where |x(i)| <= 1000. We want to assign non-negative integer weights c(1), c(2), ..., c(n) to each element such that c(1) * x(1) + ... + c(n) * x(n) = 0. Let S = c(1) + ... + c(n). We need S > 0 and we want to minimize S.

We can binary search for minimum S and for some specific S we can do dynamic programming by building dp(totalWeight, position, sum) but that would be too slow. How to solve it faster?

答:
Let's assume there's at least one positive and at least one negative weight (otherwise the problem has no solution). We know S is at most 2000, because if there's weights -c and +d, then d*-c + c*d = 0. And since c, d <= 1000, we know S (the minimum positive solution) is at most 2000. With 2000 weights, the maximum possible total is 2 million, and the minimum possible total is negative 2 million.

Now, we compute the minimum number of positive weights that can total 0 to 2 million.

```<code>N = 2000000
p = [0] + [infinity] * N
for w in positive weights:
    for i = w ... N:
        p[i] = min(p[i], p[i-w]+1)
</code>```

We do the same for negative weights:

```<code>n = [0] + [infinity] * N
for w in negative weights:
    for i = -w ... N:
        n[i] = min(n[i], n[i+w]+1)
</code>```

And to find the solution, we find the minimum sum of the two arrays:

```<code>S = infinity
for i = 1 ... N:
    S = min(S, n[i] + p[i])
</code>```

To speed things up, one can find a better bound for S (which reduces the N we need to consider). Let -c be the negative weight closest to 0, and d be the positive weight closest to 0, and e be the weight of largest magnitude. Then S <= c+d, so N can be reduced to (c+d)e. In fact, one can do a little better: if -c and d are any two negative/positive weights, then d/gcd(c, d) * -c + c/gcd(c, d) * d = 0, so S is bounded by min((d+c)/gcd(c, d) for -c a negative weight, and d a positive weight).

Putting all this together into a single Go solution, which you can run online here: https://play.golang.org/p/CAa54pQs26

```<code>package main

import "fmt"

func boundS(ws []int) int {
    best := 5000
    for _, pw := range ws {
        if pw < 0 {
            continue
        }
        for _, nw := range ws {
            if nw > 0 {
                continue
            }
            best = min(best, (pw-nw)/gcd(pw, -nw))
        }
    }
    return best
}

func minSum(ws []int) int {
    maxw := 0
    for _, w := range ws {
        maxw = max(maxw, abs(w))
    }
    N := maxw * boundS(ws)
    n := make([]int, N+1)
    p := make([]int, N+1)
    for i := 1; i <= N; i++ {
        n[i] = 5000
        p[i] = 5000
    }
    for _, w := range ws {
        for i := abs(w); i <= N; i++ {
            if w > 0 {
                p[i] = min(p[i], 1+p[i-w])
            } else {
                n[i] = min(n[i], 1+n[i+w])
            }
        }
    }
    S := p[1] + n[1]
    for i := 1; i <= N; i++ {
        S = min(S, p[i]+n[i])
    }
    return S
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func abs(a int) int {
    if a < 0 {
        return -a
    }
    return a
}

func gcd(a, b int) int {
    if a < b {
        a, b = b, a
    }
    for b > 0 {
        a, b = b, a%b
    }
    return a
}
</code>```

And testing on some easy and some hard test cases. The code runs in under half a second on my laptop.

```<code>func isPrime(p int) bool {
    if p < 4 {
        return p >= 2
    }
    for i := 2; i*i <= p; i++ {
        if p%i == 0 {
            return false
        }
    }
    return true
}

func main() {
    var middle, ends, altPrimes []int
    sign := 1
    for i := -1000; i <= 1000; i++ {
        if i == 0 {
            continue
        }
        if abs(i) <= 500 {
            middle = append(middle, i)
        } else {
            ends = append(ends, i)
        }
        if abs(i) >= 500 && isPrime(i) {
            altPrimes = append(altPrimes, sign*i)
            sign *= -1
        }
    }
    cases := [][]int{
        []int{999, -998},
        []int{10, -11, 15, -3},
        middle,
        ends,
        altPrimes,
    }
    for i, ws := range cases {
        fmt.Println("case", i+1, minSum(ws))
    }
}
</code>```

Body:
Let's assume there's at least one positive and at least one negative weight (otherwise the problem has no solution). We know S is at most 2000, because if there's weights -c and +d, then d*-c + c*d = 0. And since c, d <= 1000, we know S (the minimum positive solution) is at most 2000. With 2000 weights, the maximum possible total is 2 million, and the minimum possible total is negative 2 million.

Now, we compute the minimum number of positive weights that can total 0 to 2 million.

N = 2000000
p = [0] + [infinity] * N
for w in positive weights:
    for i = w ... N:
        p[i] = min(p[i], p[i-w]+1)

We do the same for negative weights:

n = [0] + [infinity] * N
for w in negative weights:
    for i = -w ... N:
        n[i] = min(n[i], n[i+w]+1)

And to find the solution, we find the minimum sum of the two arrays:

S = infinity
for i = 1 ... N:
    S = min(S, n[i] + p[i])

To speed things up, one can find a better bound for S (which reduces the N we need to consider). Let -c be the negative weight closest to 0, and d be the positive weight closest to 0, and e be the weight of largest magnitude. Then S <= c+d, so N can be reduced to (c+d)e. In fact, one can do a little better: if -c and d are any two negative/positive weights, then d/gcd(c, d) * -c + c/gcd(c, d) * d = 0, so S is bounded by min((d+c)/gcd(c, d) for -c a negative weight, and d a positive weight).

Putting all this together into a single Go solution, which you can run online here: https://play.golang.org/p/CAa54pQs26

package main

import "fmt"

func boundS(ws []int) int {
    best := 5000
    for _, pw := range ws {
        if pw < 0 {
            continue
        }
        for _, nw := range ws {
            if nw > 0 {
                continue
            }
            best = min(best, (pw-nw)/gcd(pw, -nw))
        }
    }
    return best
}

func minSum(ws []int) int {
    maxw := 0
    for _, w := range ws {
        maxw = max(maxw, abs(w))
    }
    N := maxw * boundS(ws)
    n := make([]int, N+1)
    p := make([]int, N+1)
    for i := 1; i <= N; i++ {
        n[i] = 5000
        p[i] = 5000
    }
    for _, w := range ws {
        for i := abs(w); i <= N; i++ {
            if w > 0 {
                p[i] = min(p[i], 1+p[i-w])
            } else {
                n[i] = min(n[i], 1+n[i+w])
            }
        }
    }
    S := p[1] + n[1]
    for i := 1; i <= N; i++ {
        S = min(S, p[i]+n[i])
    }
    return S
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func abs(a int) int {
    if a < 0 {
        return -a
    }
    return a
}

func gcd(a, b int) int {
    if a < b {
        a, b = b, a
    }
    for b > 0 {
        a, b = b, a%b
    }
    return a
}

And testing on some easy and some hard test cases. The code runs in under half a second on my laptop.

func isPrime(p int) bool {
    if p < 4 {
        return p >= 2
    }
    for i := 2; i*i <= p; i++ {
        if p%i == 0 {
            return false
        }
    }
    return true
}

func main() {
    var middle, ends, altPrimes []int
    sign := 1
    for i := -1000; i <= 1000; i++ {
        if i == 0 {
            continue
        }
        if abs(i) <= 500 {
            middle = append(middle, i)
        } else {
            ends = append(ends, i)
        }
        if abs(i) >= 500 && isPrime(i) {
            altPrimes = append(altPrimes, sign*i)
            sign *= -1
        }
    }
    cases := [][]int{
        []int{999, -998},
        []int{10, -11, 15, -3},
        middle,
        ends,
        altPrimes,
    }
    for i, ws := range cases {
        fmt.Println("case", i+1, minSum(ws))
    }
}


问:
PHP MySQL Group BY Having issue
Suppose I have a table like:

```<code>ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7
</code>```

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

```<code>SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
</code>```

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

```<code>SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;
</code>```

Thanks

答:
Here are two solutions that return the correct records, the first as individual records by ID and Reference, and the second with one record per ID and the Words and References as comma separated in columns.

Setup table and populate rows:

```<code>DROP TABLE IF EXISTS `list1`;

CREATE table `list1` (
    id int(10),
    Word varchar(10),
    Reference int(10)
);

INSERT INTO `list1` (`ID`, `Word`, `Reference`)
VALUES
(1, 'Dog',1),
(1 ,'Fish',2),
(1 ,'Sheep',3),
(2 ,'Dog',4),
(2 ,'Sheep',5),
(3 ,'Sheep',6),
(4 ,'Dog',7);
</code>```

Returns one row for each combination of ID and Word

```<code>SELECT
    t.`ID`,
    t.`Word`,
    t.`Reference`
FROM `list1` as t
JOIN (
    SELECT
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
ORDER BY t.`ID`,t.`Word`;
</code>```

Results

```<code>ID  |   Word    |   Reference
1   |   Dog     |   1
1   |   Sheep   |   3
2   |   Dog     |   4
2   |   Sheep   |   5
</code>```

Returns one row per ID, with a comma separated list of Words in one column, and a comma separated list of Reference in another.

```<code>SELECT
    t.`ID`,
    GROUP_CONCAT(t.`Word`) AS `Words`,
    GROUP_CONCAT(t.`Reference`) AS `References`
FROM `list1` as t
JOIN (
    SELECT
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
GROUP BY t.`ID`
ORDER BY t.`ID`,t.`Word`;
</code>```

Results:

```<code>ID  |   Words       |   References
1   |   Dog,Sheep   |   1,3
2   |   Dog,Sheep   |   4,5
</code>```

Title: PHP MySQL Group BY Having issue

Body:
Suppose I have a table like:

ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

Thanks

Body:
Here are two solutions that return the correct records, the first as individual records by ID and Reference, and the second with one record per ID and the Words and References as comma separated in columns.

Setup table and populate rows:

DROP TABLE IF EXISTS `list1`;

CREATE table `list1` (
    id int(10),
    Word varchar(10),
    Reference int(10)
);

INSERT INTO `list1` (`ID`, `Word`, `Reference`)
VALUES
(1, 'Dog',1),
(1 ,'Fish',2),
(1 ,'Sheep',3),
(2 ,'Dog',4),
(2 ,'Sheep',5),
(3 ,'Sheep',6),
(4 ,'Dog',7);

Returns one row for each combination of ID and Word

SELECT
    t.`ID`,
    t.`Word`,
    t.`Reference`
FROM `list1` as t
JOIN (
    SELECT
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
ORDER BY t.`ID`,t.`Word`;

Results

ID  |   Word    |   Reference
1   |   Dog     |   1
1   |   Sheep   |   3
2   |   Dog     |   4
2   |   Sheep   |   5

Returns one row per ID, with a comma separated list of Words in one column, and a comma separated list of Reference in another.

SELECT
    t.`ID`,
    GROUP_CONCAT(t.`Word`) AS `Words`,
    GROUP_CONCAT(t.`Reference`) AS `References`
FROM `list1` as t
JOIN (
    SELECT
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
GROUP BY t.`ID`
ORDER BY t.`ID`,t.`Word`;

Results:

ID  |   Words       |   References
1   |   Dog,Sheep   |   1,3
2   |   Dog,Sheep   |   4,5


问:
Why does setInputType disable autocorrection?
Normally the android keyboard automatically shows suggestions as you type (autocorrect), but if you change the properties of the edit field from your code, the suggestions no longer show up.

For instance, this line successfully changes the input type to use all caps, but suggestions no longer show up:

```<code>mEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
</code>```

Even if I explicitly tell it to use autocorrect, it STILL doesn't use autocorrect:

```<code>mEditText.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
</code>```

However, if I never call setInputType, the suggestions show up just fine! Why does this happen? How do I fix it it?

Thanks!

答:
I don't remember the full story, but I had to do the following to make it work for me

```<code>edit.setRawInputType(edit.getInputType() & ~EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
</code>```

note the calling of setRawInputType instead of setInputType

Body:
Normally the android keyboard automatically shows suggestions as you type (autocorrect), but if you change the properties of the edit field from your code, the suggestions no longer show up.

For instance, this line successfully changes the input type to use all caps, but suggestions no longer show up:

mEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);

Even if I explicitly tell it to use autocorrect, it STILL doesn't use autocorrect:

mEditText.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

However, if I never call setInputType, the suggestions show up just fine! Why does this happen? How do I fix it it?

Thanks!

Body:
I don't remember the full story, but I had to do the following to make it work for me

edit.setRawInputType(edit.getInputType() & ~EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);

note the calling of setRawInputType instead of setInputType


问:
Angularjs order by not working properly
I'm facing a little problem with order by that i could not underdstand.

When i reoder the array i can see that every thing is working perfectly, but the problem is in the ng-click function of the list.

For example if i have this array:

```<code>$scope.ticketsEncour = [
  {_id: 1, vendeur: 'John Doe', date_ticket: '18:52', total: 50},
  {_id: 2, vendeur: 'Foo Bar', date_ticket: '12:12', total: 20},
  {_id: 3, vendeur: 'John Smith', date_ticket: '11:02', total: 10},
  {_id: 4, vendeur: 'Test Test', date_ticket: '05:10', total: 6000}
]
</code>```

And this is ther reoder and click functions:

```<code>$scope.reverse = false;
$scope.orderItems = function (item) {
$scope.reverse = !$scope.reverse;
  if (item != undefined) {
    if (item == $scope.orderItem) {
      $scope.orderType = $scope.orderType == '+' ? '-' : '+';
    }
    else {
      $scope.orderItem = item;
      $scope.orderType = '+';
    }
  }

  $('.iconOrder').removeClass('up').removeClass('down');
  if ($scope.orderType == '+') {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down')
  }
  else {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up')
  }

  return $scope.orderType + $scope.orderItem;
}
$scope.goToCaissePage = function (id) {
  id = id.replace("app/caisse/", "");
  console.log(id);
};
</code>```

And my Html Code

```<code><ion-list class="list articlesList swipedList" show-delete="showDelete">
      <ion-item class="item item-button-right stable-bg">
        <span class="row">
          <span class="col col-20" ng-click="orderItems('vendeur')">
            <strong>Vendeur</strong>
            <div class="iconOrder" name="vendeur">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
          <span class="col col-20" ng-click="orderItems('date_ticket')">
            <strong>Heure</strong>
            <div class="iconOrder" name="date_ticket">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
          <span class="col col-10" ng-click="orderItems('total')">
            <strong>Total</strong>
            <div class="iconOrder" name="total">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
        </span>
      </ion-item>

      <ion-item class="item item-button-right pad-item" ng-repeat="ticket in ticketsEncour | orderBy : orderBy : orderItem:reverse  track by $index">
        <span class="row">
          <span class="col col-20 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.vendeur }}</a>
            </div>
          </span>
          <span class="col col-20 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.date_ticket | date:'HH:mm' }}</a>
            </div>
          </span>
          <span class="col col-10 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.total.toFixed(2) }}€</a>
            </div>
          </span>
        </span>
      </ion-item>
    </ion-list>
</code>```

When i click on any item of the ng-repeat it shows the right id in the console. But when i use the reorder i can is that the HTML has changed but the ng-click function render always the old one:

click on index 0 => console 1 (perfect)

After reoder with any type:

click on index 0 => console 1 (expected 3 for example)

Thanks

Update: changed the array name (copy cut error)

Updated with @Weijian suggestion

答: I fixed the issue, i was from the track by $index in the ng-repeat loop

Title: Angularjs order by not working properly

Body:
I'm facing a little problem with order by that i could not underdstand.

When i reoder the array i can see that every thing is working perfectly, but the problem is in the ng-click function of the list.

For example if i have this array:

$scope.ticketsEncour = [
  {_id: 1, vendeur: 'John Doe', date_ticket: '18:52', total: 50},
  {_id: 2, vendeur: 'Foo Bar', date_ticket: '12:12', total: 20},
  {_id: 3, vendeur: 'John Smith', date_ticket: '11:02', total: 10},
  {_id: 4, vendeur: 'Test Test', date_ticket: '05:10', total: 6000}
]

And this is ther reoder and click functions:

$scope.reverse = false;
$scope.orderItems = function (item) {
$scope.reverse = !$scope.reverse;
  if (item != undefined) {
    if (item == $scope.orderItem) {
      $scope.orderType = $scope.orderType == '+' ? '-' : '+';
    }
    else {
      $scope.orderItem = item;
      $scope.orderType = '+';
    }
  }

  $('.iconOrder').removeClass('up').removeClass('down');
  if ($scope.orderType == '+') {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down')
  }
  else {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up')
  }

  return $scope.orderType + $scope.orderItem;
}
$scope.goToCaissePage = function (id) {
  id = id.replace("app/caisse/", "");
  console.log(id);
};

And my Html Code

<ion-list class="list articlesList swipedList" show-delete="showDelete">
      <ion-item class="item item-button-right stable-bg">

            Vendeur

            Heure

            Total

      </ion-item>

      <ion-item class="item item-button-right pad-item" ng-repeat="ticket in ticketsEncour | orderBy : orderBy : orderItem:reverse  track by $index">

              {{ ticket.vendeur }}

              {{ ticket.date_ticket | date:'HH:mm' }}

              {{ ticket.total.toFixed(2) }}€

      </ion-item>
    </ion-list>

When i click on any item of the ng-repeat it shows the right id in the console. But when i use the reorder i can is that the HTML has changed but the ng-click function render always the old one:

click on index 0 => console 1 (perfect)

After reoder with any type:

click on index 0 => console 1 (expected 3 for example)

Thanks

Update: changed the array name (copy cut error)

Updated with @Weijian suggestion


问:
using sed or awk to remove a "checkbox" character
I have a script that has a variable that might contain some weird characters:  ✔. I need to remove them but, honestly, I don't even know where to begin to match those characters. I can't copy and paste them into my script, they just show up as ?? ?. How can a match those characters with sed or awk? I don't have the ability to use perl or php or anything much beyond sed or awk due to system availability.

答:
The solution I ended up using was just changing the encoding of the script to UTF-8 instead of ASCII. I did this with notepad++. Then I could work with the character directly instead of some roundabout way of converting to hex (which I couldn't do anyway as the variable is an environmental variable and not from a file) or something else. I also didn't need to use awk or sed as the following was much simpler:

cleaned_var=${environmental_variable//"  ✔"}


问:
Error (400) Bad Request when attempting to connect to Sabre API
I am trying to connect to the Sabre API using  the following code:

```<code>Dim u As String = "https://developer.sabre.com/io-docs/call-api"

' Create the web request
request2 = DirectCast(WebRequest.Create(u), HttpWebRequest)

' Get response
response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

' Get the response stream into a reader
reader2 = New StreamReader(response2.GetResponseStream())

' Console application output

' MsgBox(reader.ReadToEnd())
Response.Write(reader.ReadToEnd())
</code>```

However I am getting the following error:

Server Error in '/' Application.

The remote server returned an error: (400) Bad Request.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Source Error:

Line 49:

Line 50:         ' Get response

Line 51:         response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

Line 52:

Line 53:         ' Get the response stream into a reader

答:
You are not referencing the correct Sabre API endpoints. I would recommend looking at the .Net Sabre API Code Sample for reference information.

https://github.com/SabreDevStudio/SACS-DotNet

Body:
I am trying to connect to the Sabre API using  the following code:

Dim u As String = "https://developer.sabre.com/io-docs/call-api"

' Create the web request
request2 = DirectCast(WebRequest.Create(u), HttpWebRequest)

' Get response
response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

' Get the response stream into a reader
reader2 = New StreamReader(response2.GetResponseStream())

' Console application output

' MsgBox(reader.ReadToEnd())
Response.Write(reader.ReadToEnd())

However I am getting the following error:

Server Error in '/' Application.

The remote server returned an error: (400) Bad Request.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Source Error:

Line 49:

Line 50:         ' Get response

Line 51:         response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

Line 52:

Line 53:         ' Get the response stream into a reader


问:
replace sed command text inline
I have this file

file.txt

```<code>unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4
</code>```

How can I use the sed command to obtain this:

```<code>unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|
</code>```

答:
I would combine the related lines with paste and reshuffle the elements with awk (I assume the related lines are exactly half a file away):

```<code>n=$(wc -l < file.txt)
paste -d'|' <(head -n $((n/2)) file.txt) <(tail -n $((n/2)) file.txt) |
awk '{ print $1, $6, $3, $6, "" }' FS='|' OFS='|'
</code>```

Output:

```<code>unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|
</code>```

Title: replace sed command text inline

Body:
I have this file

file.txt

unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4

How can I use the sed command to obtain this:

unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|

Body:
I would combine the related lines with paste and reshuffle the elements with awk (I assume the related lines are exactly half a file away):

n=$(wc -l < file.txt)
paste -d'|' <(head -n $((n/2)) file.txt) <(tail -n $((n/2)) file.txt) |
awk '{ print $1, $6, $3, $6, "" }' FS='|' OFS='|'

Output:

unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|


问:
Trying to create linked list in C. But only half the requested nodes are created
I'm trying to create a program that creates a linked list with nodes made up of 2 integers. It asks for the number of nodes.

If I input an even number of nodes, the program only creates half of them but if I input an odd number, then it crashes after half of the nodes.

Here is my code:

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

struct node{

    int student;
    int exam;
    struct node *link;
};

int main(void){

    int student_num, exam_num, node_num, i;
    struct node *start;
    struct node *next;
    struct node *temp;

    printf("How many nodes?: ");
    scanf("%d",&node_num);

    temp = malloc(sizeof(struct node));
    start = temp;

    start->link = NULL;

    next = start;

    //Creates node_num nodes
    for(i=1;i<=node_num;i++){

        temp = malloc(sizeof(struct node));

        next->link=temp;

        next=temp;
        next->link=NULL;
    }

    next=start->link;

    //Fills in the numbers
    for(temp=start;temp->link!=NULL;temp=next->link){

        printf("\nStudent number: ");
        scanf("%d",&student_num);

        temp->student=student_num;

        printf("Exam number: ");
        scanf("%d",&exam_num);

        temp->exam=exam_num;

        next=temp->link;
    }

    next=start->link;

    //Shows the result
    for(temp=start;temp->link!=NULL;temp=next->link){

        printf("\nStudent number: %d\tExam number: %d\n",temp->student,temp->exam);
        next=temp->link;
    }
}
</code>```

答:
You're going to the next node in the list twice. You do it in the for() loop header:

```<code>for(temp=start;temp->link!=NULL;temp=next->link){
                                ^^^^^^^^^^^^^^^
</code>```

and also at the bottom of the loop:

```<code>    next=temp->link;
</code>```

Just do one or the other, not both. Change the header to:

```<code>for(temp=start;temp->link!=NULL;temp=temp->link){
</code>```

and get rid of the line at the end.

Body:
I'm trying to create a program that creates a linked list with nodes made up of 2 integers. It asks for the number of nodes.

If I input an even number of nodes, the program only creates half of them but if I input an odd number, then it crashes after half of the nodes.

Here is my code:

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

struct node{

    int student;
    int exam;
    struct node *link;
};

int main(void){

    int student_num, exam_num, node_num, i;
    struct node *start;
    struct node *next;
    struct node *temp;

    printf("How many nodes?: ");
    scanf("%d",&node_num);

    temp = malloc(sizeof(struct node));
    start = temp;

    start->link = NULL;

    next = start;

    //Creates node_num nodes
    for(i=1;i<=node_num;i++){

        temp = malloc(sizeof(struct node));

        next->link=temp;

        next=temp;
        next->link=NULL;
    }

    next=start->link;

    //Fills in the numbers
    for(temp=start;temp->link!=NULL;temp=next->link){

        printf("\nStudent number: ");
        scanf("%d",&student_num);

        temp->student=student_num;

        printf("Exam number: ");
        scanf("%d",&exam_num);

        temp->exam=exam_num;

        next=temp->link;
    }

    next=start->link;

    //Shows the result
    for(temp=start;temp->link!=NULL;temp=next->link){

        printf("\nStudent number: %d\tExam number: %d\n",temp->student,temp->exam);
        next=temp->link;
    }
}

Body:
You're going to the next node in the list twice. You do it in the for() loop header:

for(temp=start;temp->link!=NULL;temp=next->link){
                                ^^^^^^^^^^^^^^^

and also at the bottom of the loop:

    next=temp->link;

Just do one or the other, not both. Change the header to:

for(temp=start;temp->link!=NULL;temp=temp->link){

and get rid of the line at the end.


问:
Escaping values with apostrophes for MySQL insert
I am trying to create some SQL insert statements and a few variables have names like the following:

"Aamma's Pastries"

I want to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?

答: Have a look at mysql_real_escape_string</p>

Body: Have a look at mysql_real_escape_string

ContentLicense: CC BY-SA 2.5


问:
Inkscape inx param defaults
I am developing a extension for Inkscape and would like to set a param value based on a value that is set on a object. For example if the ID of the selected object is set to "myRect" how would I display that value in the extension dialog? Seems to me that there should be a way to tell Inkscape that I want a value displayed here from attribute "id", I have read through the documentation on Inkscapes wiki and searched the web but couldn't find any answers. </p>

答:
I don't think it's possible.

The extension UI is built from the static .inx file.  There's no way for your extension code to modify that AFAIK.

It might be possible to have your extension rewrite the .inx file all the time.  But I imagine that this would be a horrible horrible approach.  Also I'm not sure how frequently inkscape reloads the .inx file.

Title: Inkscape inx param defaults


问:
Confused on how to use arrays with an object with the calculation on another class.
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.

```<code>using System;
using Square;

namespace DemoSquares
{
    public class DemoSquares
    {
        static void Main()
    {
        int[] numbers = new int[10];

        Squares asquare = new Squares();

        asquare.Length = numbers[0];

        foreach (int i in numbers)
        {
            Console.WriteLine("{0}", i, asquare.Area);

        }
    }
}
</code>```

}
This is the class.
    using System;

```<code>namespace Square
{
    class Squares
    {

    private int length;
    private int area;
    public int Length
    {
        get
        {
            return length;
        }
        set
        {
            length = value;
            CalcArea();
        }
    }
    public int Area
    {
        get
        {
            return area;
        }
    }
    private void CalcArea()
    {
        area = Length * Length;
    }
}
</code>```

}

答:
First populate the array with some values, possibly something like this:

```<code>int[] numbers = new int[10];
int counter = 1;
for (int i = 0; i < numbers.Length; i++) {
       numbers[i] = counter;
       counter++;
}
</code>```

then you can find the area of each square like so:

```<code>foreach (int i in numbers)
{
     Squares asquare = new Squares();
     asquare.Length = i;
     Console.WriteLine("{0}", i, asquare.Area);
}
</code>```

Another alternative

```<code>int[] numbers = {
    1,2,3,4,5,6,7,8,9,10  // enter your numbers here
};

numbers.ToList().ForEach(n => {
    Squares asquare = new Squares();
    asquare.Length = n;
    Console.WriteLine("{0}", n, asquare.Area);
});
</code>```

note - if you decide to go with the latter, ensure you import:

```<code>using System.Linq;
</code>```

Body:
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.

using System;
using Square;

namespace DemoSquares
{
    public class DemoSquares
    {
        static void Main()
    {
        int[] numbers = new int[10];

        Squares asquare = new Squares();

        asquare.Length = numbers[0];

        foreach (int i in numbers)
        {
            Console.WriteLine("{0}", i, asquare.Area);

        }
    }
}

}
This is the class.
    using System;

namespace Square
{
    class Squares
    {

    private int length;
    private int area;
    public int Length
    {
        get
        {
            return length;
        }
        set
        {
            length = value;
            CalcArea();
        }
    }
    public int Area
    {
        get
        {
            return area;
        }
    }
    private void CalcArea()
    {
        area = Length * Length;
    }
}

}

Body:
First populate the array with some values, possibly something like this:

int[] numbers = new int[10];
int counter = 1;
for (int i = 0; i < numbers.Length; i++) {
       numbers[i] = counter;
       counter++;
}

then you can find the area of each square like so:

foreach (int i in numbers)
{
     Squares asquare = new Squares();
     asquare.Length = i;
     Console.WriteLine("{0}", i, asquare.Area);
}

Another alternative

int[] numbers = {
    1,2,3,4,5,6,7,8,9,10  // enter your numbers here
};

numbers.ToList().ForEach(n => {
    Squares asquare = new Squares();
    asquare.Length = n;
    Console.WriteLine("{0}", n, asquare.Area);
});

note - if you decide to go with the latter, ensure you import:

using System.Linq;


问:
Get hex in fixed position from file in vbscript
So I have multiple files that in hex editor looks like below:

```<code>      Offset(h) 00 01 02 03 04 05

      1o        10 20 02 00 0A 05 (...)

      2o        10 20 53 00 0A 03 (...)

      3o        10 20 22 00 0A 55 (...)

      4o        10 20 12 00 0A 22 (...)
</code>```

How do I get the 0A value and store into a variable, knowing that is a fixed position? (always 5th byte)

I need to get the 0A value so I compare to other value and make a decision.

I need to do this in VBscript.

Thanks in advance and appreciate any help

答:
Reading from a binary file is easy in vbscript as long as you read sequentially from the beginning to the end. </p>

```<code>Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim BinaryFile : Set BinaryFile = fso.OpenTextFile("content.bin")
BinaryFile.Skip(4)
WScript.echo Hex(Asc(BinaryFile.Read(1))) 'Returns "A"
BinaryFile.Close
</code>```

Body:
So I have multiple files that in hex editor looks like below:

      Offset(h) 00 01 02 03 04 05

      1o        10 20 02 00 0A 05 (...)

      2o        10 20 53 00 0A 03 (...)

      3o        10 20 22 00 0A 55 (...)

      4o        10 20 12 00 0A 22 (...)

How do I get the 0A value and store into a variable, knowing that is a fixed position? (always 5th byte)

I need to get the 0A value so I compare to other value and make a decision.

I need to do this in VBscript.

Thanks in advance and appreciate any help

Body:
Reading from a binary file is easy in vbscript as long as you read sequentially from the beginning to the end.

Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim BinaryFile : Set BinaryFile = fso.OpenTextFile("content.bin")
BinaryFile.Skip(4)
WScript.echo Hex(Asc(BinaryFile.Read(1))) 'Returns "A"
BinaryFile.Close


问:
How to create virtual printer with iOS Simulator?
In one of my application there is feature to print documents. I want to test this feature but I don’t have device, So I have to test on Simulator. With simulator how can I print documents. Do I need to connect physical printer or can I create virtual printer and test with it ?

I am using Xcode 8.2.1, iOS 10 and StarPrint iOS SDK 5.2.1

I have searched lot but I didn’t find which work for me. How can I do that ?

I have referred below links :

Where is printer simulator in Xcode 6

Here I cannot find hardware tools for Xcode 8.2.1

答:
The Simulator should be able to see any AirPrint compatible printer that you Mac can see.

You can use a simulated printer. Go to https://developer.apple.com/download/more/.

Download "Additional Tools for Xcode 8.x" corresponding to your version.

Install the package.

Start Printer Simulator

Printer Simulator will automatically register several simulated printers as long as it is running. They will show up in the iOS printer selection view. They also show up to other Macs on your network and even physical iOS devices.


问:
Transposing individual elements of a Python Dictionary
I have a python super dictionary that is made of individual dictionaries and currently looks like this:

```<code>raw_data1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
top_dictionary = {
'raw_data1': raw_data1,
'raw_data2': raw_data2,
'raw_data3': raw_data3
}
print top_dictionary
</code>```

I would like to transpose the individual dictionaries in my top_dictionary  in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column.

As an example the value in top_dictionary with the key: 'raw_data1' will then look like:

```<code>raw_data1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}
</code>```

I know how to do this for each individual dictionary by using the pandas melt function but how do I do this for my top_dictionary such that all elements inside it get transposed accordingly?

Body:
I have a python super dictionary that is made of individual dictionaries and currently looks like this:

raw_data1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
top_dictionary = {
'raw_data1': raw_data1,
'raw_data2': raw_data2,
'raw_data3': raw_data3
}
print top_dictionary

I would like to transpose the individual dictionaries in my top_dictionary  in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column.

As an example the value in top_dictionary with the key: 'raw_data1' will then look like:

raw_data1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}

I know how to do this for each individual dictionary by using the pandas melt function but how do I do this for my top_dictionary such that all elements inside it get transposed accordingly?

Body:
Just loop over the top dictionary items. You'll have to play with if you want strict chronological order:

top_dict_new = dict()
for key, data_dict in top_dictionary.items():
    df = pd.melt(pd.DataFrame(data_dict), id_vars = ['Series_Date'])
    top_dict_new[key] = df.to_dict('list')

Edit:
This yields:

print top_dict_new['raw_data1']
{'variable': ['1M', '1M', '1M', '1M', '3M', '3M', '3M', '3M', 'SP', 'SP', 'SP', 'SP'], 'Series_Date': ['2017-03-10', '2017-03-13', '2017-03-14', '2017-03-15', '2017-03-10', '2017-03-13', '2017-03-14', '2017-03-15', '2017-03-10', '2017-03-13', '2017-03-14', '2017-03-15'], 'value': [-7.7999999999999998, 56.0, 56.0, -3.3999999999999999, 24.0, -31.0, 53.0, 5.0, 35.600000000000001, 56.700000000000003, 41.0, 41.0]}


问:
Warning: UICollectionViewFlowLayout has cached frame mismatch for index path 'abc'
This is the code causing the warning:

```<code>private override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
    let distance = CGRectGetMidX(attributes!.frame) - self.midX;
    var transform = CATransform3DIdentity;
    transform = CATransform3DTranslate(transform, -distance, 0, -self.width);
    attributes!.transform3D = CATransform3DIdentity;
    return attributes
}
</code>```

The console also prints:

This is likely occurring because the flow layout "xyz" is modifying attributes returned by UICollectionViewFlowLayout without copying them.

How do I fix this warning?

答:
It's not the answer to original question, but can help for layoutAttributesForElements(in rect: CGRect) (Swift 3.0): </p>

```<code>let safeAttributes = super.layoutAttributesForElements(in: rect)?.map { $0.copy() as! UICollectionViewLayoutAttributes }
safeAttributes?.forEach { /* do something with attributes*/ }
</code>```

Body:
This is the code causing the warning:

private override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
    let distance = CGRectGetMidX(attributes!.frame) - self.midX;
    var transform = CATransform3DIdentity;
    transform = CATransform3DTranslate(transform, -distance, 0, -self.width);
    attributes!.transform3D = CATransform3DIdentity;
    return attributes
}

The console also prints:

This is likely occurring because the flow layout "xyz" is modifying attributes returned by UICollectionViewFlowLayout without copying them.

How do I fix this warning?

Body:
It's not the answer to original question, but can help for layoutAttributesForElements(in rect: CGRect) (Swift 3.0):

let safeAttributes = super.layoutAttributesForElements(in: rect)?.map { $0.copy() as! UICollectionViewLayoutAttributes }
safeAttributes?.forEach { /* do something with attributes*/ }


问:
Shared Hosting + Entity Framework + MySQL = Data Provider Errors?
long-time listener, first-time caller!

I’m trying to connect to MySQL using the ADO.NET Entity Framework. (Visual Studio 2010, .NET 4.0) I created a web project and another class library project to serve as my DAL. On my local machine, I have no problems, and I have also tried running with Medium trust. I’m able to fully control the db as expected.

When I deploy to my host (shared, medium trust) however, I keep getting errors. I have tweaked my web.config multiple ways: I’ve explicitly called my assembly in the connection string, I’ve used the wildcard mapping, I added references to the MySQL dll’s, etc.

```<code><connectionStrings>
    <add name="NamespaceContext" connectionString="metadata=res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.csdl|res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.ssdl|res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient"/>
    <add name=" NamespaceContext " connectionString="metadata=res://*/;provider=MySql.Data.MySqlClient;provider connection string=" server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient"/>
        <add name=" NamespaceContext " connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=MySql.Data.MySqlClient;provider connection string=" server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient" />
 </connectionStrings>
</code>```

The error I keep getting is:

```<code>System.ArgumentException: The specified store provider cannot be found in the configuration, or is not valid. --->
System.ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.
at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
--- End of inner exception stack trace ---
at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at MyNamespace.Web.Html.TestPage.EntityFrameworkTestButton_Click(Object sender, EventArgs e)
</code>```

I talked to their support guys (who aren’t devs) but they said the MySQL connector is installed and in the GAC. I tried to use the DbProviderFactories section in my web.config, like the following:

```<code><system.data>
    <DbProviderFactories>
      <clear/>
      <remove invariant="MySql.Data.MySqlClient"/>
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
    </DbProviderFactories>
  </system.data>
</code>```

I was hoping I could control this and reference the provider in my project. I then receive the following error:

```<code>System.Data.MetadataException: Schema specified is not valid.
Errors: error 0194: All artifacts loaded into an ItemCollection must have the same version. Multiple versions were encountered.
MySql.Data.Entity.Properties.SchemaDefinition-6.0.ssdl(4,9) : error 0169: All SSDL artifacts must target the same provider. The ProviderManifestToken '5' is different from '5.0' that was encountered earlier.
error 0194: All artifacts loaded into an ItemCollection must have the same version.
</code>```

(lots of the same error message was snipped for brevity)

I am at a complete loss. I tried strongly signing my DAL project, not using a DAL and just creating the .edmx in the web project, all to no avail. I could have sworn I got it working at some point, but perhaps I was delirious.

Sorry for the wall o' text. Can anyone help or shed some light?

Thanks!

答: What happens if you put the mysql dll in your bin folder? Alternatively, try to remove the version restriction on the mysql dll, they may not have that exact version loaded on their servers.</p>

Body:
long-time listener, first-time caller!

I’m trying to connect to MySQL using the ADO.NET Entity Framework. (Visual Studio 2010, .NET 4.0) I created a web project and another class library project to serve as my DAL. On my local machine, I have no problems, and I have also tried running with Medium trust. I’m able to fully control the db as expected.

When I deploy to my host (shared, medium trust) however, I keep getting errors. I have tweaked my web.config multiple ways: I’ve explicitly called my assembly in the connection string, I’ve used the wildcard mapping, I added references to the MySQL dll’s, etc.

<connectionStrings>
    <add name="NamespaceContext" connectionString="metadata=res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.csdl|res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.ssdl|res:// Namespace.Data.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null/DataModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient"/>
    <add name=" NamespaceContext " connectionString="metadata=res://*/;provider=MySql.Data.MySqlClient;provider connection string=" server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient"/>
        <add name=" NamespaceContext " connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=MySql.Data.MySqlClient;provider connection string=" server=myserver;User Id=user;database=thedatabase;password=password;Persist Security Info=True"" providerName="System.Data.EntityClient" />
 </connectionStrings>

The error I keep getting is:

System.ArgumentException: The specified store provider cannot be found in the configuration, or is not valid. --->
System.ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.
at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
--- End of inner exception stack trace ---
at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at MyNamespace.Web.Html.TestPage.EntityFrameworkTestButton_Click(Object sender, EventArgs e)

I talked to their support guys (who aren’t devs) but they said the MySQL connector is installed and in the GAC. I tried to use the DbProviderFactories section in my web.config, like the following:

<system.data>
    <DbProviderFactories>
      <clear/>
      <remove invariant="MySql.Data.MySqlClient"/>
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
    </DbProviderFactories>
  </system.data>

I was hoping I could control this and reference the provider in my project. I then receive the following error:

System.Data.MetadataException: Schema specified is not valid.
Errors: error 0194: All artifacts loaded into an ItemCollection must have the same version. Multiple versions were encountered.
MySql.Data.Entity.Properties.SchemaDefinition-6.0.ssdl(4,9) : error 0169: All SSDL artifacts must target the same provider. The ProviderManifestToken '5' is different from '5.0' that was encountered earlier.
error 0194: All artifacts loaded into an ItemCollection must have the same version.

(lots of the same error message was snipped for brevity)

I am at a complete loss. I tried strongly signing my DAL project, not using a DAL and just creating the .edmx in the web project, all to no avail. I could have sworn I got it working at some point, but perhaps I was delirious.

Sorry for the wall o' text. Can anyone help or shed some light?

Thanks!


问:
Get IOC container in a popup
I am using PRISM 5 in my WPF application. And the Shell view in my application has two regions, consider it as A and B.The region A contains a POPUP (PRISM 5 interactivity feature is used to show popup).

The application is working when i create an instance of the popup view model inside the constructor of the view .

Working code

```<code>public PopupView()
{
    InitializeComponent();
    this.DataContext = new PopupViewModel(); // Working code
}
</code>```

But when i try to create view model instance using the dependency injection.The application fails on the  InitializeComponent(); of the parent view (View A).

DI Not working code

```<code>public PopupView(PopupViewModel viewModel)
{
    InitializeComponent(); // Failing in AView initialze
                           // before reaching here

    this.DataContext = viewModel;
}
</code>```

View model registration in module/bootstrapper

```<code>container.RegisterType<AViewModel>();
</code>```

Error occured

NULLReference Exception occured

Stacktrace(Edited for the question)

```<code>at System.DefaultBinder.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, Object& state)
   at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(Type type, Object[] args)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
   at System.Xaml.XamlObjectWriter.WriteEndObject()
   at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at MyNamespace.AView.InitializeComponent() in e:\xxx\xxxxx\xxx\AView.xaml:line 1
   at MyNamespace.AView..ctor(AViewModel viewModel) in e:\xxx\xxxxx\xxx\AView.xaml.cs:line 18
</code>```

AViewModel(Edited one to avoid project specific information)

```<code> public class ItemSelectionNotification : Confirmation
 {
      //This class includes properties related to my project
 }

public class AViewModel
 {
        public InteractionRequest<ItemSelectionNotification> ItemSelectionRequest { get; private set; }

        public AViewModel(EventAggregator eventAggregator,IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.container = container;
            ItemSelectionRequest = new InteractionRequest<ItemSelectionNotification>();
            SettingsCommand = new DelegateCommand(OnClickSetting);    //Command for settings button click
        }

        //Button click handling
        public void OnClickSetting()
        {
                var notification = new ItemSelectionNotification()
                    {
                        Title = "Items"
                    };
                this.ItemSelectionRequest.Raise(notification,OnSaveCallback);
         }

        private void OnSaveCallback(PropertySelectionNotification returned)
        {
        }
 }
</code>```

答:
I will assume that you use InteractionRequestTrigger with PopupWindowAction in your XAML to bind PopupView to corresponding InteractionRequest.

You can't pass PopupViewModel to the constructor of the PopupView because the view is created by the PopupWindowAction directly and not by DI-container. When PopupWindowAction creates PopupView, it will set view's DataContext to the INotification object that you passed to the InteractionRequest.Raise(…). That INotification has a Content property which can be used to pass any data you want to the PopupView. For example, you can pass PopupViewModel here.

EDIT: I've looked up PopupWindowAction sources and it appears that I'm wrong. They use ServiceLocator when they try to instantiate PopupWindowAction.WindowContentType, so technically passing PopupViewModel to PopupView's constructor should not result in an exception, but it is still useless since view's DataContext is further replaced by the INotification object passed to the InteractionRequest.

Example:

```<code>// PopupViewModel.cs
internal sealed class PopupViewModel
{
    public PopupViewModel(string message)
    {
        Message = message;
    }

    public string Message { get; }
}

// PopupView.xaml
<UserControl …>
    <Grid DataContext="{Binding Content, Mode=OneTime}">
        <Label Text="{Binding Message, Mode=OneTime}" />
    </Grid>
</UserControl>

// SomeViewModel.cs
internal sealed class SomeViewModel
{
    // Don't use DI-container references to construct objects, inject factories instead.
    // Also to keep things simple you can just create your PopupViewModel directly if it has no external dependencies.
    private readonly Func<string, PopupViewModel> _popupViewModelFactory;

    public SomeViewModel(Func<string, PopupViewModel> popupViewModelFactory)
    {
        _popupViewModelFactory = popupViewModelFactory;
    }

    public ICommand ShowPopupCommand { get; } = new DelegateCommand(DoShowPopup);

    public InteractionRequest<INotification> PopupRequest { get; } = new InteractionRequest<INotification>();

    private void DoShowPopup()
    {
        PopupRequest.Raise(new Notification
        {
            Content = _popupViewModelFactory("This is a Popup Message!")
        }, _ =>
        {
            // Callback code.
        });
    }
}

// SomeView.xaml
<UserControl …>
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding PopupRequest, Mode=OneTime}">
            <prism:PopupWindowAction WindowContentType="views:PopupView" />
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>

    <Button Command="{Binding ShowPopupCommand, Mode=OneTime}" />
<UserControl>

// SomeModule.cs (or maybe Bootstrapper.cs if you setup your container in Bootstrapper)
public sealed class SomeModule : IModule
{
    private readonly IUnityContainer _container;

    public SomeModule(IUnityContainer container)
    {
        _container = container;
    }

    public override void Initialize()
    {
        _container.RegisterType<Func<string, PopupViewModel>>(
            new InjectionFactory(c =>
                new Func<string, PopupViewModel>(message =>
                    c.Resolve<PopupViewModel>(
                        new ParameterOverride("message", message))));
    }
}
</code>```

Title: Get IOC container in a popup

Body:
I am using PRISM 5 in my WPF application. And the Shell view in my application has two regions, consider it as A and B.The region A contains a POPUP (PRISM 5 interactivity feature is used to show popup).

The application is working when i create an instance of the popup view model inside the constructor of the view .

Working code

public PopupView()
{
    InitializeComponent();
    this.DataContext = new PopupViewModel(); // Working code
}

But when i try to create view model instance using the dependency injection.The application fails on the  InitializeComponent(); of the parent view (View A).

DI Not working code

public PopupView(PopupViewModel viewModel)
{
    InitializeComponent(); // Failing in AView initialze
                           // before reaching here

    this.DataContext = viewModel;
}

View model registration in module/bootstrapper

container.RegisterType<AViewModel>();

Error occured

NULLReference Exception occured

Stacktrace(Edited for the question)

at System.DefaultBinder.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, Object& state)
   at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(Type type, Object[] args)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
   at System.Xaml.XamlObjectWriter.WriteEndObject()
   at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at MyNamespace.AView.InitializeComponent() in e:\xxx\xxxxx\xxx\AView.xaml:line 1
   at MyNamespace.AView..ctor(AViewModel viewModel) in e:\xxx\xxxxx\xxx\AView.xaml.cs:line 18

AViewModel(Edited one to avoid project specific information)

 public class ItemSelectionNotification : Confirmation
 {
      //This class includes properties related to my project
 }

public class AViewModel
 {
        public InteractionRequest<ItemSelectionNotification> ItemSelectionRequest { get; private set; }

        public AViewModel(EventAggregator eventAggregator,IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.container = container;
            ItemSelectionRequest = new InteractionRequest<ItemSelectionNotification>();
            SettingsCommand = new DelegateCommand(OnClickSetting);    //Command for settings button click
        }

        //Button click handling
        public void OnClickSetting()
        {
                var notification = new ItemSelectionNotification()
                    {
                        Title = "Items"
                    };
                this.ItemSelectionRequest.Raise(notification,OnSaveCallback);
         }

        private void OnSaveCallback(PropertySelectionNotification returned)
        {
        }
 }

Body:
I will assume that you use InteractionRequestTrigger with PopupWindowAction in your XAML to bind PopupView to corresponding InteractionRequest.

You can't pass PopupViewModel to the constructor of the PopupView because the view is created by the PopupWindowAction directly and not by DI-container. When PopupWindowAction creates PopupView, it will set view's DataContext to the INotification object that you passed to the InteractionRequest.Raise(…). That INotification has a Content property which can be used to pass any data you want to the PopupView. For example, you can pass PopupViewModel here.

EDIT: I've looked up PopupWindowAction sources and it appears that I'm wrong. They use ServiceLocator when they try to instantiate PopupWindowAction.WindowContentType, so technically passing PopupViewModel to PopupView's constructor should not result in an exception, but it is still useless since view's DataContext is further replaced by the INotification object passed to the InteractionRequest.

Example:

// PopupViewModel.cs
internal sealed class PopupViewModel
{
    public PopupViewModel(string message)
    {
        Message = message;
    }

    public string Message { get; }
}

// PopupView.xaml
<UserControl …>
    <Grid DataContext="{Binding Content, Mode=OneTime}">
        <Label Text="{Binding Message, Mode=OneTime}" />
    </Grid>
</UserControl>

// SomeViewModel.cs
internal sealed class SomeViewModel
{
    // Don't use DI-container references to construct objects, inject factories instead.
    // Also to keep things simple you can just create your PopupViewModel directly if it has no external dependencies.
    private readonly Func<string, PopupViewModel> _popupViewModelFactory;

    public SomeViewModel(Func<string, PopupViewModel> popupViewModelFactory)
    {
        _popupViewModelFactory = popupViewModelFactory;
    }

    public ICommand ShowPopupCommand { get; } = new DelegateCommand(DoShowPopup);

    public InteractionRequest<INotification> PopupRequest { get; } = new InteractionRequest<INotification>();

    private void DoShowPopup()
    {
        PopupRequest.Raise(new Notification
        {
            Content = _popupViewModelFactory("This is a Popup Message!")
        }, _ =>
        {
            // Callback code.
        });
    }
}

// SomeView.xaml
<UserControl …>
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding PopupRequest, Mode=OneTime}">
            <prism:PopupWindowAction WindowContentType="views:PopupView" />
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>

    <Button Command="{Binding ShowPopupCommand, Mode=OneTime}" />
<UserControl>

// SomeModule.cs (or maybe Bootstrapper.cs if you setup your container in Bootstrapper)
public sealed class SomeModule : IModule
{
    private readonly IUnityContainer _container;

    public SomeModule(IUnityContainer container)
    {
        _container = container;
    }

    public override void Initialize()
    {
        _container.RegisterType<Func<string, PopupViewModel>>(
            new InjectionFactory(c =>
                new Func<string, PopupViewModel>(message =>
                    c.Resolve<PopupViewModel>(
                        new ParameterOverride("message", message))));
    }
}


答:
I have corrected your program. You were trying to create n+1 nodes and iterating in wrong way. Just use one variable from start and stop till you reach NULL value. Let me know if you din't understand any part of it.</p>

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

struct node{

    int student;
    int exam;
    struct node *link;
};

int main(void){

    int student_num, exam_num, node_num, i;
    struct node *start;
    struct node *next;
    struct node *temp;

    printf("How many nodes?: ");
    scanf("%d",&node_num);

    if(node_num == 0) {
        return 0;
    }

    temp = (node*)malloc(sizeof(struct node));
    start = temp;

    start->link = NULL;

    next = start;

    //Creates node_num nodes
    for(i=1;i<node_num;i++){

        temp = (node*)malloc(sizeof(struct node));

        next->link=temp;

        next=temp;
        next->link=NULL;
    }

    //Fills in the numbers
    for(temp=start;temp!=NULL;temp=temp->link){

        printf("\nStudent number: ");
        scanf("%d",&student_num);

        temp->student=student_num;

        printf("Exam number: ");
        scanf("%d",&exam_num);

        temp->exam=exam_num;

    }

    //Shows the result
    for(temp=start;temp!=NULL;temp=temp->link){

        printf("\nStudent number: %d\tExam number: %d\n",temp->student,temp->exam);
    }

}
</code>```

Title: Trying to create linked list in C. But only half the requested nodes are created

Body:
I have corrected your program. You were trying to create n+1 nodes and iterating in wrong way. Just use one variable from start and stop till you reach NULL value. Let me know if you din't understand any part of it.

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

struct node{

    int student;
    int exam;
    struct node *link;
};

int main(void){

    int student_num, exam_num, node_num, i;
    struct node *start;
    struct node *next;
    struct node *temp;

    printf("How many nodes?: ");
    scanf("%d",&node_num);

    if(node_num == 0) {
        return 0;
    }

    temp = (node*)malloc(sizeof(struct node));
    start = temp;

    start->link = NULL;

    next = start;

    //Creates node_num nodes
    for(i=1;i<node_num;i++){

        temp = (node*)malloc(sizeof(struct node));

        next->link=temp;

        next=temp;
        next->link=NULL;
    }

    //Fills in the numbers
    for(temp=start;temp!=NULL;temp=temp->link){

        printf("\nStudent number: ");
        scanf("%d",&student_num);

        temp->student=student_num;

        printf("Exam number: ");
        scanf("%d",&exam_num);

        temp->exam=exam_num;

    }

    //Shows the result
    for(temp=start;temp!=NULL;temp=temp->link){

        printf("\nStudent number: %d\tExam number: %d\n",temp->student,temp->exam);
    }

}


问:
Stop printing after certain HTML tags
I have written the following script to print the page.

Is it possible to Not Print the HTML after the following tag

```<code> <font class="productnamecolorSMALL colors_productname"><b>Related Items</b></font>
</code>```

Meaning ignore the print after the above

```<code><p>Click the button to print the current page.</p>

    <button onclick="myFunction()">Print this page</button>
    <script>
    function myFunction() {
        window.print();
    }
    </script>
</code>```

答:
As Alexis Wilke suggested add a print stylesheet.

This css will remove the first adjacent sibling of .productnamecolorSMALL from the printed page by using the adjacent sibling selector. You can use whatever css you want to mark what you want to remove or display differently while printing. So just edit the print stylesheet to your needs.

html

```<code><link rel="stylesheet" media="print" href="/css/print.css" type="text/css" />
</code>```

css

```<code>@media print{
  .productnamecolorSMALL+*{
    display: none;
  }
}
</code>```

Title: Stop printing after certain HTML tags

Body:
I have written the following script to print the page.

Is it possible to Not Print the HTML after the following tag

 Related Items

Meaning ignore the print after the above

Click the button to print the current page.

    <button onclick="myFunction()">Print this page</button>

Body:
As Alexis Wilke suggested add a print stylesheet.

This css will remove the first adjacent sibling of .productnamecolorSMALL from the printed page by using the adjacent sibling selector. You can use whatever css you want to mark what you want to remove or display differently while printing. So just edit the print stylesheet to your needs.

html

<link rel="stylesheet" media="print" href="/css/print.css" type="text/css" />

css

@media print{
  .productnamecolorSMALL+*{
    display: none;
  }
}


问:
How Can I Resolve An 'npm Warn' When Using 'create-react-app'?
I'm getting the following warning when using 'create-react-app': npm WARN prefer global marked@0.3.6 should be installed with -g

How can I get rid of this warning?

I looked at "Question that may already have your answer" and didn't seem to find a precise answer. However, I'm new and may have overlooked the obvious.

My installs are:

```<code>$ npm -v
4.3.0

$ node --version
v7.0.0

$ npm list -g create-react-app
/usr/local/lib
└── create-react-app@1.2.1

$ npm list -g marked@
/usr/local/lib
└── marked@0.3.6
</code>```

It looks to me that this package is already installed globally.

I ran the following:

```<code>$ sudo npm update -g create-react-app
</code>```

which resulted in the following:

```<code>$ npm list -g create-react-app
/usr/local/lib
└── create-react-app@1.3.0
</code>```

However, I still get:

```<code>npm WARN prefer global marked@0.3.6 should be installed with -g
</code>```

答:
Because that package includes the CLI.

Try to remove and install create-react-app to the newest version 1.3.0

npm install -g create-react-app

Body:
I'm getting the following warning when using 'create-react-app': npm WARN prefer global marked@0.3.6 should be installed with -g

How can I get rid of this warning?

I looked at "Question that may already have your answer" and didn't seem to find a precise answer. However, I'm new and may have overlooked the obvious.

My installs are:

$ npm -v
4.3.0

$ node --version
v7.0.0

$ npm list -g create-react-app
/usr/local/lib
└── create-react-app@1.2.1

$ npm list -g marked@
/usr/local/lib
└── marked@0.3.6

It looks to me that this package is already installed globally.

I ran the following:

$ sudo npm update -g create-react-app

which resulted in the following:

$ npm list -g create-react-app
/usr/local/lib
└── create-react-app@1.3.0

However, I still get:

npm WARN prefer global marked@0.3.6 should be installed with -g


问:
Check for usage of an XML Schema Collection?
As part of a script, in which execution is halted and changes are rolled back if there are any errors, I use the following statements to drop an xml schema collection if it exists

```<code>IF EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'MyXMLSchemaCollection')
BEGIN
    PRINT 'Drop MyXMLSchemaCollection';
    DROP XML SCHEMA COLLECTION MyXMLSchemaCollection;
END
GO
</code>```

This works nicely except for when the schema collection is in use, the result of which is an error like the following:

Specified collection 'MyXMLSchemaCollection' cannot be dropped because it is used by object 'MyObject'.

How would I go about only dropping the schema collection if it is not used by any objects in the database? The xml schema collection does not need to be dropped if it's being used.

答:
Using the example XML Schema Collection from MSDN documentation ALTER XML SCHEMA COLLECTION (Transact-SQL) I found that you can determine if an XML Schema Collection is being referenced by a table using:

```<code>select distinct t.name from sys.tables t
left join sys.columns c ON c.object_id = t.object_id
left join sys.xml_schema_collections x ON x.xml_collection_id = c.xml_collection_id
where x.name = 'MyXMLSchemaCollection'
</code>```

Also for stored procedures and I imagine other object types sys.sql_expression_dependencies table will be of use to you.

```<code>select
    *
from sys.sql_expression_dependencies sed
left join sys.objects o ON o.object_id = sed.referencing_id
where referenced_entity_name = 'MyXMLSchemaCollection'
</code>```

Have a look at these questions for more information on exploring object catalogs:

List of Stored Procedure from Table

Find all references to an object in an SQL Server database

Body:
As part of a script, in which execution is halted and changes are rolled back if there are any errors, I use the following statements to drop an xml schema collection if it exists

IF EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'MyXMLSchemaCollection')
BEGIN
    PRINT 'Drop MyXMLSchemaCollection';
    DROP XML SCHEMA COLLECTION MyXMLSchemaCollection;
END
GO

This works nicely except for when the schema collection is in use, the result of which is an error like the following:

Specified collection 'MyXMLSchemaCollection' cannot be dropped because it is used by object 'MyObject'.

How would I go about only dropping the schema collection if it is not used by any objects in the database? The xml schema collection does not need to be dropped if it's being used.

Body:
Using the example XML Schema Collection from MSDN documentation ALTER XML SCHEMA COLLECTION (Transact-SQL) I found that you can determine if an XML Schema Collection is being referenced by a table using:

select distinct t.name from sys.tables t
left join sys.columns c ON c.object_id = t.object_id
left join sys.xml_schema_collections x ON x.xml_collection_id = c.xml_collection_id
where x.name = 'MyXMLSchemaCollection'

Also for stored procedures and I imagine other object types sys.sql_expression_dependencies table will be of use to you.

select
    *
from sys.sql_expression_dependencies sed
left join sys.objects o ON o.object_id = sed.referencing_id
where referenced_entity_name = 'MyXMLSchemaCollection'

Have a look at these questions for more information on exploring object catalogs:

List of Stored Procedure from Table

Find all references to an object in an SQL Server database


问:
Deleting a file after transcoding with AWS Lambda and Elastic Transcoder
I'm using a Lambda python script to call Elastic Transcoder on a file that I upload.  How do I delete the file after transcoding?

At the moment, my code creates the job, and then deletes the source file straight away, i.e., before the job even has a chance to run. :-)

How can I wait for Elastic Transcode to finish?

```<code>import os
import boto3
import urllib

def lambda_handler(event, context):
  transcoder = boto3.client('elastictranscoder', 'ap-southeast-2')
  pipeline_id = get_pipeline(transcoder, 'MP4 Transcode')
  base_filename = os.path.basename(event['Records'][0]['s3']['object']['key'])
  output = transcoder.create_job(
      PipelineId=pipeline_id,
      Input={
      'Key': create_aws_filename('uploads', base_filename, ''),
      'FrameRate': 'auto',
      'Resolution': 'auto',
      'AspectRatio': 'auto',
      'Interlaced': 'auto',
      'Container' : 'auto'
  })
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'])
print("deleting " + key)
boto3.client('s3').delete_object(Bucket=bucket, Key=key)
</code>```

答:
You basically have to poll Elastic Transcoder for the job's status (every 30 seconds, for example), and wait until the job is completed. Once the job is completed, you can delete your S3 source file.

Using boto3, you can retrieve a job's status like this:

```<code>transcoder = boto3.client('elastictranscoder')
job = transcoder.read_job(Id=job_id)
status = job['Job']['Status']
</code>```

Or alternatively, you can use the job_complete waiter.

Body:
I'm using a Lambda python script to call Elastic Transcoder on a file that I upload.  How do I delete the file after transcoding?

At the moment, my code creates the job, and then deletes the source file straight away, i.e., before the job even has a chance to run. :-)

How can I wait for Elastic Transcode to finish?

import os
import boto3
import urllib

def lambda_handler(event, context):
  transcoder = boto3.client('elastictranscoder', 'ap-southeast-2')
  pipeline_id = get_pipeline(transcoder, 'MP4 Transcode')
  base_filename = os.path.basename(event['Records'][0]['s3']['object']['key'])
  output = transcoder.create_job(
      PipelineId=pipeline_id,
      Input={
      'Key': create_aws_filename('uploads', base_filename, ''),
      'FrameRate': 'auto',
      'Resolution': 'auto',
      'AspectRatio': 'auto',
      'Interlaced': 'auto',
      'Container' : 'auto'
  })
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'])
print("deleting " + key)
boto3.client('s3').delete_object(Bucket=bucket, Key=key)

Body:
You basically have to poll Elastic Transcoder for the job's status (every 30 seconds, for example), and wait until the job is completed. Once the job is completed, you can delete your S3 source file.

Using boto3, you can retrieve a job's status like this:

transcoder = boto3.client('elastictranscoder')
job = transcoder.read_job(Id=job_id)
status = job['Job']['Status']

Or alternatively, you can use the job_complete waiter.