问:
Multiplying certain elements within an array
I am coding an nth term of a mathematical sequence generator. I'm just experimenting with the first seven terms for now.

The user enters 1,2,3,4,5,6 and 7 (or any other consecutive values) into the sequence, then the program should multiply the 1st, then every other term entered by 8 (so in this case the 1st, 3rd, 5th and 7th numbers entered).

It should also multiply the 2nd then every other term entered by 2 (so in this case the 2nd, 4th and 6th numbers entered).

Afterwards, I want it to add everything together. Here is what I tried to do:

```<code>x = [0,0,0,0,0,0,0]
for n in range (0,7):
    x[n] = int(input("Input the digits of the sequence one by one:"))
    if x[n] == x[0] or x[2] or x[4] or x[6]:
        x[n] == x[n]*8

    elif x[n] == x[1] or x[3] or x[5]:
        x[n] == x[n]*2

    else:
        break

finalnumber = x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]
print(finalnumber)
</code>```

I inputted 1,2,3,4,5,6 and 7 and calculated myself that the finalnumber should be 152, however this program for some reason printed 28.

Please tell me what I have done wrong.

I am using Python 3.6.

答:
Although, this is not the most pythonic way of doing this but there are two major errors with your code.

Firstly, inside the if conditions, you need to check for each of the  values. So, replace x[n] == x[0] or x[2] or x[4] or x[6]: with if (x[n] == x[0]) or (x[n] == x[2]) or (x[n] == x[4]) or (x[n] == x[6]):

Secondly, you need to use the assignment operator ( = ) instead of using comparison operator ( == ) inside condition blocks. So, replace x[n] == x[n]*2 with x[n] = x[n]*2

The reason you were getting 28 as the result because x[n] = int(input("Input the digits of the sequence one by one:")) will assign values to x as [1, 2, 3, 4, 5, 6, 7] and in your if-else blocks, there is no assignment of any kind. So, x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6] will result in 1 + 2 + 3 + 4 + 5 + 6 + 7 which is equal to 28.

You can do something like this :

```<code>x = [0,0,0,0,0,0,0]
for n in range (0,7):
    x[n] = int(input("Input the digits of the sequence one by one:"))
    if (x[n] == x[0]) or (x[n] == x[2]) or (x[n] == x[4]) or (x[n] == x[6]):
        x[n] = x[n]*8

    elif (x[n] == x[1]) or (x[n] == x[3]) or (x[n] == x[5]):
        x[n] = x[n]*2

    else:
        break

finalnumber = x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]
print(finalnumber)
</code>```

This will result in :

```<code>152
</code>```

Alternatively, if you want to do this a bit pythonic way, you can do something like this :

```<code>x = [int(input("Input the digits of the sequence one by one : ")) for _ in range(7)]
finalnumber = sum([num * 8 if i % 2 == 0 else num * 2 for i, num in enumerate(x)])
print(finalnumber)
</code>```

This will also result in :

```<code>152
</code>```

Body:
I am coding an nth term of a mathematical sequence generator. I'm just experimenting with the first seven terms for now.

The user enters 1,2,3,4,5,6 and 7 (or any other consecutive values) into the sequence, then the program should multiply the 1st, then every other term entered by 8 (so in this case the 1st, 3rd, 5th and 7th numbers entered).

It should also multiply the 2nd then every other term entered by 2 (so in this case the 2nd, 4th and 6th numbers entered).

Afterwards, I want it to add everything together. Here is what I tried to do:

x = [0,0,0,0,0,0,0]
for n in range (0,7):
    x[n] = int(input("Input the digits of the sequence one by one:"))
    if x[n] == x[0] or x[2] or x[4] or x[6]:
        x[n] == x[n]*8

    elif x[n] == x[1] or x[3] or x[5]:
        x[n] == x[n]*2

    else:
        break

finalnumber = x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]
print(finalnumber)

I inputted 1,2,3,4,5,6 and 7 and calculated myself that the finalnumber should be 152, however this program for some reason printed 28.

Please tell me what I have done wrong.

I am using Python 3.6.

Body:
Although, this is not the most pythonic way of doing this but there are two major errors with your code.

Firstly, inside the if conditions, you need to check for each of the  values. So, replace x[n] == x[0] or x[2] or x[4] or x[6]: with if (x[n] == x[0]) or (x[n] == x[2]) or (x[n] == x[4]) or (x[n] == x[6]):

Secondly, you need to use the assignment operator ( = ) instead of using comparison operator ( == ) inside condition blocks. So, replace x[n] == x[n]*2 with x[n] = x[n]*2

The reason you were getting 28 as the result because x[n] = int(input("Input the digits of the sequence one by one:")) will assign values to x as [1, 2, 3, 4, 5, 6, 7] and in your if-else blocks, there is no assignment of any kind. So, x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6] will result in 1 + 2 + 3 + 4 + 5 + 6 + 7 which is equal to 28.

You can do something like this :

x = [0,0,0,0,0,0,0]
for n in range (0,7):
    x[n] = int(input("Input the digits of the sequence one by one:"))
    if (x[n] == x[0]) or (x[n] == x[2]) or (x[n] == x[4]) or (x[n] == x[6]):
        x[n] = x[n]*8

    elif (x[n] == x[1]) or (x[n] == x[3]) or (x[n] == x[5]):
        x[n] = x[n]*2

    else:
        break

finalnumber = x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]
print(finalnumber)

This will result in :

152

Alternatively, if you want to do this a bit pythonic way, you can do something like this :

x = [int(input("Input the digits of the sequence one by one : ")) for _ in range(7)]
finalnumber = sum([num * 8 if i % 2 == 0 else num * 2 for i, num in enumerate(x)])
print(finalnumber)

This will also result in :

152


来源: stackexchange

问:
2 satisfiability strongly connected components topological ordering
I'm solving a two-satisfiability problem with SCCs, and have a question about topological sorting. The algorithm I'm basing this on is to process SCCs in reverse topological order, which is fine when they're all connected. My algorithm is breaking on cases like this:

```<code>3 3
-2 3
1 -2
-2 -1
</code>```

This makes a graph that looks like this:

There are two sources and two sinks in this graph, and depending on where you start there are multiple topological sorts, so there are two possible final nodes. There are no cycles so each node is an SCC. There are multiple paths from source to sink, so when I do reverse topological order I can either start at sink x3 or sink !x2. The path that will give me a correct answer is to start at !x2, which will result in 1, -2, -3 or -1, -2, -3, both of which are solutions. But if I start at x3, one possible outcome is -1, 2, 3, which is not a solution.

So when I look at my two sinks, how do I decide topologically which is last? Clearly the answer is !x2, but I'm trying to figure out how the algorithm will determine that. I see four possible ideas:

!x2 is last because it has more nodes leading into it

!x2 is last because it is at the end of a longer path

Set the truth value of each of the sinks before I start processing anything

There is no way to know which is last, so create all possible solutions and test each of them to see if it works.

Or is there something about topologically ordering SCCs I'm not getting here? This is based on the algorithm I used to pass a Strongly Connected Components assignment in an earlier course, so it can't be completely wrong.

答:
Without seeing your code I can't be sure, but my guess is that  when you process the literals you're setting a value and then flipping it later when you encounter its negation deeper in the topological order.  The key is that once you set a variable, you don't change it again.  Skip the literal of any variable that already has a set value.

Edited to add: From your comment I think I see the problem.  You mention setting the variable x2 to true when !x2 comes first in the reverse topological sort.  You should be setting the literal !x2 to true, which means you set the variable x2 to false.  If you do that, then your solver should work not matter which of the sinks you start with.

ContentLicense: CC BY-SA 3.0

Body:
I'm solving a two-satisfiability problem with SCCs, and have a question about topological sorting. The algorithm I'm basing this on is to process SCCs in reverse topological order, which is fine when they're all connected. My algorithm is breaking on cases like this:

3 3
-2 3
1 -2
-2 -1

This makes a graph that looks like this:

There are two sources and two sinks in this graph, and depending on where you start there are multiple topological sorts, so there are two possible final nodes. There are no cycles so each node is an SCC. There are multiple paths from source to sink, so when I do reverse topological order I can either start at sink x3 or sink !x2. The path that will give me a correct answer is to start at !x2, which will result in 1, -2, -3 or -1, -2, -3, both of which are solutions. But if I start at x3, one possible outcome is -1, 2, 3, which is not a solution.

