问:
Arduino : avrdude: stk500_recv(): programmer is not responding
I'm currently trying to make Controlling an RGB LED With an Android Smartphone Using Arduino and Bluetooth Module. As in below link tutorial.

http://www.instructables.com/id/Controlling-an-RGB-LED-With-an-Android-Smartphone-/

I'm using Arduino Uno.
I made as in tutorial and code and upload to Arduino then It's Show as below Error Messages and cannot upload to Arduino.

```<code>avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/Applications/Arduino.app/
     Contents/Java/hardware/tools/avr/etc/avrdude.conf"

     User configuration file is "/Users/kyawzinwai/.avrduderc"
     User configuration file does not exist or is not a regular file,
     skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 1 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 2 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 3 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 4 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 5 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 6 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 7 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 8 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 9 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 10 of 10: not in sync:
     resp=0x00

     avrdude done.  Thank you.

     Problem uploading to board.  See
     http://www.arduino.cc/en/Guide/Troubleshooting#upload for
     suggestions.
</code>```

答:
This problem can have various reasons, please refer the link below

https://arduino.stackexchange.com/questions/17/avrdude-stk500-getsync-not-in-sync-resp-0x00-aka-some-dude-named-avr-won

If you are a mac user, please see this link
Mac + Uno + avrdude: stk500_recv(): programmer is not responding

Body:
I'm currently trying to make Controlling an RGB LED With an Android Smartphone Using Arduino and Bluetooth Module. As in below link tutorial.

http://www.instructables.com/id/Controlling-an-RGB-LED-With-an-Android-Smartphone-/

I'm using Arduino Uno.
I made as in tutorial and code and upload to Arduino then It's Show as below Error Messages and cannot upload to Arduino.

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/Applications/Arduino.app/
     Contents/Java/hardware/tools/avr/etc/avrdude.conf"

     User configuration file is "/Users/kyawzinwai/.avrduderc"
     User configuration file does not exist or is not a regular file,
     skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 1 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 2 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 3 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 4 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 5 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 6 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 7 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 8 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 9 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 10 of 10: not in sync:
     resp=0x00

     avrdude done.  Thank you.

     Problem uploading to board.  See
     http://www.arduino.cc/en/Guide/Troubleshooting#upload for
     suggestions.


来源: stackexchange

问:
I want to pass a list of SqlParameter to a function which executes stored procedure in C#
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

```<code>public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}
</code>```

But I want to pass these two variable as a single List<SqlParameter> variable as

```<code>List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));
</code>```

Thus the declaration of above function changes from

```<code>public void save1()
</code>```

to

```<code>public void save1(List<SqlParameter> param)
</code>```

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.

答:
You can use a for loop to access each individual parameter inside the list.

for(interesting i=0, i< parameter.Count, i++){
   //
    var param1 = param[i];
}

ContentLicense: CC BY-SA 3.0

Body:
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}

But I want to pass these two variable as a single List<SqlParameter> variable as

List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));

Thus the declaration of above function changes from

public void save1()

to

public void save1(List<SqlParameter> param)

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.


问:
Need assistance with Xcode/database in Mac OS
I am new to Mac OS and I am unable to understand whether I have any database installed in my system or not. As far as my knowledge is concerned about Mac OS, I am not able to see any database under Applications/Utilities or Applications/Developer.

Can anyone help me choose a basic database I can install in Mac OS? My intent is to learn to connect a DB with the Native app which I am trying to create.

It would be helpful if you could provide me with some useful links for installation and connecting the DB.

答:
I think you could have a look at MAMP to get a quick setup.

I know it's not perfect, but it contains stuff for administrating, as well as a default install of a MySQL DB.

On the other hand, if you feel adventurous (not a big deal):

You can try MySQL as a standalone package.

My advice would be to use MySQL Workbench as well; it's a very good GUI tool for MySQL administration.

However, you should take some SQL training beforehand. It'll give you a clear view of what can and can not be done with it, and help you avoid some common mistakes.

Wikipedia is a good start for that to give you an idea.

ContentLicense: CC BY-SA 2.5


问:
Comparing keys in HashMap and Values
I have a HashMap as follows-

```<code>HashMap<String, Integer> BC = new HashMap<String, Integer>();
</code>```

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

```<code>"the/at" 153
"that/cs" 45
"Ann/np" 3
</code>```

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

```<code>"the/at" 153
"the/det" 80
</code>```

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

```<code>private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }
</code>```

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

答:
A basic thought on the algorithm:

You should get the entrySet() of the HashMap and convert it to a List:

```<code>ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
</code>```

Now you should sort the list by the keys in alphabetical order. We do that because the HashMap has no order, so you can expect that the corresponding keys might be far apart. But by sorting them, all related keys are directly next to each other.

```<code>Collections.sort(list, Comparator.comparing(e -> e.getKey()));
</code>```

The entries "the/at" and "the/det" will be next to each other, thanks to sorting alphabetically.

Now you can iterate over the entire list while remembering the best item, until you find a better one or you find the first item which has not the same prefix (e.g. "the").

```<code>ArrayList<Map.Entry<String, Integer>> bestList = new ArrayList<>();
// The first entry of the list is considered the currently best item for it's group
Map.Entry<String, Integer> currentBest = best.get(0);
String key = currentBest.getKey();
String currentPrefix = key.substring(0, key.indexOf('/'));

for (int i=1; i<list.size(); i++) {
    // The item we compare the current best with
    Map.Entry<String, Integer> next = list.get(i);
    String nkey = next.getKey();
    String nextPrefix = nkey.substring(0, nkey.indexOf('/'));

    // If both items have the same prefix, then we want to keep the best one
    // as the current best item
    if (currentPrefix.equals(nextPrefix)) {
        if (currentBest.getValue() < next.getValue()) {
            currentBest = next;
        }

    // If the prefix is different we add the current best to the best list and
    // consider the current item the best one for the next group
    } else {
        bestList.add(currentBest);
        currentBest = next;
        currentPrefix = nextPrefix;
    }
}
// The last one must be added here, or we would forget it
bestList.add(currentBest);
</code>```

Now you should have a list of Map.Entry objects representing the desired entries. The complexity should be n(log n) and is limited by the sorting algorithm, while grouping/collection the items has a complexity of n.

Title: Comparing keys in HashMap and Values

Body:
I have a HashMap as follows-

HashMap<String, Integer> BC = new HashMap<String, Integer>();

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

"the/at" 153
"that/cs" 45
"Ann/np" 3

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

"the/at" 153
"the/det" 80

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

Body:
A basic thought on the algorithm:

You should get the entrySet() of the HashMap and convert it to a List:

ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());

Now you should sort the list by the keys in alphabetical order. We do that because the HashMap has no order, so you can expect that the corresponding keys might be far apart. But by sorting them, all related keys are directly next to each other.

Collections.sort(list, Comparator.comparing(e -> e.getKey()));

The entries "the/at" and "the/det" will be next to each other, thanks to sorting alphabetically.

Now you can iterate over the entire list while remembering the best item, until you find a better one or you find the first item which has not the same prefix (e.g. "the").

ArrayList<Map.Entry<String, Integer>> bestList = new ArrayList<>();
// The first entry of the list is considered the currently best item for it's group
Map.Entry<String, Integer> currentBest = best.get(0);
String key = currentBest.getKey();
String currentPrefix = key.substring(0, key.indexOf('/'));

for (int i=1; i<list.size(); i++) {
    // The item we compare the current best with
    Map.Entry<String, Integer> next = list.get(i);
    String nkey = next.getKey();
    String nextPrefix = nkey.substring(0, nkey.indexOf('/'));

    // If both items have the same prefix, then we want to keep the best one
    // as the current best item
    if (currentPrefix.equals(nextPrefix)) {
        if (currentBest.getValue() < next.getValue()) {
            currentBest = next;
        }

    // If the prefix is different we add the current best to the best list and
    // consider the current item the best one for the next group
    } else {
        bestList.add(currentBest);
        currentBest = next;
        currentPrefix = nextPrefix;
    }
}
// The last one must be added here, or we would forget it
bestList.add(currentBest);

Now you should have a list of Map.Entry objects representing the desired entries. The complexity should be n(log n) and is limited by the sorting algorithm, while grouping/collection the items has a complexity of n.


问:
Count based on inner select
I want to do a count based on a sub select statement.

```<code>SELECT MONTH(Received), State, COUNT('id'), SUM(price) FROM Leads GROUP BY MONTH(Received), State
</code>```

That query works and generates something like this

```<code>MONTH(Received)     State   COUNT('id')    SUM(price)
4                   CA      25             35
4                   UT      13             8
</code>```

What I'm trying to count is how many rows had a price > 0

This is the query I tried

```<code>SELECT MONTH(Received), SUM(price), COUNT(`id`), (SELECT COUNT(*) as count FROM Leads WHERE Price > 0) as NumPaidLeads, State FROM Leads GROUP BY MONTH(Received), State
</code>```

But NumPaidLeads Counts the entire column, the price column is numeric type.

What am I doing wrong?

答:
You forgot to include state in the where-clause of your sub-select.
The case-solution in the other post may be faster, though.

```<code>SELECT MONTH(Received), SUM(price), COUNT(`id`),
 (SELECT COUNT(*) as count FROM Leads as L1 WHERE Price > 0
  and L1.State=L2.State) as NumPaidLeads,
 State FROM Leads as L2 GROUP BY MONTH(Received), State
</code>```

Title: Count based on inner select

Body:
I want to do a count based on a sub select statement.

SELECT MONTH(Received), State, COUNT('id'), SUM(price) FROM Leads GROUP BY MONTH(Received), State

That query works and generates something like this

MONTH(Received)     State   COUNT('id')    SUM(price)
4                   CA      25             35
4                   UT      13             8

What I'm trying to count is how many rows had a price > 0

This is the query I tried

SELECT MONTH(Received), SUM(price), COUNT(`id`), (SELECT COUNT(*) as count FROM Leads WHERE Price > 0) as NumPaidLeads, State FROM Leads GROUP BY MONTH(Received), State

But NumPaidLeads Counts the entire column, the price column is numeric type.

What am I doing wrong?

Body:
You forgot to include state in the where-clause of your sub-select.
The case-solution in the other post may be faster, though.

SELECT MONTH(Received), SUM(price), COUNT(`id`),
 (SELECT COUNT(*) as count FROM Leads as L1 WHERE Price > 0
  and L1.State=L2.State) as NumPaidLeads,
 State FROM Leads as L2 GROUP BY MONTH(Received), State


问:
Visual Studio C# Project-to-project Reference
I have two .NET Framework libraries in the same solution. If I set project A as a dependency of project B is there a way to get it to copy over the dll when I build the solution?

Thanks,

答:
I found an answer (which I think is mentioned in many other areas but cryptically).

The following must be done in addition to declaring a project dependency.

In the Reference Manager (Solution>References>Add Reference) you can select a project from your solution and reference that directly. It will handle all of the updating of the library.


问:
Cardinality constraints in MiniZinc
The MiniZinc constraint solver allows to express cardinality constraints very easily using the built-in sum() function:

```<code>%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_sum(array[int] of var bool: x) =
    (sum(x) == 2);
</code>```

The cardinality constraint is met, if and only if the number if true elements in the array of Boolean variables is as specified. Booleans are automatically mapped to integer values 0 and 1 to compute the sum.

I implemented my own cardinality constraint predicate as set of counter slices:

```<code>%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_serial(array[int] of var bool: x) =
    let
    {
      int: lb = min(index_set(x));
      int: ub = max(index_set(x));
      int: len = length(x);
    }
    in
    if len < 2 then
      false
    else if len == 2 then
      x[lb] /\ x[ub]
    else
      (
        let
        {
          %  1-of-3 counter is modelled as a set of slices
          %  with 3 outputs each
          array[lb+1..ub-1] of var bool: t0;
          array[lb+1..ub-1] of var bool: t1;
          array[lb+1..ub-1] of var bool: t2;
        }
        in
        %  first two slices are hard-coded
        (t0[lb+1] == not(x[lb] \/ x[lb+1])) /\
        (t1[lb+1] == (x[lb] != x[lb+1])) /\
        (t2[lb+1] == (x[lb] /\ x[lb+1])) /\
        %   remaining slices are regular
        forall(i in lb+2..ub-1)
        (
          (t0[i] == t0[i-1] /\ not x[i]) /\
          (t1[i] == (t0[i-1] /\ x[i]) \/ (t1[i-1] /\ not x[i])) /\
          (t2[i] == (t1[i-1] /\ x[i]) \/ (t2[i-1] /\ not x[i]))
        ) /\
        %  output 2 of final slice must be true to fulfil predicate
        ((t1[ub-1] /\ x[ub]) \/ (t2[ub-1] /\ not x[ub]))
      )
    endif endif;
</code>```

This implementation is using a parallel encoding with fewer lines/variables between the slices:

```<code>%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_parallel(array[int] of var bool: x) =
    let
    {
      int: lb = min(index_set(x));
      int: ub = max(index_set(x));
      int: len = length(x);
    }
    in
    if len < 2 then
      false
    else if len == 2 then
      x[lb] /\ x[ub]
    else
      (
        let
        {
          %  counter is modelled as a set of slices
          %  with 2 outputs each
          %  Encoding:
          %  0 0 : 0 x true
          %  0 1 : 1 x true
          %  1 0 : 2 x true
          %  1 1 : more than 2 x true
          array[lb+1..ub] of var bool: t0;
          array[lb+1..ub] of var bool: t1;
        }
        in
        %  first two slices are hard-coded
        (t1[lb+1] == (x[lb] /\ x[lb+1])) /\
        (t0[lb+1] == not t1[lb+1]) /\
        %   remaining slices are regular
        forall(i in lb+2..ub)
        (
          (t0[i] == (t0[i-1] != x[i]) \/ (t0[i-1] /\ t1[i-1])) /\
          (t1[i] == t1[i-1] \/ (t0[i-1] /\ x[i]))
        ) /\
        %  output of final slice must be  1 0 to fulfil predicate
        (t1[ub] /\ not t0[ub])
      )
    endif endif;
</code>```

Question:

Does it make sense to use home-grown cardinality predicates? Or is the MiniZinc implementation of sum() beyond all doubts in terms of solution speed?

Update:

I am using Gecode as solver back-end.

答:
Linear sums is typically one of the most significant constraints to implement well in a constraint solver, so for your case the initial version using a simple sum is much better. In particular, the propagator in Gecode that implements the Boolean sum is heavily optimized to be as efficient as possible.

As a general rule, it is typically a good idea to use the constraints that are available. In particular, if what one is doing maps well to a global constraint that is typically a good idea. A related example would be if you want to count the occurrences of several different numbers in an array of integers, in which case the global cardinality constraint is very useful.

For completeness: When using lazy clause generation solvers (Chuffed for example), (novel) decompositions may sometimes be surprisingly useful. But that is a much more advanced topic.

Title: Cardinality constraints in MiniZinc

Body:
The MiniZinc constraint solver allows to express cardinality constraints very easily using the built-in sum() function:

%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_sum(array[int] of var bool: x) =
    (sum(x) == 2);

The cardinality constraint is met, if and only if the number if true elements in the array of Boolean variables is as specified. Booleans are automatically mapped to integer values 0 and 1 to compute the sum.

I implemented my own cardinality constraint predicate as set of counter slices:

%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_serial(array[int] of var bool: x) =
    let
    {
      int: lb = min(index_set(x));
      int: ub = max(index_set(x));
      int: len = length(x);
    }
    in
    if len < 2 then
      false
    else if len == 2 then
      x[lb] /\ x[ub]
    else
      (
        let
        {
          %  1-of-3 counter is modelled as a set of slices
          %  with 3 outputs each
          array[lb+1..ub-1] of var bool: t0;
          array[lb+1..ub-1] of var bool: t1;
          array[lb+1..ub-1] of var bool: t2;
        }
        in
        %  first two slices are hard-coded
        (t0[lb+1] == not(x[lb] \/ x[lb+1])) /\
        (t1[lb+1] == (x[lb] != x[lb+1])) /\
        (t2[lb+1] == (x[lb] /\ x[lb+1])) /\
        %   remaining slices are regular
        forall(i in lb+2..ub-1)
        (
          (t0[i] == t0[i-1] /\ not x[i]) /\
          (t1[i] == (t0[i-1] /\ x[i]) \/ (t1[i-1] /\ not x[i])) /\
          (t2[i] == (t1[i-1] /\ x[i]) \/ (t2[i-1] /\ not x[i]))
        ) /\
        %  output 2 of final slice must be true to fulfil predicate
        ((t1[ub-1] /\ x[ub]) \/ (t2[ub-1] /\ not x[ub]))
      )
    endif endif;

This implementation is using a parallel encoding with fewer lines/variables between the slices:

%  This predicate is true, iff 2 of the array
%  elements are true
predicate exactly_two_parallel(array[int] of var bool: x) =
    let
    {
      int: lb = min(index_set(x));
      int: ub = max(index_set(x));
      int: len = length(x);
    }
    in
    if len < 2 then
      false
    else if len == 2 then
      x[lb] /\ x[ub]
    else
      (
        let
        {
          %  counter is modelled as a set of slices
          %  with 2 outputs each
          %  Encoding:
          %  0 0 : 0 x true
          %  0 1 : 1 x true
          %  1 0 : 2 x true
          %  1 1 : more than 2 x true
          array[lb+1..ub] of var bool: t0;
          array[lb+1..ub] of var bool: t1;
        }
        in
        %  first two slices are hard-coded
        (t1[lb+1] == (x[lb] /\ x[lb+1])) /\
        (t0[lb+1] == not t1[lb+1]) /\
        %   remaining slices are regular
        forall(i in lb+2..ub)
        (
          (t0[i] == (t0[i-1] != x[i]) \/ (t0[i-1] /\ t1[i-1])) /\
          (t1[i] == t1[i-1] \/ (t0[i-1] /\ x[i]))
        ) /\
        %  output of final slice must be  1 0 to fulfil predicate
        (t1[ub] /\ not t0[ub])
      )
    endif endif;

Question:

Does it make sense to use home-grown cardinality predicates? Or is the MiniZinc implementation of sum() beyond all doubts in terms of solution speed?

Update:

I am using Gecode as solver back-end.

ContentLicense: CC BY-SA 4.0


问:
R Markdown Table Sizing Inconsistent
When I output my R Markdown (knitr / RStudio) to html the following table stretches the full width of the browser you view it in. It's only two columns and looks rather odd stretched out on a widescreen display.

```<code>Col1 | Col2
--- | ---
1 | 1
1349 | 143910
</code>```

This same table shown below, same syntax, correctly limits the width of Column 1 to the width of its own contents. The only difference is the cell contents of position [2, 2] are extremely long.

```<code>Col1 | Col2
--- | ---
1 | 1
1349 | 143910143910143910143910143910143910143910143910143910
</code>```

How do I force knitr or pandoc or R or whatever to limit column width to only slightly larger than the columns contents. Why did the extreme number of characters in cell [2, 2] force my output to behave as I wish? I didn't involve any CSS in the second table and prefer not to mess around with CSS.

答:
I suggest you use kable from the knitr package and kable_styling from the kableExtra package.

Supposing your dataframe is df

```<code>kable(df, "html") %>%
  kable_styling(full_width = F)
</code>```

You can find more info here.

https://www.rdocumentation.org/packages/kableExtra/versions/0.6.1/topics/kable_styling

EDIT: eipi10´S clarifications on packages. (Thanks!)

Title: R Markdown Table Sizing Inconsistent

Body:
When I output my R Markdown (knitr / RStudio) to html the following table stretches the full width of the browser you view it in. It's only two columns and looks rather odd stretched out on a widescreen display.

Col1 | Col2
--- | ---
1 | 1
1349 | 143910

This same table shown below, same syntax, correctly limits the width of Column 1 to the width of its own contents. The only difference is the cell contents of position [2, 2] are extremely long.

Col1 | Col2
--- | ---
1 | 1
1349 | 143910143910143910143910143910143910143910143910143910

How do I force knitr or pandoc or R or whatever to limit column width to only slightly larger than the columns contents. Why did the extreme number of characters in cell [2, 2] force my output to behave as I wish? I didn't involve any CSS in the second table and prefer not to mess around with CSS.

Body:
I suggest you use kable from the knitr package and kable_styling from the kableExtra package.

Supposing your dataframe is df

kable(df, "html") %>%
  kable_styling(full_width = F)

You can find more info here.

https://www.rdocumentation.org/packages/kableExtra/versions/0.6.1/topics/kable_styling

EDIT: eipi10´S clarifications on packages. (Thanks!)


问:
Swift Mapbox custom user location annotation(Fatal Error)
I would like to create a custom user location pin which it gets the photoURL from Firebase and displays it. I tried using this Swift 3 - Mapbox - Customize User Location Annotation as a reference. However, I get an error when I build the custom class. I am not sure can I edit much in the MGLUserLocationAnnotationView but it seems like inherit UIView so I think it should be fine. Also, should I get the data from Firebase in the View Class or in the View Controller?

It is my custom class

```<code>class CustomUserLocationDisplayView: MGLUserLocationAnnotationView {

  var view: UIView!

  @IBOutlet weak var displayView: UIImageView!
  var imageView: UIImageView!

  required override init(reuseIdentifier: String?) {
    super.init(reuseIdentifier: reuseIdentifier)
    setup()
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("Error")         <--------- I get this FATAL Error
  }

  func readFirebaseUserProfile(){
    let user = Auth.auth().currentUser
    let photoURL = user?.photoURL
      displayView.kf.setImage(with: photoURL)
  }

  func setup() {
    view = loadViewFromNib()
    displayView.layer.cornerRadius = 30
    addSubview(view)
  }

  func loadViewFromNib() -> UIView {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "CustomUserLocationDisplayView", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

    return view
  }
}
</code>```

It is my function for annotation

```<code>func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    if annotation is MGLPointAnnotation{

    }else{
        var userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "user") as? CustomUserLocationDisplayView

        if userLocationAnnotationView == nil {
          userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

        }

        return userLocationAnnotationView
      }
  }
</code>```

答:
One possible issue: I don't see where you call readFirebaseUserProfile. I would double check that it is being called.

Also, could you put a breakpoint after if userLocationAnnotationView == nil { and see if you are reaching it? You could also try something like:

```<code> if annotation is MGLUserLocation && mapView.userLocation != nil {
    userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

    return userLocationAnnotationView
 } else if annotation is MGLPointAnnotation {
    // Set annotations here
 }
 return nil
</code>```

Body:
I would like to create a custom user location pin which it gets the photoURL from Firebase and displays it. I tried using this Swift 3 - Mapbox - Customize User Location Annotation as a reference. However, I get an error when I build the custom class. I am not sure can I edit much in the MGLUserLocationAnnotationView but it seems like inherit UIView so I think it should be fine. Also, should I get the data from Firebase in the View Class or in the View Controller?

It is my custom class

class CustomUserLocationDisplayView: MGLUserLocationAnnotationView {

  var view: UIView!

  @IBOutlet weak var displayView: UIImageView!
  var imageView: UIImageView!

  required override init(reuseIdentifier: String?) {
    super.init(reuseIdentifier: reuseIdentifier)
    setup()
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("Error")         <--------- I get this FATAL Error
  }

  func readFirebaseUserProfile(){
    let user = Auth.auth().currentUser
    let photoURL = user?.photoURL
      displayView.kf.setImage(with: photoURL)
  }

  func setup() {
    view = loadViewFromNib()
    displayView.layer.cornerRadius = 30
    addSubview(view)
  }

  func loadViewFromNib() -> UIView {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "CustomUserLocationDisplayView", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

    return view
  }
}

It is my function for annotation

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    if annotation is MGLPointAnnotation{

    }else{
        var userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "user") as? CustomUserLocationDisplayView

        if userLocationAnnotationView == nil {
          userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

        }

        return userLocationAnnotationView
      }
  }

Body:
One possible issue: I don't see where you call readFirebaseUserProfile. I would double check that it is being called.