So when I look at my two sinks, how do I decide topologically which is last? Clearly the answer is !x2, but I'm trying to figure out how the algorithm will determine that. I see four possible ideas:

!x2 is last because it has more nodes leading into it

!x2 is last because it is at the end of a longer path

Set the truth value of each of the sinks before I start processing anything

There is no way to know which is last, so create all possible solutions and test each of them to see if it works.

Or is there something about topologically ordering SCCs I'm not getting here? This is based on the algorithm I used to pass a Strongly Connected Components assignment in an earlier course, so it can't be completely wrong.


问:
Latest Mongodb search collection
There are currently many conflicting posts regarding mongodb and php due to the driver version. I am using driver 1.2.7, php 5.6 and the latest mongodb on XAMPP

This is my current code:

```<code>$filter = [ 'userID' => $myUserId, 'isSold' => true];

$cmdOne = new MongoDB\Driver\Command([

    'distinct' => 'collectionNameHere',
    'key' => 'productID',
    'query' => $filter

]);

$cursorOne = $connection->executeCommand('DatabaseNameHere', $cmdOne);

$products = current($cursorOne->toArray())->values;
</code>```

Is there a way to find non-distinct results?

This does not work due to the different mongoDb driver:
MongoDB search in collection

答:
You've to use executeQuery with query filter and projection</p>

```<code>$filter = [ 'userID' => $myUserId, 'isSold' => true];

$projection = ['projection' => ['productID' => 1]];

$query = new MongoDB\Driver\Query($filter, $projection);

$cursor = $connection->executeQuery('DatabaseNameHere.CollectionNameHere', $query);
</code>```

Title: Latest Mongodb search collection

Body:
There are currently many conflicting posts regarding mongodb and php due to the driver version. I am using driver 1.2.7, php 5.6 and the latest mongodb on XAMPP

This is my current code:

$filter = [ 'userID' => $myUserId, 'isSold' => true];

$cmdOne = new MongoDB\Driver\Command([

    'distinct' => 'collectionNameHere',
    'key' => 'productID',
    'query' => $filter

]);

$cursorOne = $connection->executeCommand('DatabaseNameHere', $cmdOne);

$products = current($cursorOne->toArray())->values;

Is there a way to find non-distinct results?

This does not work due to the different mongoDb driver:
MongoDB search in collection

Body:
You've to use executeQuery with query filter and projection

$filter = [ 'userID' => $myUserId, 'isSold' => true];

$projection = ['projection' => ['productID' => 1]];

$query = new MongoDB\Driver\Query($filter, $projection);

$cursor = $connection->executeQuery('DatabaseNameHere.CollectionNameHere', $query);


问:
BigInteger, BitSet and their bit and byte order
Consider following code (java8):

```<code>@Test
public void testBigIntegerVsBitSet() throws Throwable
{
    String bitString529 = "00000010 00010001";        // <- value = 529 (LittleEndian)
    byte[] arr529 = new byte[] { 0x02, 0x11 };        // <- the same as byte array (LittleEndian)
    BigInteger bigIntByString = new BigInteger( bitString529.replace( " ", ""), 2); // throws if there is a blank!
    BigInteger bigIntByArr = new BigInteger( arr529);
    BitSet bitsetByArr = BitSet.valueOf( arr529);  // interpretes bit-order as LittleEndian, but byte-order as BigEndian !!!

    System.out.println( "bitString529     : " + bitString529);              // bitString529     : 00000010 00010001
    System.out.println( "arr529.toString  : " + Arrays.toString( arr529));  // arr529.toString  : [2, 17]
    System.out.println( "bigIntByString   : " + bigIntByString);            // bigIntByString   : 529
    System.out.println( "bigIntByArr      : " + bigIntByArr);               // bigIntByArr      : 529
    System.out.println( "bitsetByArr      : " + bitsetByArr.toString() );   // bitsetByArr      : {1, 8, 12}
    System.out.println( "expecting        : {0, 4, 9}");                    // expecting        : {0, 4, 9}

    String bigIntByStringStr = toBitString( bigIntByString::testBit);
    String bigIntByArrStr = toBitString( bigIntByArr::testBit);
    String bitsetByArrStr = toBitString( bitsetByArr::get);

    System.out.println( "bigIntByStringStr: " + bigIntByStringStr);         // bigIntByStringStr: 1000100001000000
    System.out.println( "bigIntByArrStr   : " + bigIntByArrStr);            // bigIntByArrStr   : 1000100001000000
    System.out.println( "bitsetByArrStr   : " + bitsetByArrStr );           // bitsetByArrStr   : 0100000010001000
}

private String toBitString( Function<Integer, Boolean> aBitTester)
{
    StringBuilder sb =  new StringBuilder();
    for ( int i = 0; i < 16; i++ )
    {
        sb.append( aBitTester.apply( i) ? "1" : "0");
    }
    return sb.toString();
}
</code>```

which prooves that the BitSet parses byte arrays as BIG_ENDIAN whereas it interpretes the bit order (of a single byte) as LITTLE_ENDIAN. The BigInteger in contrast interpretes both in LITTLE_ENDIAN, even when loaded by a bit string.

Especially the iteration on the bit indices of the two classes (BitInteger::testBit vs. BitSet::get) delivers different results.

Is there a reason for this inconsistency?

答:
Endianess mostly refers only to the ordering of bytes, not to the ordering of the individual bits. The latter is not relevant in most applications, because you cannot for example address individual bits in memory. So endianness of bits in a byte is only used in cases where it is important, such as serial data buses, and otherwise bytes are typically treated as the numbers they represent without any endianness (cf. Wikipedia and the answers to Can endianness refer to bits order in a byte?).

So because of this BitSet treats bytes as having their least-significant bit first such that when you give it the byte 0x01 you get the expected result of having the lowest bit set, regardless of what endianness it uses for the ordering of the bytes. This is why your outputs using BigInteger and BitSet differ only in the order of the bytes.

Note that for the order of bytes, BitSet uses little-endianness, and BigInteger uses big endianness (different from what you claim).

As to why BitSet uses a different endianness than BigInteger, we can only speculate. Note that the respected BitSet methods are much newer (introduced only in Java 1.7), so maybe perceived importance of little- vs. big-endianness has changed since the BigInteger was introduced.

Body:
Consider following code (java8):

@Test
public void testBigIntegerVsBitSet() throws Throwable
{
    String bitString529 = "00000010 00010001";        // <- value = 529 (LittleEndian)
    byte[] arr529 = new byte[] { 0x02, 0x11 };        // <- the same as byte array (LittleEndian)
    BigInteger bigIntByString = new BigInteger( bitString529.replace( " ", ""), 2); // throws if there is a blank!
    BigInteger bigIntByArr = new BigInteger( arr529);
    BitSet bitsetByArr = BitSet.valueOf( arr529);  // interpretes bit-order as LittleEndian, but byte-order as BigEndian !!!

    System.out.println( "bitString529     : " + bitString529);              // bitString529     : 00000010 00010001
    System.out.println( "arr529.toString  : " + Arrays.toString( arr529));  // arr529.toString  : [2, 17]
    System.out.println( "bigIntByString   : " + bigIntByString);            // bigIntByString   : 529
    System.out.println( "bigIntByArr      : " + bigIntByArr);               // bigIntByArr      : 529
    System.out.println( "bitsetByArr      : " + bitsetByArr.toString() );   // bitsetByArr      : {1, 8, 12}
    System.out.println( "expecting        : {0, 4, 9}");                    // expecting        : {0, 4, 9}

    String bigIntByStringStr = toBitString( bigIntByString::testBit);
    String bigIntByArrStr = toBitString( bigIntByArr::testBit);
    String bitsetByArrStr = toBitString( bitsetByArr::get);

    System.out.println( "bigIntByStringStr: " + bigIntByStringStr);         // bigIntByStringStr: 1000100001000000
    System.out.println( "bigIntByArrStr   : " + bigIntByArrStr);            // bigIntByArrStr   : 1000100001000000
    System.out.println( "bitsetByArrStr   : " + bitsetByArrStr );           // bitsetByArrStr   : 0100000010001000
}