Also, could you put a breakpoint after if userLocationAnnotationView == nil { and see if you are reaching it? You could also try something like:

 if annotation is MGLUserLocation && mapView.userLocation != nil {
    userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

    return userLocationAnnotationView
 } else if annotation is MGLPointAnnotation {
    // Set annotations here
 }
 return nil


问:
How to Use Sabre EnhancedSeatMap v5.0.0 Service as .Net Web Reference
After using the old v2.0.0 we decided to upgrade the Sabre SOAP EnhancedSeatMap to v5.0.0. We use it as Web Reference (not service reference) to our C# .NET 4.5 project. When instancing the new upgraded service with:

```<code>var x = new EnhancedSeatMapService();
</code>```

Exception:

```<code>Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]'
</code>```

On the Sabre API Documentation there is explicit statement that this version supports .net:

Please help

答:
This is actually because a .NET bug that takes a sequence with a maxOccurs="1000" and instead of understanding it as 1000 limit, or simply as an array, .NET creates an array of arrays.

```<code><xsd:complexType name="AmenityTable">
    <xsd:sequence>
        <xsd:element name="AmenityDetail" maxOccurs="1000" minOccurs="0" type="imap-0400:Amenity_Detail">
</code>```

Here is the double array:

```<code>[System.Xml.Serialization.XmlArrayItemAttribute("AmenityDetail", typeof(Amenity_Detail), IsNullable=false)]
public Amenity_Detail[][] AmenityTable {
    get {
        return this.amenityTableField;
    }
    set {
        this.amenityTableField = value;
    }
}
</code>```

You can simply download the WSDL with all the schemas and remove the maxOccurs="1000" from both imap-0400:Amenity_Detail and imap-0400:Price_AndTaxDescription_Detail

If not, you can use my modified version: https://files.fm/f/guzxxkkn

Body:
After using the old v2.0.0 we decided to upgrade the Sabre SOAP EnhancedSeatMap to v5.0.0. We use it as Web Reference (not service reference) to our C# .NET 4.5 project. When instancing the new upgraded service with:

var x = new EnhancedSeatMapService();

Exception:

Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail'

error CS0030: Cannot convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Amenity_Detail[]'

error CS0029: Cannot implicitly convert type 'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail' to
'ServiceSupplier_Sabre.EnhancedSeatMapRQ.Price_AndTaxDescription_Detail[]'

On the Sabre API Documentation there is explicit statement that this version supports .net:

Please help

Body:
This is actually because a .NET bug that takes a sequence with a maxOccurs="1000" and instead of understanding it as 1000 limit, or simply as an array, .NET creates an array of arrays.

<xsd:complexType name="AmenityTable">
    <xsd:sequence>
        <xsd:element name="AmenityDetail" maxOccurs="1000" minOccurs="0" type="imap-0400:Amenity_Detail">

Here is the double array:

[System.Xml.Serialization.XmlArrayItemAttribute("AmenityDetail", typeof(Amenity_Detail), IsNullable=false)]
public Amenity_Detail[][] AmenityTable {
    get {
        return this.amenityTableField;
    }
    set {
        this.amenityTableField = value;
    }
}

You can simply download the WSDL with all the schemas and remove the maxOccurs="1000" from both imap-0400:Amenity_Detail and imap-0400:Price_AndTaxDescription_Detail

If not, you can use my modified version: https://files.fm/f/guzxxkkn


问:
multidex error on android studio 3
Before upgrading to AS 3, I used multidex in my project just fine, after upgrading It started getting this error each time i try to run the app on a device or even generate an APK

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp;
  Error:com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp; Error:  at
  com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
  Error:    at
  com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
  Error:    at
  com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
  Error:    at
  com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
  Error:    at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
  Error:    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
  Error:    at
  java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
  Error:    at
  java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
  Error:    at
  java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
  Error:    at
  java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Please not that all i did was update AS and gradle plguin to 3.0.0. I tried going back to 2.3.3, but It tells me the project is incompatible.

Here is my Multidex code:

```<code>android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "net.mohammed.billmob"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
</code>```

and my application class:

```<code>public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}
</code>```

and these are the app dependencies:

```<code>dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:mediarouter-v7:26.1.0'

   // compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-perf:11.6.0'

    compile 'com.karumi:dexter:4.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.facebook.android:facebook-android-sdk:4.28.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    compile 'com.android.support:support-v4:26.1.0'

    compile 'com.android.support:multidex:1.0.1'
/*    compile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex-instrumentation:1.0.2'*/

    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0'
    testCompile 'junit:junit:4.12'
}
</code>```

答: Sol i solved it by downgrading firebase and google dependencies to 11.4.2 to match the firebase ui version provided here: https://github.com/firebase/FirebaseUI-Android. </p>

Title: multidex error on android studio 3

Body:
Before upgrading to AS 3, I used multidex in my project just fine, after upgrading It started getting this error each time i try to run the app on a device or even generate an APK

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp;
  Error:com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp; Error:  at
  com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
  Error:    at
  com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
  Error:    at
  com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
  Error:    at
  com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
  Error:    at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
  Error:    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
  Error:    at
  java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
  Error:    at
  java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
  Error:    at
  java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
  Error:    at
  java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Please not that all i did was update AS and gradle plguin to 3.0.0. I tried going back to 2.3.3, but It tells me the project is incompatible.

Here is my Multidex code:

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "net.mohammed.billmob"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

and my application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

and these are the app dependencies:

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:mediarouter-v7:26.1.0'

   // compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-perf:11.6.0'

    compile 'com.karumi:dexter:4.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.facebook.android:facebook-android-sdk:4.28.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    compile 'com.android.support:support-v4:26.1.0'

    compile 'com.android.support:multidex:1.0.1'
/*    compile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex-instrumentation:1.0.2'*/

    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0'
    testCompile 'junit:junit:4.12'
}


问:
How to make backtrace()/backtrace_symbols() print the function names?
The Linux specific backtrace() and backtrace_symbols() allows you to produce a call trace of the program. However, it only prints function addresses, not their names for my program. How can I make them print the function names as well ? I've tried compiling the program with -g as well as -ggdb. The test case below just prints this:

```

    BACKTRACE ------------
    ./a.out() [0x8048616]
    ./a.out() [0x8048623]
    /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413]
    ./a.out() [0x8048421]
    ----------------------
    ```

I'd want the first 2 items to also show the function names, foo and main

Code:

```<code>#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) && (errno != EINTR))
                        break;

                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}

void print_backtrace(void)
{
        static const char start[] = "BACKTRACE ------------\n";
        static const char end[] = "----------------------\n";

        void *bt[1024];
        int bt_size;
        char **bt_syms;
        int i;

        bt_size = backtrace(bt, 1024);
        bt_syms = backtrace_symbols(bt, bt_size);
        full_write(STDERR_FILENO, start, strlen(start));
        for (i = 1; i < bt_size; i++) {
                size_t len = strlen(bt_syms[i]);
                full_write(STDERR_FILENO, bt_syms[i], len);
                full_write(STDERR_FILENO, "\n", 1);
        }
        full_write(STDERR_FILENO, end, strlen(end));
    free(bt_syms);
}
void foo()
{
    print_backtrace();
}

int main()
{
    foo();
    return 0;
}
</code>```

答:
the answer on the top has a bug
if ret == -1 and errno is EINTER you should try again, but not count ret as copied
(not going to make an account just for this, if you don't like it tough)</p>

```<code>static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) {
                        if (errno != EINTR))
                                break;
                        //else
                        continue;
                }
                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}
</code>```

Body:
The Linux specific backtrace() and backtrace_symbols() allows you to produce a call trace of the program. However, it only prints function addresses, not their names for my program. How can I make them print the function names as well ? I've tried compiling the program with -g as well as -ggdb. The test case below just prints this:

    BACKTRACE ------------
    ./a.out() [0x8048616]
    ./a.out() [0x8048623]
    /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413]
    ./a.out() [0x8048421]
    ----------------------

I'd want the first 2 items to also show the function names, foo and main

Code:

#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) && (errno != EINTR))
                        break;

                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}

void print_backtrace(void)
{
        static const char start[] = "BACKTRACE ------------\n";
        static const char end[] = "----------------------\n";

        void *bt[1024];
        int bt_size;
        char **bt_syms;
        int i;

        bt_size = backtrace(bt, 1024);
        bt_syms = backtrace_symbols(bt, bt_size);
        full_write(STDERR_FILENO, start, strlen(start));
        for (i = 1; i < bt_size; i++) {
                size_t len = strlen(bt_syms[i]);
                full_write(STDERR_FILENO, bt_syms[i], len);
                full_write(STDERR_FILENO, "\n", 1);
        }
        full_write(STDERR_FILENO, end, strlen(end));
    free(bt_syms);
}
void foo()
{
    print_backtrace();
}

int main()
{
    foo();
    return 0;
}

Body:
the answer on the top has a bug
if ret == -1 and errno is EINTER you should try again, but not count ret as copied
(not going to make an account just for this, if you don't like it tough)

static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) {
                        if (errno != EINTR))
                                break;
                        //else
                        continue;
                }
                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}


问:
Propagate constness to data pointed by member variables
It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct:

```<code>class SomeClass
{
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom

  public:

    void const_method() const;
};

struct SomeClass::SomeClassImpl
{
    void non_const_method() { /*modify data*/ }
};

void SomeClass::const_method() const
{
    impl_->non_const_method(); //ok because impl_ is const, not *impl_
};
</code>```

However, it would sometimes be rather handy if the constness would propagate to pointed objects (I voluntarily used the PImpl idiom because it is one of the case where I think "constness propagation" would be very useful).

When using pointers, this can easily be achieved by using some kind of smart pointer with operators overloaded on constness:

```<code>template < typename T >
class const_propagating_ptr
{
  public:

    const_propagating_ptr( T * ptr ) : ptr_( ptr ) {}

    T       & operator*()       { return *ptr_; }
    T const & operator*() const { return *ptr_; }

    T       * operator->()       { return ptr_; }
    T const * operator->() const { return ptr_; }

    // assignment operator (?), get() method (?), reset() method (?)
    // ...

  private:

    T * ptr_;
};
</code>```

Now, I just need to modify SomeClass::impl_ to be a const_propagating_ptr<SomeClassImpl> to obtain the wanted behavior.

So I have a few questions about this:

Are there some issues with constness propagation that I have overlooked?

If not, are there any libraries that provide classes to obtain constness propagation?

Wouldn't it be useful that the common smart pointers (unique_ptr, shared_ptr, etc.) provide some mean to obtain this behavior (for example through a template parameter)?

答:
One approach is to just not use the pointer directly except through two accessor functions.</p>

```<code>class SomeClass
{
  private:
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom - don't use me directly!

    SomeClassImpl * mutable_impl() { return impl_; }
    const SomeClassImpl * impl() const { return impl_; }

  public:

    void const_method() const
    {
      //Can't use mutable_impl here.
      impl()->const_method();
    }
    void non_const_method() const
    {
      //Here I can use mutable_impl
      mutable_impl()->non_const_method();
    }
};
</code>```

Body:
It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct:

class SomeClass
{
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom

  public:

    void const_method() const;
};

struct SomeClass::SomeClassImpl
{
    void non_const_method() { /*modify data*/ }
};

void SomeClass::const_method() const
{
    impl_->non_const_method(); //ok because impl_ is const, not *impl_
};

However, it would sometimes be rather handy if the constness would propagate to pointed objects (I voluntarily used the PImpl idiom because it is one of the case where I think "constness propagation" would be very useful).

When using pointers, this can easily be achieved by using some kind of smart pointer with operators overloaded on constness:

template < typename T >
class const_propagating_ptr
{
  public:

    const_propagating_ptr( T * ptr ) : ptr_( ptr ) {}

    T       & operator*()       { return *ptr_; }
    T const & operator*() const { return *ptr_; }

    T       * operator->()       { return ptr_; }
    T const * operator->() const { return ptr_; }

    // assignment operator (?), get() method (?), reset() method (?)
    // ...

  private:

    T * ptr_;
};

Now, I just need to modify SomeClass::impl_ to be a const_propagating_ptr<SomeClassImpl> to obtain the wanted behavior.

So I have a few questions about this:

Are there some issues with constness propagation that I have overlooked?

If not, are there any libraries that provide classes to obtain constness propagation?

Wouldn't it be useful that the common smart pointers (unique_ptr, shared_ptr, etc.) provide some mean to obtain this behavior (for example through a template parameter)?

Body:
One approach is to just not use the pointer directly except through two accessor functions.

class SomeClass
{
  private:
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom - don't use me directly!

    SomeClassImpl * mutable_impl() { return impl_; }
    const SomeClassImpl * impl() const { return impl_; }

  public:

    void const_method() const
    {
      //Can't use mutable_impl here.
      impl()->const_method();
    }
    void non_const_method() const
    {
      //Here I can use mutable_impl
      mutable_impl()->non_const_method();
    }
};


问:
SQL Schema Comparison Error "Target is unavailable"
When comparing an SQLServer project in Visual Studio 2015 Update 2 against a database SQL Server 2012, it shows the error "Target is unavailable" or "Source is unavailable" when change the direction.

It used to work properly a couple of months ago. Is there any workaround? I couldn't find any.

答:
For me it was the \ symbol at the end of the server's ip address in the server name field that fixed it. Very strange.

e.g. instead of 10.10.10.10 i write 10.10.10.10\ and it connects ok.

Note: I'm using Visual Studio 2017.


问:
Manipulating a factor and category in R
So i have a data set i am trying to manipulate and i cant seem to find the right way to do this. Iv looked into using dcast and spread but not sure how to get the right manipulation.

so i have something like:

```<code>ID var1 var2 var3 category
--------------------------
1  x    x    x     a
1  x    x    x     b
1  x    x    x     b
2  y    y    y     a
2  y    y    y     b
2  y    y    y     c
3  z    z    z     b
3  z    z    z     b
3  z    z    z     c
</code>```

Id like it to look like this:

```<code>ID var1 var2 var3  a  b  c
--------------------------------
1  x    x    x     1  1  0
2  y    y    y     1  1  1
3  z    z    z     0  1  1
</code>```

Easy example data

```<code>ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c('x','x','x','y','y','y','z','z','z')
var2 <- c('x','x','x','y','y','y','z','z','z')
var3 <- c('x','x','x','y','y','y','z','z','z')
category <- c('a','b','b','a','b','c','b','b','c')

dat <- data.frame(ID,var1,var2,var3,category)
</code>```

答:
```<code>ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c("x","x","x","y","y","y","z","z","z")
var2 <- c("x","x","x","y","y","y","z","z","z")
var3 <- c("x","x","x","y","y","y","z","z","z")
category <- c("a","b","b","a","b","c","b","b","c")

dat <- data.frame(ID,var1,var2,var3,category)

library(tidyr)
library(dplyr)

dat %>%
  distinct() %>%                   # get distinct rows
  mutate(value = 1) %>%            # create a counter
  spread(category, value, fill=0)  # reshape dataset

#   ID var1 var2 var3 a b c
# 1  1    x    x    x 1 1 0
# 2  2    y    y    y 1 1 1
# 3  3    z    z    z 0 1 1
</code>```

Title: Manipulating a factor and category in R

Body:
So i have a data set i am trying to manipulate and i cant seem to find the right way to do this. Iv looked into using dcast and spread but not sure how to get the right manipulation.

so i have something like:

ID var1 var2 var3 category
--------------------------
1  x    x    x     a
1  x    x    x     b
1  x    x    x     b
2  y    y    y     a
2  y    y    y     b
2  y    y    y     c
3  z    z    z     b
3  z    z    z     b
3  z    z    z     c

Id like it to look like this:

ID var1 var2 var3  a  b  c
--------------------------------
1  x    x    x     1  1  0
2  y    y    y     1  1  1
3  z    z    z     0  1  1

Easy example data

ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c('x','x','x','y','y','y','z','z','z')
var2 <- c('x','x','x','y','y','y','z','z','z')
var3 <- c('x','x','x','y','y','y','z','z','z')
category <- c('a','b','b','a','b','c','b','b','c')

dat <- data.frame(ID,var1,var2,var3,category)


问:
Extended Request class's attributes are empty - Laravel
I've created an own Request called ValidateSecretRequest for the google 2fa. But I only get empty attributes.

As additional information: I followed a tutorial from https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/

After the authenticate() method the LoginController executes the postValidateToken() method. For testing I only implemented the request output.

LoginController

```<code>public function postValidateToken(ValidateSecretRequest $request) {
      echo '```'; print_r($request); echo '```';
}
</code>```

Request class

Firstly I supposed that there was a mistake with the extened Request? Actually it should be right in this way?

```<code><?php

namespace App\Http\Requests;

use Cache;
use Crypt;
use Google2FA;
use App\User;
use Illuminate\Validation\Factory as ValidatonFactory;
use Illuminate\Http\Request;

class ValidateSecretRequest extends Request {
   /**
    *
    * @var \App\User
    */
   private $user;
   public $totp;

   /**
    * Create a new FormRequest instance.
    *
    * @param \Illuminate\Validation\Factory $factory
    * @return void
    */
   public function __construct(ValidatonFactory $factory) {
      $factory->extend(
         'valid_token',
         function ($attribute, $value, $parameters, $validator) {
            $secret = Crypt::decrypt($this->user->google2fa_secret);

            return Google2FA::verifyKey($secret, $value);
         },
         'Not a valid token'
      );

      $factory->extend(
         'used_token',
         function ($attribute, $value, $parameters, $validator) {
            $key = $this->user->id . ':' . $value;

            return !Cache::has($key);
         },
         'Cannot reuse token'
      );
   }

   /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
   public function authorize() {
      try {
         $this->user = User::findOrFail(
            session('2fa:user:id')
         );
      } catch (Exception $exc) {
         return false;
      }

      return true;
   }

   /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
   public function rules() {
      return [
         'totp' => 'bail|required|digits:6|valid_token|used_token',
      ];
   }
}
</code>```

But the function postValidateToken() returns an empty array.

```<code>App\Http\Requests\ValidateSecretRequest Object
(
    [user:App\Http\Requests\ValidateSecretRequest:private] =>
    [totp] =>
    [json:protected] =>
    [convertedFiles:protected] =>
    [userResolver:protected] =>
    [routeResolver:protected] =>
    [attributes] =>
    [request] =>
    [query] =>
    [server] =>
    ...
    [session:protected] =>
    [locale:protected] =>
    [defaultLocale:protected] => en
    [isHostValid:Symfony\Component\HttpFoundation\Request:private] => 1
    [isForwardedValid:Symfony\Component\HttpFoundation\Request:private] => 1
)
</code>```