private String toBitString( Function<Integer, Boolean> aBitTester)
{
    StringBuilder sb =  new StringBuilder();
    for ( int i = 0; i < 16; i++ )
    {
        sb.append( aBitTester.apply( i) ? "1" : "0");
    }
    return sb.toString();
}

which prooves that the BitSet parses byte arrays as BIG_ENDIAN whereas it interpretes the bit order (of a single byte) as LITTLE_ENDIAN. The BigInteger in contrast interpretes both in LITTLE_ENDIAN, even when loaded by a bit string.

Especially the iteration on the bit indices of the two classes (BitInteger::testBit vs. BitSet::get) delivers different results.

Is there a reason for this inconsistency?


问:
How to find the second lowest and second highest number in a user-inputted list using loops and no arrays
For my program, I need to find the highest pair and lowest pair from 8 user-inputted ints, I am required to use a loop and no arrays.
Ex. 6, 7, 8, 9, 10, 11, 12, 13 should return: (13, 12) , (6, 7)

How should I go about finding the second highest and second lowest number using a loop?

答:
Read your integers into an array

```<code>Scanner scanner = new Scanner(System.in);
int[] array = new int[8];

for (int i = 0; i < array.length; i++) {
    array[i] = Integer.parseInt(scanner.next());
}
</code>```

Sort the array

```<code>Arrays.sort(array);
</code>```

Print the 4 integers you are interested in

```<code>int min1 = array[0];
int min2 = array[1];
int max1 = array[6];
int max2 = array[7];

System.out.println("(" + max2 + "," + max1 + "), (" + min1 + "," + min2 + ")");
</code>```

Body:
Read your integers into an array

Scanner scanner = new Scanner(System.in);
int[] array = new int[8];

for (int i = 0; i < array.length; i++) {
    array[i] = Integer.parseInt(scanner.next());
}

Sort the array

Arrays.sort(array);

Print the 4 integers you are interested in

int min1 = array[0];
int min2 = array[1];
int max1 = array[6];
int max2 = array[7];

System.out.println("(" + max2 + "," + max1 + "), (" + min1 + "," + min2 + ")");


问:
How to print out a cell?
In MATLAB (R2015b) I have a cell C (1x4 cell, with 4 columns):

```<code>C = [4x1 double] [4x1 double] {4x1 cell} {4x1 cell}
</code>```

And when I call C I get the printout above, but I want MATLAB to write it as:

[10]   [31.2]   'TRS'   'BLU'
[12]   [34.2]   'TRS'   'BLU'
[13]   [33.5]   'TRS'   'BLU'
[14]   [34.8]   'TRS'   'BLU'

I.e. a 4x4 cell. How can I get this printout? Thanks

答:
I think this can work </p>

```<code>for i=1:numel(c)
    fprintf('%g %g %s %s\n',c{1}(i),c{2}(i),c{3}{i},c{4}{i})
end
</code>```

Title: How to print out a cell?

Body:
In MATLAB (R2015b) I have a cell C (1x4 cell, with 4 columns):

C = [4x1 double] [4x1 double] {4x1 cell} {4x1 cell}

And when I call C I get the printout above, but I want MATLAB to write it as:

[10]   [31.2]   'TRS'   'BLU'
[12]   [34.2]   'TRS'   'BLU'
[13]   [33.5]   'TRS'   'BLU'
[14]   [34.8]   'TRS'   'BLU'

I.e. a 4x4 cell. How can I get this printout? Thanks

Body:
I think this can work

for i=1:numel(c)
    fprintf('%g %g %s %s\n',c{1}(i),c{2}(i),c{3}{i},c{4}{i})
end


问:
formatting of prime factorization algorithm
suppose we have following script for  prime factorization

```<code> z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
</code>```

but output of this code is not formatted well,for instance

```<code> >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1
</code>```

how can i do  so  that i got

```<code>30=2^1*3^1*5^1?
</code>```

thanks in advance

答:
You can simply create a string and add your numbers to the string and finally print the string. something as follow:</p>

```<code> z=input('enter your number : ');
for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
        str = str + [num2str(ii) '^' num2str(s) '*' ];%only update
        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        end
    end
    str = str(0,str.size -1) %use proper command to remove the last * from your string result
    disp(str) ; %display the str at the end in one line
end
</code>```

Body:
suppose we have following script for  prime factorization

 z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end

but output of this code is not formatted well,for instance

 >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1

how can i do  so  that i got

30=2^1*3^1*5^1?

thanks in advance

Body:
You can simply create a string and add your numbers to the string and finally print the string. something as follow:

 z=input('enter your number : ');
for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
        str = str + [num2str(ii) '^' num2str(s) '*' ];%only update
        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        end
    end
    str = str(0,str.size -1) %use proper command to remove the last * from your string result
    disp(str) ; %display the str at the end in one line
end


问:
Multiple form validation with jQuery plugin submit by onclick without submit button
I have multiple form but it need to validation by jquery validation plugin. when i use submit button it works fine but when i use jquery on click function to submit form it works only first form and others form not working.

Here is my code.......

HTML...

```<code><form class="validateForm">
    <div class="form-group has-feedback">
       <input id="form-field-9" class="form-control new_stock" name="new_stock" type="text">
    </div>
     <a href="javascript:void(0)"  class="btn btn-xs btn-green stock_details" title="Product Stock Update">
     <i class="fa fa-edit"></i>
         Stock Update
     </a>
</form>
</code>```

my jquery......

```<code><script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
    $(function () {
        var site_url = $('.site_url').val();
        var stockUpdateForm =  $('.validateForm').each(function(key, form) {
            $(form).validate({
                rules: {
                    new_stock: {
                        required: true,
                        digits:true
                    }
                },
                highlight: function (element) {
                    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
                },
                unhighlight: function (element) {
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                },
                errorElement: 'span',
                errorClass: 'help-block',
                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length) {
                        error.insertAfter(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });
        });
        $('.stock_details').on('click', function () {
           if(stockUpdateForm.valid()) {
               // only one form work but another form not working
           }
        })
    })
</script>
</code>```

Note: when use submit button it works fine but not working click function

答:
Your code...

```<code>$('.stock_details').on('click', function () {
    if(stockUpdateForm.valid()) { ....
</code>```

You can only attach the .valid() method to a specific form or form element, however your stockUpdateForm represents neither kind of thing.

Try this instead.  Using jQuery's $(this) keyword, you can target only the relevant form surrounding the clicked button.

```<code>$('.stock_details').on('click', function () {
    if($(this).parent('form').valid()) { ....
</code>```

Body:
I have multiple form but it need to validation by jquery validation plugin. when i use submit button it works fine but when i use jquery on click function to submit form it works only first form and others form not working.

Here is my code.......

HTML...

<form class="validateForm">

       <input id="form-field-9" class="form-control new_stock" name="new_stock" type="text">

         Stock Update

</form>

my jquery......

Note: when use submit button it works fine but not working click function

Body:
Your code...