答:
Found the solution:

You have to use FormRequest not Request

```<code>use Illuminate\Foundation\Http\FormRequest;
</code>```

Body:
I've created an own Request called ValidateSecretRequest for the google 2fa. But I only get empty attributes.

As additional information: I followed a tutorial from https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/

After the authenticate() method the LoginController executes the postValidateToken() method. For testing I only implemented the request output.

LoginController

public function postValidateToken(ValidateSecretRequest $request) {
      echo '
'; print_r($request); echo '
';
}

Request class

Firstly I supposed that there was a mistake with the extened Request? Actually it should be right in this way?

<?php

namespace App\Http\Requests;

use Cache;
use Crypt;
use Google2FA;
use App\User;
use Illuminate\Validation\Factory as ValidatonFactory;
use Illuminate\Http\Request;

class ValidateSecretRequest extends Request {
   /**
    *
    * @var \App\User
    */
   private $user;
   public $totp;

   /**
    * Create a new FormRequest instance.
    *
    * @param \Illuminate\Validation\Factory $factory
    * @return void
    */
   public function __construct(ValidatonFactory $factory) {
      $factory->extend(
         'valid_token',
         function ($attribute, $value, $parameters, $validator) {
            $secret = Crypt::decrypt($this->user->google2fa_secret);

            return Google2FA::verifyKey($secret, $value);
         },
         'Not a valid token'
      );

      $factory->extend(
         'used_token',
         function ($attribute, $value, $parameters, $validator) {
            $key = $this->user->id . ':' . $value;

            return !Cache::has($key);
         },
         'Cannot reuse token'
      );
   }

   /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
   public function authorize() {
      try {
         $this->user = User::findOrFail(
            session('2fa:user:id')
         );
      } catch (Exception $exc) {
         return false;
      }

      return true;
   }

   /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
   public function rules() {
      return [
         'totp' => 'bail|required|digits:6|valid_token|used_token',
      ];
   }
}

But the function postValidateToken() returns an empty array.

App\Http\Requests\ValidateSecretRequest Object
(
    [user:App\Http\Requests\ValidateSecretRequest:private] =>
    [totp] =>
    [json:protected] =>
    [convertedFiles:protected] =>
    [userResolver:protected] =>
    [routeResolver:protected] =>
    [attributes] =>
    [request] =>
    [query] =>
    [server] =>
    ...
    [session:protected] =>
    [locale:protected] =>
    [defaultLocale:protected] => en
    [isHostValid:Symfony\Component\HttpFoundation\Request:private] => 1
    [isForwardedValid:Symfony\Component\HttpFoundation\Request:private] => 1
)

Body:
Found the solution:

You have to use FormRequest not Request

use Illuminate\Foundation\Http\FormRequest;


问:
Linking within jqGrid
Suppose we have 2 separate jqGrid pages. On one side we have an overview about artists, on the other an overview about their works. I done linking with context menu. For example, from artist there is a link to their works. The link is as follows

```<code>$(window.location).attr('href', $(window.location).attr('href').replace('c_picture','c_edition')+'?_search=true&rows=10&page=1&searchField=work_id&searchOper=eq&searchString='+jQuery("#grid").getCell(e.id, 'work_id');
</code>```

Is it a reasonable solution to the problem?

PS. I am not looking for ajax load, I try to make a link to another page (to another grid). I changed my call now to window.location.href = window.location.href.replace('c_picture','c_edition')+'/?_search=true&rows=10&page=1&searchField=work_id&searchOper=eq&searchString='+jQuery('#grid').getCell(e.id, 'work_id'); But this method seems still to be very "dirty". For example with window.location.href I can not change parameter _search. Is it better to make small form with all GET-Parameters and then submit this?

答:
I link two grids together on a single page (not sure if that's what you're talking about here) as follows

by using the onSelectRow to set the url on the grid to be 'affected'..

jQuery("#userGrid").jqGrid({
   "datatype":"json",
   "rowNum":10,
   ...

...
   'onSelectRow':function(id, status) {
      jQuery('#userDetailsGrid').setGridParam({
         url:'jsonRequest.php?JSONRequestType=details&userId='+id,
         page:1
      })
      .trigger('reloadGrid');
   },
   ...

...
};

Note: looks like $(window.location).attr('href') is something you should avoid generally as it's broken in 1.4.3 and 1.4.4 - see http://bugs.jquery.com/ticket/7607

Title: Linking within jqGrid

Body:
Suppose we have 2 separate jqGrid pages. On one side we have an overview about artists, on the other an overview about their works. I done linking with context menu. For example, from artist there is a link to their works. The link is as follows

$(window.location).attr('href', $(window.location).attr('href').replace('c_picture','c_edition')+'?_search=true&rows=10&page=1&searchField=work_id&searchOper=eq&searchString='+jQuery("#grid").getCell(e.id, 'work_id');

Is it a reasonable solution to the problem?

PS. I am not looking for ajax load, I try to make a link to another page (to another grid). I changed my call now to window.location.href = window.location.href.replace('c_picture','c_edition')+'/?_search=true&rows=10&page=1&searchField=work_id&searchOper=eq&searchString='+jQuery('#grid').getCell(e.id, 'work_id'); But this method seems still to be very "dirty". For example with window.location.href I can not change parameter _search. Is it better to make small form with all GET-Parameters and then submit this?


问:
svg scaling with jquery
i am developing a website but i am not that good at the UI part, anyway i have managed to get an SVG file from illustrator then using jquery i am manipulating it, however it doesn't show properly on browsers, the SVG is bigger than the "preview" on adobe illustrator, the preview on adobe use <object> but in JQUERY i am loading the svg file directly

here is the head of my svg file

```<code><?xml version="1.0" encoding="iso-8859-1"?>
    <!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version:
    6.00 Build 0)  -->
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 768"
    style="width:1024;height:768;">
</code>```

and here is start of my code

```<code><!doctype html>
<html>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-
 1.0.1.min.js"></script>
 <script>
 $.get('new.svg', function(data) {
 $(document.body).append(data.documentElement);
 $('#TESTGROUPCIRCLE').on('click touchstart', function () {
 $('#tooltip').hide();
 $('#TESTTEXT').fadeIn();
 $('#MAIN').fadeOut();
  });
</code>```

i am not sure why the svg shows larger when i get it directly without using <object> , it shows at 1333 * 999 for a reason i don't know, anybody came across such a problem before?

答:
You should use the img tag with style="width:1024;height:768" to display the svg in the correct dimensions.
You are appending the svg right onto the body without having an img tag.
As far as I can see your new.svg is at the same source. So there should be no need to load it with jQuery.

Title: svg scaling with jquery

Body:
i am developing a website but i am not that good at the UI part, anyway i have managed to get an SVG file from illustrator then using jquery i am manipulating it, however it doesn't show properly on browsers, the SVG is bigger than the "preview" on adobe illustrator, the preview on adobe use <object> but in JQUERY i am loading the svg file directly

here is the head of my svg file

<?xml version="1.0" encoding="iso-8859-1"?>

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 768"
    style="width:1024;height:768;">

and here is start of my code

<!doctype html>


问:
heatmap2 lmat,lhei, lwid parameters?
I'm trying to make a heat map with dendrogram in R. I'm also trying to make it so that the color matrix is on the bottom of the heat map. i understand that I would have to change the value of lmat for this. So far I have something like this for lmat.

```<code> lmat=rbind(c(0,3,0), c(2,1,0), c(0,4,0)).
</code>```

After I run it, it asks me to update the lhei and lwid values. After looking at the documentation, I understand that these are vectors for column width and row height. But I don't understand the multiple values needed for their values. For ex, when I set this , I get this error.

```<code>  lhei must have length = nrow(lmat) = 3
</code>```

I'm not sure what the three values for lhei would correspond to. This leads me to a broader question, what does each value in the vectors for lhei and lwid correspond to?

答:
lmat stands for layout matrix, and in heatmap.2 the default is a 2x2 matrix used to organize four components (1=heatmap, 2=row dendogram, 3=col dendogram, 4= key ) as follows:
lmat = rbind(c(4,3),c(2,1))
Your error, "lhei must have length = nrow(lmat) = 3" arises because you need to specify the new lhei or layout row heights, which from your code is now 3 rows. Visually it helps to organize this code in stacked format. In your example I can clearly see that the key will be below the heatmap, while the zeros are used as padding.  </p>

Title: heatmap2 lmat,lhei, lwid parameters?

Body:
I'm trying to make a heat map with dendrogram in R. I'm also trying to make it so that the color matrix is on the bottom of the heat map. i understand that I would have to change the value of lmat for this. So far I have something like this for lmat.

 lmat=rbind(c(0,3,0), c(2,1,0), c(0,4,0)).

After I run it, it asks me to update the lhei and lwid values. After looking at the documentation, I understand that these are vectors for column width and row height. But I don't understand the multiple values needed for their values. For ex, when I set this , I get this error.

  lhei must have length = nrow(lmat) = 3

I'm not sure what the three values for lhei would correspond to. This leads me to a broader question, what does each value in the vectors for lhei and lwid correspond to?


问:
Ending OpenMP for prematurely
I have a problem with writing a routine in C++ using OpenMP for. The code of the routine is as follows:

```<code>int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                }
            }
        }
    return solution;
}
</code>```

when running this routine without the parallel clause, everything works fine (i.e. routine returns true every time it's called). However, when I use the parallel for, it sometimes returns false. I wasn't able to figure out, why is this happening and the only way of removing this bug is from my perspective ending the whole parallel block prematurely after solution is set to true. However, if I did my research properly, there is no way to prematurely end a parallel block. Could you please suggest me an alternative?

EDIT: Adding minimal functioning example as requested:

```<code>#include <omp.h>
#include <iostream>
#include <list>
#include <chrono>

using namespace std;

bool solutionFound = false;
int sudoku [9][9] = { 5,7,0,9,0,0,0,0,8,
                      0,0,0,0,0,5,0,3,9,
                      0,0,0,0,0,0,2,0,4,
                      0,0,0,0,9,0,6,8,0,
                      0,0,0,8,0,2,0,0,0,
                      0,5,2,0,7,0,0,0,0,
                      6,0,5,0,0,0,0,0,0,
                      7,9,0,4,0,0,0,0,0,
                      2,0,0,0,0,9,0,7,6};

int sudokuSolution [9][9];

bool isPossible(int s[9][9], int row, int col, int val) {
    for(int i = 0; i < 9; i++) {
        if (s[row][i] == val)
            return false;
        if (s[i][col] == val)
            return false;
        if (s[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == val)
            return false;
    }
    return true;
}

bool solve(int s[9][9], int row, int col) {
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }

    for (int val = 1; val < 10; val++) {
        if (isPossible(s,row,col,val)){
            sudokuSolution[row][col] = val;
            s[row][col] = val;
            if (solve(s, row + col / 9, (col + 1) % 9))
                return true;
            sudokuSolution[row][col] = 0;
            s[row][col] = 0;
        }
    }
    return false;
}

bool solvep(int sa[9][9], int row, int col) {
    int s [9][9];
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            s[i][j] = sa[i][j];
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if(!solutionFound) {
                if (isPossible(s,row,col,val)){
                    s[row][col] = val;
                    if (solve(s, row + col / 9, (col + 1) % 9)) {
                        sudokuSolution[row][col] = val;
                        solutionFound = true;
                        solution = true;
                    }
                }
            }
        }
    return solution;
}

int main() {
    for (int k = 0; k < 100; k++) {
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                sudokuSolution[i][j] = sudoku[i][j];
        solutionFound = false;
        solvep(sudokuSolution,0,0);
        bool calcResult = solvep(sudoku,0,0);
        cout << calcResult;
    }
    return 0;
}
</code>```

答:
You could reduce the solution values on all threads using the || operator:

```<code>int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for reduction(||:solution)
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                } else {
                    solution = false;
                }
            } else {
                 solution = false;
            }
        }
    return solution;
}
</code>```

Title: Ending OpenMP for prematurely

Body:
I have a problem with writing a routine in C++ using OpenMP for. The code of the routine is as follows:

int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                }
            }
        }
    return solution;
}

when running this routine without the parallel clause, everything works fine (i.e. routine returns true every time it's called). However, when I use the parallel for, it sometimes returns false. I wasn't able to figure out, why is this happening and the only way of removing this bug is from my perspective ending the whole parallel block prematurely after solution is set to true. However, if I did my research properly, there is no way to prematurely end a parallel block. Could you please suggest me an alternative?

EDIT: Adding minimal functioning example as requested:

#include <omp.h>
#include <iostream>
#include <list>
#include <chrono>

using namespace std;

bool solutionFound = false;
int sudoku [9][9] = { 5,7,0,9,0,0,0,0,8,
                      0,0,0,0,0,5,0,3,9,
                      0,0,0,0,0,0,2,0,4,
                      0,0,0,0,9,0,6,8,0,
                      0,0,0,8,0,2,0,0,0,
                      0,5,2,0,7,0,0,0,0,
                      6,0,5,0,0,0,0,0,0,
                      7,9,0,4,0,0,0,0,0,
                      2,0,0,0,0,9,0,7,6};

int sudokuSolution [9][9];

bool isPossible(int s[9][9], int row, int col, int val) {
    for(int i = 0; i < 9; i++) {
        if (s[row][i] == val)
            return false;
        if (s[i][col] == val)
            return false;
        if (s[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == val)
            return false;
    }
    return true;
}

bool solve(int s[9][9], int row, int col) {
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }

    for (int val = 1; val < 10; val++) {
        if (isPossible(s,row,col,val)){
            sudokuSolution[row][col] = val;
            s[row][col] = val;
            if (solve(s, row + col / 9, (col + 1) % 9))
                return true;
            sudokuSolution[row][col] = 0;
            s[row][col] = 0;
        }
    }
    return false;
}

bool solvep(int sa[9][9], int row, int col) {
    int s [9][9];
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            s[i][j] = sa[i][j];
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if(!solutionFound) {
                if (isPossible(s,row,col,val)){
                    s[row][col] = val;
                    if (solve(s, row + col / 9, (col + 1) % 9)) {
                        sudokuSolution[row][col] = val;
                        solutionFound = true;
                        solution = true;
                    }
                }
            }
        }
    return solution;
}

int main() {
    for (int k = 0; k < 100; k++) {
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                sudokuSolution[i][j] = sudoku[i][j];
        solutionFound = false;
        solvep(sudokuSolution,0,0);
        bool calcResult = solvep(sudoku,0,0);
        cout << calcResult;
    }
    return 0;
}

Body:
You could reduce the solution values on all threads using the || operator:

int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for reduction(||:solution)
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                } else {
                    solution = false;
                }
            } else {
                 solution = false;
            }
        }
    return solution;
}


问:
GPS 5.0.2 - Build fails instantly with "Invalid Context, Cannot Build"
We have a fairly old Ada project where we are using GPS 5.0.2 (20110607) hosted on x86_64-pc-linux-gnu with GNAT Pro 6.4.2 (20110614-45).

GPS is able to perform the "check semantic" and "compile file" functions, but upon selection of "build main" or "build all," it fails immediately with the message Invalid context, cannot build.

A google search of this revealed that there was a bug that was fixed at one point dealing with this issue (it had to do with symlinks in the project tree), yet there are no symlinks and the workaround suggested does not work.

Build currently and has always worked perfectly when doing it from the command line, and build from GPS menu works fine on everyone's development computer except mine. We have checked environment variables, deleted the Gnat directory (and loaded one from a working computer), and deleted all Git repos and re-cloned from the server. At this point, I am out of ideas as to how to get it to work. It was my original understanding that everything GPS needs to know about a project is contained in the .gpr file.

Is there a settings location that I don't know about? Any ideas why this message pops up when I try to build, or what it means?

答: Sometimes problems like this can be fixed by deleting the ~/.gpsdirectory, which contains your personal settings.


问:
Android studio uses 100% CPU while just coding (no builiding)
Android Studio uses 100% CPU when I'm just coding, even if I type a single word CPU use raises to the 100% and comes to back normal, and if I keep typing it takes 100% CPU all the time.

What I have tried is :

File > Invalidate cache and Restart

Change max heap size for android studio by editing VM options

"Power Save Mode" it runs perfectly when it is turned on. but it also disables some useful features of IDE and I don't want to disable it.

removed .android and .AndroidStudio3.0 folder from c:\users\username\

Android Studio plugins are set to default. no extra plugins are added. I tried disabling a plugin that can be disabled like Git and SVN but it's still same

I'm running windows 7 64-bit OS and Android Studio 3.0 and OS which I re-installed yesterday. I did not install the JDK - Android Studio is using default OpenJDK.

I've searched on internet but it did not help. any help would be appreciated.

答:
Did you try to set the power plan to best performance instead of balanced plan.
This may consume the battery but may solve this problem.</p>


问:
ASP.NET MVC View Model Naming Conventions
I know I will probably get a mixed opinion on this, but I was wondering if there were and "Best Practices" for model naming conventions.

I have a rather large application and I have adopted the following model naming convention:

Models

Add