$('.stock_details').on('click', function () {
    if(stockUpdateForm.valid()) { ....

You can only attach the .valid() method to a specific form or form element, however your stockUpdateForm represents neither kind of thing.

Try this instead.  Using jQuery's $(this) keyword, you can target only the relevant form surrounding the clicked button.

$('.stock_details').on('click', function () {
    if($(this).parent('form').valid()) { ....


问:
Can doctrine Transaction also includes other queries run by codeigniter database library
So Doctrine is very nice so the Code Igniter is .. both are well and different things,
I am using CI+Doctrine.. but sometimes CI's active record seems to be easy for simpler queries. but now what about transactions.. can i beginTransaction() from Doctrine Connection and then comit or roll back with some CI's database queries ..

Can i do this ... means rollback will rollback every sql run by Doctrine as well as by CI ...

Thanks in Advance ...

答:
Transactions are connection-based. This means that Doctrine can have an ongoing transaction while CI fetches data from elsewhere as long they have their own connection resource to the database.

Fetching data from the database while having a transaction running isn't the way to go. You should collect the needed data before starting the transaction.

In addition, having model logic split across multiple classes seems like a clear case of code smell.

ContentLicense: CC BY-SA 2.5


问:
R not responding request to interrupt stop process
Every now and then I have to run a function that takes a lot of time and I need to interrupt the processing before it's complete. To do so, I click on the red sign of "stop" at the top of the console in Rstudio, which quite often returns this message below:

R is not responding to your request to interrupt processing so to stop the current operation you may need to terminate R entirely.

Terminating R will cause your R session to immediately abort. Active computations will be interrupted and unsaved source file changes and workspace objects will be discarded.

Do you want to terminate R now?

The problem is that I click "No" and then Rstudios seems to freeze completely. I would like to know if others face a similar issue and if there is any way to get around this.

Is there a way to stop a process in Rstudio quickly without losing the objects in the workspace?

答:
Unfortunately, RStudio is currently not able to interrupt R in a couple situations:

R is executing an external program (e.g. you cannot interrupt system("sleep 10")),

R is executing (for example) a C / C++ library call that doesn't provide R an opportunity to check for interrupts.

In such a case, the only option is to forcefully kill the R process -- hopefully this is something that could change in a future iteration of RStudio.

EDIT: RStudio v1.2 should now better handle interrupts in many of these contexts.

ContentLicense: CC BY-SA 4.0


问:
excel vba SKYPE4COMLib is not working with Skype for Business (SfB)
Is there a way to send messages via Skype for Business using excel VBA?
I tried to add  SKYPE4COMLib and following code:

```<code>Sub skype()
Dim aSkype As SKYPE4COMLib.skype
Set aSkype = New SKYPE4COMLib.skype
Dim oChat As Chat
Dim skUser As SKYPE4COMLib.user
    Set skUser = aSkype.user("user_name")
    Set oChat = aSkype.CreateChatWith(skUser.Handle)
   oChat.OpenWindow
   oChat.SendMessage "automated message"
End Sub
</code>```

But it is not working :(
Is it even possible?
Thank you very much!

答:
Please keep noted that there are two products:

Skype for Business (SfB) [former known as Lync]

Skype for Consumer (SfC)

both products can be used for chat & calls (VOIP) however they are not the same products. SfB is mostly used for companies where SfC is mostly used for consumer as you can download the client here for free and can as well use some features from SfC for free.

The Skype4com.lib is only compatible with SfC and not with SfB. This is due to the reason that Lync 2013/SfB 2015 does not expose COM entry points that Excel can use (see here). If you wish to send chats with SfB you should check UCWA 2.0.

Body:
Is there a way to send messages via Skype for Business using excel VBA?
I tried to add  SKYPE4COMLib and following code:

Sub skype()
Dim aSkype As SKYPE4COMLib.skype
Set aSkype = New SKYPE4COMLib.skype
Dim oChat As Chat
Dim skUser As SKYPE4COMLib.user
    Set skUser = aSkype.user("user_name")
    Set oChat = aSkype.CreateChatWith(skUser.Handle)
   oChat.OpenWindow
   oChat.SendMessage "automated message"
End Sub

But it is not working :(
Is it even possible?
Thank you very much!


问:
Confused by Gothon exercise game Python
From learningpythonthehardway, I've reached the text adventure game and I had a few codes that I understand what they execute, but I don't understand how. Below is the whole code I made smaller into a single .py file:

```<code>from sys import exit
from random import randint

class Scene(object):
    def enter(self):
        print "This isn't configured yet. Subclass and implement enter()"
        exit(1)

class CentralCorridor(Scene):

    def enter(self):
        print "Something."
    action = raw_input("> ")

    if action == "shoot!":
        print "Something something."

        return 'death'

class Death(Scene):

    dead = [
    "You died. That sucks ...",
    "You shouldn't have died here...that was dumb.",
    "You L00se.",
    "Even a cow's moo sounds smarter than you."
    ]

    def enter(self):
        print Death.dead[randint(0, len(self.dead)-1)]
        exit(1)

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map #sets scene_map from the a_map variable

    def play(self):
        current_scene = self.scene_map.opening_scene()#sets aMap.opening_scene() and initiates CentralCorridor
        last_scene = self.scene_map.next_scene('finished') #for the last win scene Finished()
        while current_scene != last_scene:
            next_scene_name = current_scene.enter() #if scene's not last, call enter() of current scene to next scene name
            current_scene = self.scene_map.next_scene(next_scene_name)#Set current_scene to instance of scene_map with self, next_scene_name as parameters

        current_scene.enter()

class Map(object): #initially central_corridor

    scenes = {
        'central_corridor':CentralCorridor(),
        'death':Death(),
        }

    def __init__(self, start_scene):
        self.start_scenes = start_scene #central_corridor

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name) #sets CentralCorridor() to val
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scenes) #returns val from
                                            #next_scene which is
                                            #CentralCorridor()

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
</code>```

In this code, I have a few things I don't get (bear with me.)

How does " return 'death' " under the CentralCorridor class refer to the dictionary down in Map class's scenes, and return Death class? When I type shoot! it seems to go through the Engine class and execute the current_scene.enter() but I haven't called the Engine class's play function anywhere in the CentralCorridor class.

In the Map class's opening_scene function, how exactly is
return self.next_scene(self.start_scenes) working??? I know what it does, but the self.next_scene(self.start_scenes) bit is slightly confusing me.

Thank you for anyone explaining this!

答:
To understand the code, you need to understand the last three lines of the code and what they actually do:

```<code>a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
</code>```

The object a_map is first created, which is-of class Map. Map is called with the argument central_corridor, which is a key to a dictionary that holds the value CentralCorridor(). CentralCorridor() is a class which inherits from the class Scene.

With this information, let's understand what the object a_map now actually holds. The object a_map can access everything within the class Map. The object also is directed to the class CentralCorridor and can access every method and variable there. Remember that CentralCorridor inherits from the class Scene, meaning it can also access variables and methods in Scene.

Now let's understand the object a_game. This object is an Engine class object. The Engine class, on the other hand, has the argument a_map. The a_map, as we have seen, is an object that can access various methods and variables in a number of classes as discussed above. It is now possible to access the play method in Engine, i.e. a_game.play(). Keenly this can help you understand and respond to your first questions. Just take time to understand how everything merges out and connects to each other.

On the second question, in fact, a proper understanding of the above can help you understand how everything couples up in the Engine class. return self.next_scene(self.start_scenes)holds the initial argument central_corridor. After executing the next value that is picked by the code val = Map.scenes.get(scene_name) Therefore, the code return val takes the code to the new scene, which is the class Death.

Title: Confused by Gothon exercise game Python

Body:
From learningpythonthehardway, I've reached the text adventure game and I had a few codes that I understand what they execute, but I don't understand how. Below is the whole code I made smaller into a single .py file:

from sys import exit
from random import randint

class Scene(object):
    def enter(self):
        print "This isn't configured yet. Subclass and implement enter()"
        exit(1)

class CentralCorridor(Scene):

    def enter(self):
        print "Something."
    action = raw_input("> ")

    if action == "shoot!":
        print "Something something."

        return 'death'

class Death(Scene):

    dead = [
    "You died. That sucks ...",
    "You shouldn't have died here...that was dumb.",
    "You L00se.",
    "Even a cow's moo sounds smarter than you."
    ]

    def enter(self):
        print Death.dead[randint(0, len(self.dead)-1)]
        exit(1)

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map #sets scene_map from the a_map variable

    def play(self):
        current_scene = self.scene_map.opening_scene()#sets aMap.opening_scene() and initiates CentralCorridor
        last_scene = self.scene_map.next_scene('finished') #for the last win scene Finished()
        while current_scene != last_scene:
            next_scene_name = current_scene.enter() #if scene's not last, call enter() of current scene to next scene name
            current_scene = self.scene_map.next_scene(next_scene_name)#Set current_scene to instance of scene_map with self, next_scene_name as parameters

        current_scene.enter()

class Map(object): #initially central_corridor

    scenes = {
        'central_corridor':CentralCorridor(),
        'death':Death(),
        }

    def __init__(self, start_scene):
        self.start_scenes = start_scene #central_corridor

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name) #sets CentralCorridor() to val
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scenes) #returns val from
                                            #next_scene which is
                                            #CentralCorridor()

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

In this code, I have a few things I don't get (bear with me.)

How does " return 'death' " under the CentralCorridor class refer to the dictionary down in Map class's scenes, and return Death class? When I type shoot! it seems to go through the Engine class and execute the current_scene.enter() but I haven't called the Engine class's play function anywhere in the CentralCorridor class.

In the Map class's opening_scene function, how exactly is
return self.next_scene(self.start_scenes) working??? I know what it does, but the self.next_scene(self.start_scenes) bit is slightly confusing me.

Thank you for anyone explaining this!

Body:
To understand the code, you need to understand the last three lines of the code and what they actually do:

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

The object a_map is first created, which is-of class Map. Map is called with the argument central_corridor, which is a key to a dictionary that holds the value CentralCorridor(). CentralCorridor() is a class which inherits from the class Scene.

With this information, let's understand what the object a_map now actually holds. The object a_map can access everything within the class Map. The object also is directed to the class CentralCorridor and can access every method and variable there. Remember that CentralCorridor inherits from the class Scene, meaning it can also access variables and methods in Scene.

Now let's understand the object a_game. This object is an Engine class object. The Engine class, on the other hand, has the argument a_map. The a_map, as we have seen, is an object that can access various methods and variables in a number of classes as discussed above. It is now possible to access the play method in Engine, i.e. a_game.play(). Keenly this can help you understand and respond to your first questions. Just take time to understand how everything merges out and connects to each other.

On the second question, in fact, a proper understanding of the above can help you understand how everything couples up in the Engine class. return self.next_scene(self.start_scenes)holds the initial argument central_corridor. After executing the next value that is picked by the code val = Map.scenes.get(scene_name) Therefore, the code return val takes the code to the new scene, which is the class Death.


答:
You error derives mainly from the way you put the conditions inside your loop -

```<code>if x[n] == x[0] or x[2] or x[4] or x[6]
</code>```

will check if x[n] == x[0] (which might be true even if n is not 0) or if x[2] is positive (regardless of x[n]) or if x[4] is positive and so on.

Note that the or separates between expressions, and is not used as in english, where a is b or c or d implies a is b, or a is c, or a is d, but a is b, or c is true, or d is true.

The correct way for comparing against multiple value is if n in [0, 2, 4, 6] that checks weather n is one of the values in that list.

However, for your case, where you want to filter odd and even numbers, there is no need for hard-coding numbers; just make the parity check - if x % 2 == 0 to cover all cases.

Now, lets review your specifications again:

Input n numbers.

Multiply odd indexes by 2.

Multiply even indexes by 8.

Sum it all.

Now python style:

```<code>n = 7
my_numbers = []

# Input n numbers.
for i in range(n):
    my_numbers.append(int(input("Enter the {} term: ".format(i))))

for i in range(n):
    # Mutiply even indexes by 8.
    if i % 2 == 0:
        my_numbers[i] = my_numbers[i] * 8
    # Mutiply odd indexes by 2.
    else:
        my_numbers[i] = my_numbers[i] * 2

print(sum(my_numbers)) # Sum it all.
</code>```

Title: Multiplying certain elements within an array

Body:
You error derives mainly from the way you put the conditions inside your loop -

if x[n] == x[0] or x[2] or x[4] or x[6]

will check if x[n] == x[0] (which might be true even if n is not 0) or if x[2] is positive (regardless of x[n]) or if x[4] is positive and so on.

Note that the or separates between expressions, and is not used as in english, where a is b or c or d implies a is b, or a is c, or a is d, but a is b, or c is true, or d is true.

The correct way for comparing against multiple value is if n in [0, 2, 4, 6] that checks weather n is one of the values in that list.

However, for your case, where you want to filter odd and even numbers, there is no need for hard-coding numbers; just make the parity check - if x % 2 == 0 to cover all cases.

Now, lets review your specifications again:

Input n numbers.

Multiply odd indexes by 2.

Multiply even indexes by 8.

Sum it all.

Now python style:

n = 7
my_numbers = []

# Input n numbers.
for i in range(n):
    my_numbers.append(int(input("Enter the {} term: ".format(i))))

for i in range(n):
    # Mutiply even indexes by 8.
    if i % 2 == 0:
        my_numbers[i] = my_numbers[i] * 8
    # Mutiply odd indexes by 2.
    else:
        my_numbers[i] = my_numbers[i] * 2

print(sum(my_numbers)) # Sum it all.


问:
Netbeans' RESTful Java Client : javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable
I'm developing a web service using RESTful web service of Netbeans. The service class contains following method:

```<code>@Path("jpost")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String jpost(Car c){
    return "Car:"+c.getTag()+"\t"+c.getName()+"\t"+c.getColor();
}
</code>```

For testing this method, I'm using Netbeans' RESTful Java Client to generate test method. The result is:

```<code>public String jpost(Object requestEntity) throws ClientErrorException {
        return webTarget.path("jpost").request(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
    }
</code>```

When i call jpost following error appear:

```<code>Exception in thread "main" javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:923)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:423)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:326)
    at myserver.test5.jpost(test5.java:36)
    at myserver.MyServerTest.main(MyServerTest.java:32)
</code>```

What is the problem?

答:
Your service only produces text/plain responses.

HTTP code 406 means that server cannot provide a content type acceptable by the client. So the client either specified a wrong content type in Accepts header, or did not send Accepts at all.

To specify the accepted type, request(...) argument is used.

```<code>public String jpost(Object requestEntity) throws ClientErrorException
{
    return webTarget.path("jpost")
            .request(javax.ws.rs.core.MediaType.TEXT_PLAIN)
            .post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
}
</code>```

Body:
I'm developing a web service using RESTful web service of Netbeans. The service class contains following method:

@Path("jpost")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String jpost(Car c){
    return "Car:"+c.getTag()+"\t"+c.getName()+"\t"+c.getColor();
}

For testing this method, I'm using Netbeans' RESTful Java Client to generate test method. The result is:

public String jpost(Object requestEntity) throws ClientErrorException {
        return webTarget.path("jpost").request(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
    }

When i call jpost following error appear:

Exception in thread "main" javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:923)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:423)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:326)
    at myserver.test5.jpost(test5.java:36)
    at myserver.MyServerTest.main(MyServerTest.java:32)

What is the problem?

Body:
Your service only produces text/plain responses.

HTTP code 406 means that server cannot provide a content type acceptable by the client. So the client either specified a wrong content type in Accepts header, or did not send Accepts at all.

To specify the accepted type, request(...) argument is used.

public String jpost(Object requestEntity) throws ClientErrorException
{
    return webTarget.path("jpost")
            .request(javax.ws.rs.core.MediaType.TEXT_PLAIN)
            .post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
}


问:
Centering elements in navigation header html css
I have made a navigation header (i.d.k. how you call it) and I want some text to be in the middle of it.

It basically is a black bar, with some navigation buttons on the right (e.g. Home, about us, info, gallery...) a logo on the left, and now I want some text in the middle of that bar. I can't get it to work.

This is the code I have so far.

/* Global settings */

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */

.header {
  height: 50px;
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
}

.header ul {
  height: 100%;
  float: right;
  position: relative;
  right: 50px;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
  float: left;
}

.header h1 {
  color: #FAFAFA;
  Line-height: 50px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <h1>The text I want to be centered</h1>
    <ul>
      <li>Home</li>
      <li>Info</li>
      <li>Contact</li>
      <li>About</li>
    </ul>
    <img src="" alt="Logo" />
  </div>
</body></code>```

答:
Here is a solution using Flexible Box. Flexbox does have compatibility issues in older versions of IE, but for non-dinosaur browsers it works really well. Here is a good link for learning more about it.

You may have to adjust the size of the h1 to avoid text wrapping, as well as fix some of the borders on the li.

Edit: I added flex: 1 1 0 to .flex-item which will make all of the elements the same size thereby centering the text. I removed the flex rules from the individual elements as well. This will look best on wide screens!

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

div.header {
  display: flex;
  background-color: #212121;
}

.flex-item {
  margin: auto;
  height: 50px;
  flex: 1 1 0;
}

/* Used to make 3 sections in the head*/

h1.flex-item {
  text-align: center;
  line-height: 50px;
  color: #FAFAFA;
}

ul.flex-item {
  display: flex;
}

img.flex-item {
  color: #FAFAFA;
}

/* Used to make NAV*/

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li.flex-item-li {
  width: 75px;
  text-align: center;
  line-height: 50px;
}

li.flex-item-li a {
  display: block;
  color: #FAFAFA;
  line-height: 50px;
  border: 1px solid orange;
}

li.flex-item-li:hover {
  background-color: #616161;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <img class="flex-item" src="" alt="Logo" />
    <h1 class="flex-item">Text I want to be centered</h1>
    <ul class="flex-item">
      <li class="flex-item-li">Home</li>
      <li class="flex-item-li">Info</li>
      <li class="flex-item-li">Contact</li>
      <li class="flex-item-li">About</li>
    </ul>

  </div>
</body></code>```

Body:
I have made a navigation header (i.d.k. how you call it) and I want some text to be in the middle of it.

It basically is a black bar, with some navigation buttons on the right (e.g. Home, about us, info, gallery...) a logo on the left, and now I want some text in the middle of that bar. I can't get it to work.

This is the code I have so far.

/* Global settings */

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */

.header {
  height: 50px;
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
}

.header ul {
  height: 100%;
  float: right;
  position: relative;
  right: 50px;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
  float: left;
}

.header h1 {
  color: #FAFAFA;
  Line-height: 50px;
  display: inline-block;
}

The text I want to be centered

Home

Info

Contact

About

Body:
Here is a solution using Flexible Box. Flexbox does have compatibility issues in older versions of IE, but for non-dinosaur browsers it works really well. Here is a good link for learning more about it.

You may have to adjust the size of the h1 to avoid text wrapping, as well as fix some of the borders on the li.

Edit: I added flex: 1 1 0 to .flex-item which will make all of the elements the same size thereby centering the text. I removed the flex rules from the individual elements as well. This will look best on wide screens!

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

div.header {
  display: flex;
  background-color: #212121;
}

.flex-item {
  margin: auto;
  height: 50px;
  flex: 1 1 0;
}

/* Used to make 3 sections in the head*/

h1.flex-item {
  text-align: center;
  line-height: 50px;
  color: #FAFAFA;
}

ul.flex-item {
  display: flex;
}

img.flex-item {
  color: #FAFAFA;
}

/* Used to make NAV*/

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li.flex-item-li {
  width: 75px;
  text-align: center;
  line-height: 50px;
}

li.flex-item-li a {
  display: block;
  color: #FAFAFA;
  line-height: 50px;
  border: 1px solid orange;
}

li.flex-item-li:hover {
  background-color: #616161;
}

<body>
  <div class="header">
    <img class="flex-item" src="" alt="Logo" />
    <h1 class="flex-item">Text I want to be centered</h1>
    <ul class="flex-item">
      <li class="flex-item-li"><a href="">Home</a></li>
      <li class="flex-item-li"><a href="">Info</a></li>
      <li class="flex-item-li"><a href="">Contact</a></li>
      <li class="flex-item-li"><a href="">About</a></li>
    </ul>

  </div>
</body>


答:
You need to convert the first two elements to cell arrays and then you can horizontally contatenate them and display them</p>

```<code>[num2cell(c{1}), num2cell(c{2}), c{3:end}]
</code>```

Title: How to print out a cell?

Body:
You need to convert the first two elements to cell arrays and then you can horizontally contatenate them and display them

[num2cell(c{1}), num2cell(c{2}), c{3:end}]


问:
Regex that matches a number with commas for every three digits
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

```<code>regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches
</code>```

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

```<code>regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]
</code>```

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

Body:
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

Body:
You can use

^((?:\d{1,3},(?:\d{3},)*\d{3})|(?:\d{1,3}))$

Demo and explanation


问:
FindByValue on ASP.NET DropDownList
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

```<code>public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}
</code>```

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}
</code>```

答:
Just a work around:    </p>

```<code>public long? Value
{
get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
set
{
 try
 {
    if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
    {
        ddlAggerationUnitId.SelectedValue = value.ToString();
    }
 }
 catch
 {
 ddlAggerationUnitId.SelectedIndex = -1;
 }
}
}
</code>```

Title: FindByValue on ASP.NET DropDownList

Body:
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

Body:
Just a work around:

public long? Value
{
get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
set
{
 try
 {
    if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
    {
        ddlAggerationUnitId.SelectedValue = value.ToString();
    }
 }
 catch
 {
 ddlAggerationUnitId.SelectedIndex = -1;
 }
}
}


答:
This is fairly straightforward: Use fprintf(''); instead to print/display the factors.

```<code>z=input('enter your number : ');

ans='' %the final answer string

for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
            str = [num2str(ii) '^' num2str(s) ];
        %disp(str) ;

        strcat(ans,'*',str); %concats the * str as per requirement.

        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        end
    end
end

ans=ans(2:end); % to remove the first *
fprintf(ans); % can even use the disp() function.
</code>```

So, basically, added a string to append the factors into it and display at the end, outside of the loops.

Title: formatting of prime factorization algorithm

Body:
suppose we have following script for  prime factorization

 z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end

but output of this code is not formatted well,for instance

 >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1

how can i do  so  that i got

30=2^1*3^1*5^1?

thanks in advance

Body:
This is fairly straightforward: Use fprintf(''); instead to print/display the factors.

z=input('enter your number : ');

ans='' %the final answer string

for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
            str = [num2str(ii) '^' num2str(s) ];
        %disp(str) ;

        strcat(ans,'*',str); %concats the * str as per requirement.

        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        end
    end
end

ans=ans(2:end); % to remove the first *
fprintf(ans); % can even use the disp() function.

So, basically, added a string to append the factors into it and display at the end, outside of the loops.


答:
Page_Load should be:</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
       ddlAggerationUnitId.DataTextField = "Value";
       ddlAggerationUnitId.DataValueField = "Key";
       ddlAggerationUnitId.DataBind();
    }
}
</code>```

Title: FindByValue on ASP.NET DropDownList

Body:
Page_Load should be:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
       ddlAggerationUnitId.DataTextField = "Value";
       ddlAggerationUnitId.DataValueField = "Key";
       ddlAggerationUnitId.DataBind();
    }
}


问:
My first independent C++ program. How can i improve it?
Just a simple calculator I wrote as my first piece of coding in C++, I am happy to receive constructive criticism on how to improve!<br>
I only used operations with whole numbers in hopes of just simplifying it for now!  </p>

```<code>#include <iostream>
using namespace std;

//Simple calculator that handles +,-,*,/ with whole numbers

int Add (int x, int y){
return (x+y);
}
int Sub (int x, int y){
return (x-y);
}
int Mult (int x, int y){
return (x*y);
}
int Div (int x, int y){
return (x/y);
}
int main(){
enum operation {sum, subtract, multiply, divide};
operation operationSelect;
int sel;
int a,b,c;

cout << "Which 2 numbers do you want to perform an operation on?\n";
cin >> a;
cin >> b;
cout << "Which operation do you want to perform? sum, subtract, multiply, divide (0-3)\n";
cin >> sel;
operationSelect = operation(sel);

if (operationSelect == sum){
    c = Add (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == subtract){
    c = Sub (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == multiply){
    c = Mult (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == divide){
    c = Div (a, b);
    cout << "The result is: " << c << endl;
}

return 0;
}
</code>```

答:
Just a couple of thoughts from my side:

as already pointed out proper indentation is important

imo function/method names should be verbs and therefore I would not capitalize it ie. Add -> add.

it is only possible to select exactly 1 operation, so an if-elseif-else block would make more sense, or even better a switch statement.

you should extract the line for presenting the result to the user out of the if-statements and write it only once before the return statement. Copying the same code multiple times should be avoided when possible.

Body:
Just a simple calculator I wrote as my first piece of coding in C++, I am happy to receive constructive criticism on how to improve!

I only used operations with whole numbers in hopes of just simplifying it for now!

#include <iostream>
using namespace std;

//Simple calculator that handles +,-,*,/ with whole numbers

int Add (int x, int y){
return (x+y);
}
int Sub (int x, int y){
return (x-y);
}
int Mult (int x, int y){
return (x*y);
}
int Div (int x, int y){
return (x/y);
}
int main(){
enum operation {sum, subtract, multiply, divide};
operation operationSelect;
int sel;
int a,b,c;

cout << "Which 2 numbers do you want to perform an operation on?\n";
cin >> a;
cin >> b;
cout << "Which operation do you want to perform? sum, subtract, multiply, divide (0-3)\n";
cin >> sel;
operationSelect = operation(sel);

if (operationSelect == sum){
    c = Add (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == subtract){
    c = Sub (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == multiply){
    c = Mult (a, b);
    cout << "The result is: " << c << endl;
}

if (operationSelect == divide){
    c = Div (a, b);
    cout << "The result is: " << c << endl;
}

return 0;
}


问:
Mandelbrot set in tensorflow
Where can i get the code to execute Mandlebrot set in tensorflow tutorials?
I already tried executing by pasting the code present in the website, but got an error near "import PIL.Image". Please help me</p>

答:
Sounds like you are missing the PIL library, which can easily be installed using:

```<code>$ pip install Pillow
</code>```

Also, you must run the code within a Jupyter notebook.

I don't know why they used PIL in the tutorial, I would have just used Matplotlib, which is better integrated with Jupyter. You can just copy/paste the following code in a Jupyter notebook, it should work fine:

```<code>%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# Use NumPy to create a 2D array of complex numbers on [-2,2]x[-2,2]
Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
Z = X+1j*Y

graph = tf.Graph()
with graph.as_default():
    xs = tf.constant(Z.astype("complex64"))
    zs = tf.Variable(xs)
    ns = tf.Variable(tf.zeros_like(xs, "float32"))

    init = tf.global_variables_initializer()

    # Compute the new values of z: z^2 + x
    zs_ = zs*zs + xs

    # Have we diverged with this new value?
    not_diverged = tf.abs(zs_) < 4

    # Operation to update the zs and the iteration count.
    #
    # Note: We keep computing zs after they diverge! This
    #       is very wasteful! There are better, if a little
    #       less simple, ways to do this.
    #
    step = tf.group(
      zs.assign(zs_),
      ns.assign_add(tf.cast(not_diverged, "float32"))
      )

with tf.Session(graph=graph) as sess:
    init.run()
    for i in range(100):
        step.run()
    fractal = ns.eval()

plt.figure(figsize=(13,8))
plt.imshow(fractal)
plt.axis('off')
plt.show()
</code>```

Title: Mandelbrot set in tensorflow

Body:
Sounds like you are missing the PIL library, which can easily be installed using:

$ pip install Pillow

Also, you must run the code within a Jupyter notebook.

I don't know why they used PIL in the tutorial, I would have just used Matplotlib, which is better integrated with Jupyter. You can just copy/paste the following code in a Jupyter notebook, it should work fine:

%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# Use NumPy to create a 2D array of complex numbers on [-2,2]x[-2,2]
Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
Z = X+1j*Y

graph = tf.Graph()
with graph.as_default():
    xs = tf.constant(Z.astype("complex64"))
    zs = tf.Variable(xs)
    ns = tf.Variable(tf.zeros_like(xs, "float32"))

    init = tf.global_variables_initializer()

    # Compute the new values of z: z^2 + x
    zs_ = zs*zs + xs

    # Have we diverged with this new value?
    not_diverged = tf.abs(zs_) < 4

    # Operation to update the zs and the iteration count.
    #
    # Note: We keep computing zs after they diverge! This
    #       is very wasteful! There are better, if a little
    #       less simple, ways to do this.
    #
    step = tf.group(
      zs.assign(zs_),
      ns.assign_add(tf.cast(not_diverged, "float32"))
      )

with tf.Session(graph=graph) as sess:
    init.run()
    for i in range(100):
        step.run()
    fractal = ns.eval()

plt.figure(figsize=(13,8))
plt.imshow(fractal)
plt.axis('off')
plt.show()


问:
Ruby Execution of Process-Related Shell Commands Hangs Indefinitely
In my Ruby on Rails server, whilst in Development mode, I have a need to manage running processes, such as by the pgrep command. When I attempt to execute system("pgrep MyProcess") the Rails server hangs indefinitely. I also tried the backtick version. When I use Ctrl-C, I don't get much useful information about where the process was stuck:

```<code>[1] pry(main)> `pgrep #{process}`
^CInterrupt:
from /Users/zaneclaes/.rvm/gems/ruby-2.3.0/gems/activesupport-5.0.0.1/lib/active_support/core_ext/kernel/agnostics.rb:7:in ``'
[2] pry(main)> system("pgrep #{process}")
^CInterrupt:
from (pry):2:in `system'
</code>```

I have verified that other system commands work, such as system("rm -rf #{filename}").

答: Whelp, a simple reboot of the impacted machine fixed this one. Go figure.</p>

Body:
In my Ruby on Rails server, whilst in Development mode, I have a need to manage running processes, such as by the pgrep command. When I attempt to execute system("pgrep MyProcess") the Rails server hangs indefinitely. I also tried the backtick version. When I use Ctrl-C, I don't get much useful information about where the process was stuck:

[1] pry(main)> `pgrep #{process}`
^CInterrupt:
from /Users/zaneclaes/.rvm/gems/ruby-2.3.0/gems/activesupport-5.0.0.1/lib/active_support/core_ext/kernel/agnostics.rb:7:in ``'
[2] pry(main)> system("pgrep #{process}")
^CInterrupt:
from (pry):2:in `system'

I have verified that other system commands work, such as system("rm -rf #{filename}").


问:
how to encode 27 vector3's into a 0-256 value?
I have 27 combinations of 3 values from -1 to 1 of type:

```<code> Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);
</code>```

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

```<code>  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...
</code>```

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

```<code>function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}
</code>```

答:
The most compact way is by writing a 27 digits number in  base 3 (using a shift -1 -> 0, 0 -> 1, 1 -> 2).

The value of this number will range from 0 to 3^27-1 = 7625597484987, which takes 43 bits to be encoded, i.e. 6 bytes (and 5 spare bits).

This is a little saving compared to a packed representation with 4 two-bit numbers packed in a byte (hence 7 bytes/56 bits in total).

An interesting variant is to group the base 3 digits five by five in bytes (hence numbers 0 to 242). You will still require 6 bytes (and no spare bits), but the decoding of the bytes can easily be hard-coded as a table of 243 entries.

Body:
I have 27 combinations of 3 values from -1 to 1 of type:

 Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}


问:
How to install an older version of Angular?
I need to install Angular 2 but when I'm run $ ng new myApp the version is 4. I searched a lot, but I could not find a way to install only version 2.

Does anyone know how to do it?

Edit
the command:
ng new MYAPP --ng4=false It does not work.

答:
You should use angular 4. it's in a release version now and out of beta.

Please look at the options for ng new: https://github.com/angular/angular-cli/wiki/new

If you are on angular cli version earlier that 1.0.0 please use ng new myApp --ng4=false with that --ng4=false being the default anyway.

If you are using version 1.0.0 You cannot make angular 2 the default. please look at 1.0.0 release notes. In version 1.0.0 The cli was updated to use only angular 4 with generating new project. however, you can change the angular version manually in the generated package.json to the desired version.


问:
Display number of rows on footer
I want to do a simple thing to my app.

Take a look at my main ViewController:

```<code>class Page1: UITableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Shared.instance.employees.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1

        cell.nameLabel.text = Shared.instance.employees[indexPath.row].name
        cell.positionLabel.text = Shared.instance.employees[indexPath.row].position

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? Page2,
            let indexPath = tableView.indexPathForSelectedRow {
            destination.newPage = Shared.instance.employees[indexPath.row]
        }
    }
}
</code>```

So, what function do I have to add to show the number of rows as I add more and more itens?

Differences between with and without delegates:

答:
Just implement

```<code>override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    return "Total \(Shared.instance.employees.count) rows"
}
</code>```

If you want to customize the title you have to implement tableView:viewForFooterInSection: and return a view for example:

```<code>override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 30.0))
    label.font = UIFont.boldSystemFont(ofSize: 20.0)
    label.textAlignment = .center
    label.text =  "Total \(Shared.instance.employees.count) rows"
    return label
}
</code>```

Side-note: Instead of calling Shared.instance.employees multiple times use a temporary variable:

```<code>let employee = Shared.instance.employees[indexPath.row]
cell.nameLabel.text = employee.name
cell.positionLabel.text = employee.position
</code>```

Title: Display number of rows on footer

Body:
I want to do a simple thing to my app.

Take a look at my main ViewController:

class Page1: UITableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Shared.instance.employees.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1

        cell.nameLabel.text = Shared.instance.employees[indexPath.row].name
        cell.positionLabel.text = Shared.instance.employees[indexPath.row].position

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? Page2,
            let indexPath = tableView.indexPathForSelectedRow {
            destination.newPage = Shared.instance.employees[indexPath.row]
        }
    }
}

So, what function do I have to add to show the number of rows as I add more and more itens?

Differences between with and without delegates:

Body:
Just implement

override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    return "Total \(Shared.instance.employees.count) rows"
}

If you want to customize the title you have to implement tableView:viewForFooterInSection: and return a view for example:

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 30.0))
    label.font = UIFont.boldSystemFont(ofSize: 20.0)
    label.textAlignment = .center
    label.text =  "Total \(Shared.instance.employees.count) rows"
    return label
}

Side-note: Instead of calling Shared.instance.employees multiple times use a temporary variable:

let employee = Shared.instance.employees[indexPath.row]
cell.nameLabel.text = employee.name
cell.positionLabel.text = employee.position


问:
Count All Pictures on Android Tablet
I am trying to programmatically get the number of images (videos and pictures) in the gallery of my Android Tablet.  It is an SM-T580 if that matters.  I was able to get it to work with android phones, but can not get it to work with the tablet.  It must throw an exception because the application bombs out, but it gives no meaningful information, even when I stacktrace.  I am not sure what is going on here.  I will include my code that works on phones, but bombs on the tablet.  Any help is much appreciated.

Method to get all pictures in the gallery:

```<code>public int findAnyPictures(){
    int count = 0;
    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    //Stores all the images from the gallery in Cursor
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    //Total number of images
    if (cursor != null){
        count = cursor.getCount();
    }
    cursor.close();
    return count;
}
</code>```

Here is the method that counts all videos

```<code> public int findAnyVideos() {
        int vidsCount = 0;
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] projection = { MediaStore.Video.VideoColumns.DATA };
        Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            vidsCount = cursor.getCount();
            cursor.close();
        }
        return vidsCount;
    }