CategoryAddModel

ProductAddModel

Edit

CategoryEditModel

ProductEditModel

View

CategoryViewModel

ProductViewModel

I was thinking of the following as well:

Models

Add

AddCategoryModel

AddProductModel

Edit

EditCategoryModel

EditProductModel

View

ViewCategoryModel

ViewProductModel

Which do you prefer, and why?

Do you think it really matters?

答:
To pull out Hightmaston's comment into a formal answer for clarity.

A logical template to follow would be:

{Controller}{ViewName}ViewModel

This encourages better file organization at scale, and reduces the number of Intellisense "hits".

A simple example might be as follows:

CategoryIndexViewModel

For brevity you may also consider:

CategoryIndexModel


问:
Pandas Shift values within group for subset of groups
I am looking to shift values within group, but only for a subset of the groups in the Series.

I have something like the following Series:

```<code>import pandas as pd
df=pd.DataFrame()
df['Group']=['A','A','A','B','B','B','C','C','C']
df['Month']=[1,2,3,1,2,3,1,2,3]
df['Value']=1000,900,800,700,600,500,400,300,200
df=df.set_index(['Group','Month'])['Value']
df
Out[101]:
Group  Month
A      1        1000
       2         900
       3         800
B      1         700
       2         600
       3         500
C      1         400
       2         300
       3         200
Name: Value, dtype: int64
</code>```

I want group A to remain as it is, but groups B and C should have their values shifted up by one. I can do this across all groups (as described in this question as follows:

```<code> df.groupby(level='Group').transform(lambda x:x.shift(-1))
</code>```

However, to do this for only a subset of groups, I can't come up with a more elegant way than separating the series and then concatenating back together, as I show below:

```<code>df_a = df[df.index.get_level_values('Group')=='A']
df_other = df[df.index.get_level_values('Group')<>'A']

pd.concat([df_a,df_other.groupby(level='Group').transform(lambda x:x.shift(-1))])
Out[104]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64
</code>```

Is there a more elegant solution to this?

答:
```<code>In [361]: df.groupby(level='Group').transform(lambda x:x if x.name=='A' else x.shift(-1))
Out[361]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64
</code>```

or you can update only specific rows (solution provided by @cᴏʟᴅsᴘᴇᴇᴅ) - this will simplify solution dramatically:

```<code>In [363]: df.loc[['B', 'C']] = df.loc[['B', 'C']].groupby(level=0).shift(-1)

In [364]: df
Out[364]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64
</code>```

Body:
I am looking to shift values within group, but only for a subset of the groups in the Series.

I have something like the following Series:

import pandas as pd
df=pd.DataFrame()
df['Group']=['A','A','A','B','B','B','C','C','C']
df['Month']=[1,2,3,1,2,3,1,2,3]
df['Value']=1000,900,800,700,600,500,400,300,200
df=df.set_index(['Group','Month'])['Value']
df
Out[101]:
Group  Month
A      1        1000
       2         900
       3         800
B      1         700
       2         600
       3         500
C      1         400
       2         300
       3         200
Name: Value, dtype: int64

I want group A to remain as it is, but groups B and C should have their values shifted up by one. I can do this across all groups (as described in this question as follows:

 df.groupby(level='Group').transform(lambda x:x.shift(-1))

However, to do this for only a subset of groups, I can't come up with a more elegant way than separating the series and then concatenating back together, as I show below:

df_a = df[df.index.get_level_values('Group')=='A']
df_other = df[df.index.get_level_values('Group')<>'A']

pd.concat([df_a,df_other.groupby(level='Group').transform(lambda x:x.shift(-1))])
Out[104]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64

Is there a more elegant solution to this?

Body:
In [361]: df.groupby(level='Group').transform(lambda x:x if x.name=='A' else x.shift(-1))
Out[361]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64

or you can update only specific rows (solution provided by @cᴏʟᴅsᴘᴇᴇᴅ) - this will simplify solution dramatically:

In [363]: df.loc[['B', 'C']] = df.loc[['B', 'C']].groupby(level=0).shift(-1)

In [364]: df
Out[364]:
Group  Month
A      1        1000.0
       2         900.0
       3         800.0
B      1         600.0
       2         500.0
       3           NaN
C      1         300.0
       2         200.0
       3           NaN
Name: Value, dtype: float64


问:
javascript counter using for loop
I've created a simple counter using javascript but there is a problem Field "display" starts from 1, but it should start from 100 and goes low. The console logs shows values correctly from 100 to 1.
I have to use loops to do this tasks, so please not replace it using recursion :) Also the timeout is for sure does not equal to 100ms, it's more

function wyswietlLiczbe(j) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, 100);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

答:
Build the conditional into the function which will execute after the timeout.</p>

```<code>var elmD = document.getElementById("display");

function wyswietlLiczbe(j) {
    setTimeout(function() {
      elmD.innerHTML = j;

      j--;

      if(0 <= j ) {
        wyswietlLiczbe(j)
      }
    }, 100);
}

wyswietlLiczbe(100);
</code>```

Title: javascript counter using for loop

Body:
Build the conditional into the function which will execute after the timeout.

var elmD = document.getElementById("display");

function wyswietlLiczbe(j) {
    setTimeout(function() {
      elmD.innerHTML = j;

      j--;

      if(0 <= j ) {
        wyswietlLiczbe(j)
      }
    }, 100);
}

wyswietlLiczbe(100);


问:
how to unwind javascript object into Json object without duplicate entries
existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}

I want to convert this javascript into something that doesnt have array items in it, like below

desiredJsObj = [{"a":1, "b":11},{"a":2,"b":22},{"a":3, "b":33},{"a":4, "b":44}]

答:
try this</p>

```<code>existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
desiredJsObj = []
keys = Object.keys(existingJsObj);
existingJsObj[keys[0]].forEach((val, index) => {
    value = {};
    keys.forEach((key, i) => value[key] = existingJsObj[key][index])
    desiredJsObj.push(value)
})
</code>```

Body:
try this

existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
desiredJsObj = []
keys = Object.keys(existingJsObj);
existingJsObj[keys[0]].forEach((val, index) => {
    value = {};
    keys.forEach((key, i) => value[key] = existingJsObj[key][index])
    desiredJsObj.push(value)
})


问:
Python Pandas print() and .to_csv() truncating results
I have a dataframe with 8 columns and 1399 rows. When I use the print() function to display the dataframe, it comes out roughly like this:

```<code>        Column 1    Column 2    Column 3    Column 4    \
1       data        data        data        data
2       data        data        data        data
3       data        data        data        data
4       data        data        data        data
5       data        data        data        data
...     ...         ...         ....        ....
1395    data        data        data        data
1396    data        data        data        data
1397    data        data        data        data
1398    data        data        data        data
1399    data        data        data        data

    Column 5    Column 6    Column 7    Column 8
1       data        data        data        data
2       data        data        data        data
3       data        data        data        data
4       data        data        data        data
5       data        data        data        data
...     ...         ...         ....        ....
1395    data        data        data        data
1396    data        data        data        data
1397    data        data        data        data
1398    data        data        data        data
1399    data        data        data        data
</code>```

I thought that this was just python making it easy to read via standard output, but when I use the .to_csv() function, the resulting .csv file looks exactly like the above. I've never had Pandas do this before. Does anyone know what I'm doing wrong? Thanks in advance.

答:
Set the display.max_colwidth option to -1 as follows

```<code>pd.set_option('display.max_colwidth', -1)
</code>```

for more detail check out this link

Body:
I have a dataframe with 8 columns and 1399 rows. When I use the print() function to display the dataframe, it comes out roughly like this:

        Column 1    Column 2    Column 3    Column 4    \
1       data        data        data        data
2       data        data        data        data
3       data        data        data        data
4       data        data        data        data
5       data        data        data        data
...     ...         ...         ....        ....
1395    data        data        data        data
1396    data        data        data        data
1397    data        data        data        data
1398    data        data        data        data
1399    data        data        data        data

    Column 5    Column 6    Column 7    Column 8
1       data        data        data        data
2       data        data        data        data
3       data        data        data        data
4       data        data        data        data
5       data        data        data        data
...     ...         ...         ....        ....
1395    data        data        data        data
1396    data        data        data        data
1397    data        data        data        data
1398    data        data        data        data
1399    data        data        data        data

I thought that this was just python making it easy to read via standard output, but when I use the .to_csv() function, the resulting .csv file looks exactly like the above. I've never had Pandas do this before. Does anyone know what I'm doing wrong? Thanks in advance.

Body:
Set the display.max_colwidth option to -1 as follows

pd.set_option('display.max_colwidth', -1)

for more detail check out this link