</code>```

It seems to throw a runtime exception when find any pictures is called, I am not sure why it is telling me I do not have the proper permissions.  I have included the permission it mentions in the android manifest and I have no idea what grantUriPermission() is?  Here is the stack trace

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thopfer.resetverify/com.example.thopfer.resetverify.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=22228, uid=10126 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3305)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7303)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=22228, uid=10126 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                                at android.os.Parcel.readException(Parcel.java:1620)
                                                                                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                                                                                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
                                                                                at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                                                                                at android.content.ContentResolver.query(ContentResolver.java:502)
                                                                                at android.content.ContentResolver.query(ContentResolver.java:445)
                                                                                at com.example.thopfer.resetverify.MainActivity.findAnyPictures(MainActivity.java:234)
                                                                                at com.example.thopfer.resetverify.MainActivity.onCreate(MainActivity.java:185)
                                                                                at android.app.Activity.performCreate(Activity.java:6904)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7303)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

答:
Well this tells you the problem

```<code>requires android.permission.READ_EXTERNAL_STORAGE
</code>```

You have to request permission at runtime for Android API 23+ (Android 6.0+). More on this here: https://developer.android.com/training/permissions/requesting.html

```<code>if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_CODE);
}
</code>```

You will get the answer in onRequestPermissionsResult.

Title: Count All Pictures on Android Tablet

Body:
I am trying to programmatically get the number of images (videos and pictures) in the gallery of my Android Tablet.  It is an SM-T580 if that matters.  I was able to get it to work with android phones, but can not get it to work with the tablet.  It must throw an exception because the application bombs out, but it gives no meaningful information, even when I stacktrace.  I am not sure what is going on here.  I will include my code that works on phones, but bombs on the tablet.  Any help is much appreciated.

Method to get all pictures in the gallery:

public int findAnyPictures(){
    int count = 0;
    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    //Stores all the images from the gallery in Cursor
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    //Total number of images
    if (cursor != null){
        count = cursor.getCount();
    }
    cursor.close();
    return count;
}

Here is the method that counts all videos

 public int findAnyVideos() {
        int vidsCount = 0;
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] projection = { MediaStore.Video.VideoColumns.DATA };
        Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            vidsCount = cursor.getCount();
            cursor.close();
        }
        return vidsCount;
    }

It seems to throw a runtime exception when find any pictures is called, I am not sure why it is telling me I do not have the proper permissions.  I have included the permission it mentions in the android manifest and I have no idea what grantUriPermission() is?  Here is the stack trace

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thopfer.resetverify/com.example.thopfer.resetverify.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=22228, uid=10126 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3305)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7303)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=22228, uid=10126 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                                at android.os.Parcel.readException(Parcel.java:1620)
                                                                                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                                                                                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
                                                                                at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                                                                                at android.content.ContentResolver.query(ContentResolver.java:502)
                                                                                at android.content.ContentResolver.query(ContentResolver.java:445)
                                                                                at com.example.thopfer.resetverify.MainActivity.findAnyPictures(MainActivity.java:234)
                                                                                at com.example.thopfer.resetverify.MainActivity.onCreate(MainActivity.java:185)
                                                                                at android.app.Activity.performCreate(Activity.java:6904)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3401)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7303)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
Well this tells you the problem

requires android.permission.READ_EXTERNAL_STORAGE

You have to request permission at runtime for Android API 23+ (Android 6.0+). More on this here: https://developer.android.com/training/permissions/requesting.html

if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_CODE);
}

You will get the answer in onRequestPermissionsResult.


问:
R: copying data from columns in one dataframe to another based on some conditions
Here are my datasets:

df1:

HT    AT    HHAI    HAAI   HHGC    HAGC

AS      Ar    0.3      0.5    0.8    0.9

and so on.

I'm doing this in R.

df2:

HT AT HHAI HAAI HHGC HAGC

BS FS NA NA NA NA

and so on.

I want to copy values of HHAI, HAAI, HHGC, HAGC from df1 into same columns of df2 when:

df1.HT==df2.HT and df1.AT==df2.AT

df1 and df2 are large dataframes.

I'm very new to R. Don't know about much methods and all.

Please post the code here as I don't have much knowledge about R.

Thanks in advance.

答:
Solution:</p>

```<code>merge(df1, df2, by = c("column_name", "column_name2"), all.x = TRUE, all.y = FALSE)
</code>```

Body:
Solution:

merge(df1, df2, by = c("column_name", "column_name2"), all.x = TRUE, all.y = FALSE)


问:
Check record exists db - error show
How do I check if username or email exists and then put a error message in my error array. Right now i have:

```<code>$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}
</code>```

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?

答: You can fetch one row and see if you got same email that you search or same username or both. You can do LIMIT 0,1 if you can stop after finding first row matching either this or that.</p>

Title: Check record exists db - error show

Body:
How do I check if username or email exists and then put a error message in my error array. Right now i have:

$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?


问:
How many Non access modifiers are there in Java?
Can anyone tell how many Non-access Modifiers there are in Java? I have the list below, but I want to know if it is complete or if there's any other I need to add: </p>

```<code>final,
abstract,
static,
strictfp,
native,
synchronized,
transient
</code>```

答:
I don't think Michael Bar-Sinai's answer is correct.

The Modifier class shows a total of 12 modifiers, and this page of the Java Documentation shows that there are 3 access modifiers (and a 4th nameless package-private modifier).
It follows that the 9 non-access modifiers are:

abstract

final

interface

native

static

strictfp

synchronized

transient

volatile

Body:
Can anyone tell how many Non-access Modifiers there are in Java? I have the list below, but I want to know if it is complete or if there's any other I need to add:

final,
abstract,
static,
strictfp,
native,
synchronized,
transient