问:
Create a function that outputs spending level based on money spent - Python
How do I create a function that says that for example if a person spends 100 dollars they are bronze, whereas if they spend between 100 dollars and 200 dollars they are silver?

I am trying to learn how to use user defined functions rather than loops, so would prefer no suggestions using loops.

Thanks

答:
What you'd likely want to use here is an If Statement with comparative operators.

You could make a python function to do this like so.

```<code>def findSpendingLevel(moneySpent):
  if (moneySpent <= 100):
    return 'bronze'

  if (moneySpent > 100 and moneySpent <= 200):
    return 'silver'

  if (moneySpent > 200 and moneySpent <= 300):
    return 'gold'

  if (moneySpent > 300):
    return 'diamond'
</code>```

Would likely be good for your purposes. Notice how this works by taking in an argument which is the moneySpent variable, and comparing it to the boundaries of your money levels with less-than-or-equal-to (<=) and greater-than (>) comparative operators.

Body:
What you'd likely want to use here is an If Statement with comparative operators.

You could make a python function to do this like so.

def findSpendingLevel(moneySpent):
  if (moneySpent <= 100):
    return 'bronze'

  if (moneySpent > 100 and moneySpent <= 200):
    return 'silver'

  if (moneySpent > 200 and moneySpent <= 300):
    return 'gold'

  if (moneySpent > 300):
    return 'diamond'

Would likely be good for your purposes. Notice how this works by taking in an argument which is the moneySpent variable, and comparing it to the boundaries of your money levels with less-than-or-equal-to (<=) and greater-than (>) comparative operators.


来源: stackexchange

问:
Is there a easy way to get the data with timestamp == yesterday?
Is there a easy way to get the data with timestamp == yesterday?

I just want the data of yesterday.

```<code>SELECT
 COUNT(t0.user_id) AS t0_qt_AC5uO9oi
FROM
 `{something here}` AS t0
WHERE
 (t0.event_type = 'XXXXX')
ORDER BY
 t0_qt_AC5uO9oi ASC;
</code>```

Not sure what is the best way.

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT
  CURRENT_DATE() today,
  DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY) yesterday
</code>```

<p>Assuming that you are asking for how to get yesterday's date!<br>
Then of course you need to use it in your query respectively   </p>

<p>for example  </p>

<pre class="lang-sql prettyprint-override"><code>WHERE t0.event_date = DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a easy way to get the data with timestamp == yesterday?

I just want the data of yesterday.

SELECT
 COUNT(t0.user_id) AS t0_qt_AC5uO9oi
FROM
 `{something here}` AS t0
WHERE
 (t0.event_type = 'XXXXX')
ORDER BY
 t0_qt_AC5uO9oi ASC;

Not sure what is the best way.

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  CURRENT_DATE() today,
  DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY) yesterday

Assuming that you are asking for how to get yesterday's date!

Then of course you need to use it in your query respectively

for example

WHERE t0.event_date = DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY)


问:
SQL group by week and get the date of start of the week
I have a FiscalCalendar in MS SQL which has FiscalWeek, Week, FiscalMonth, Month, datekey etc. I have joined this table to another table. I am running a query to get the sales data for different categories and grouping them by FiscalWeek. However, in the table, I want to display the first day of the week associated with it. When I add Date to the select and groupby cause, my granularity changes (which I know is wrong)

I want something like this:

Instead I am getting this when I put date in the select and the group by clause

Here is my Query:

```<code>select cal.FiscalYear, cal.FiscalWeek, CONVERT(VARCHAR(10), cal.Date, 111) AS Date, sum(sd.Used) as Actual, sd.ShipGrp

from ods.adhoc.MktFiscalCalendar as cal,
Details as sd

where cal.daykey=sd.sys1dt
and cal.FiscalYear in ('2018')

Group by cal.FiscalYear, cal.FiscalWeek, Date, sd.ShipGrp
</code>```

答:
I think you can do this in a windows function.  Please try something like below.  Note that we remove the date from the group by clause and use the MIN() aggregate function in the SELECT clause.  Partitioning by week, will change the result for each week - be sure to order it or the results can look deceiving.  </p>

```<code>SELECT cal.FiscalYear
       , cal.FiscalWeek
       , MIN(cal.Date)
           OVER (
             PARTITION BY cal.FiscalWeek) AS Date
       , sum(sd.Used)                     AS Actual
       , sd.ShipGrp
FROM   ods.adhoc.MktFiscalCalendar AS cal,
       Details AS sd
WHERE  cal.daykey = sd.sys1dt
       AND cal.FiscalYear IN ( '2018' )
GROUP  BY cal.FiscalYear
          , cal.FiscalWeek
          , sd.ShipGrp
</code>```

Body:
I have a FiscalCalendar in MS SQL which has FiscalWeek, Week, FiscalMonth, Month, datekey etc. I have joined this table to another table. I am running a query to get the sales data for different categories and grouping them by FiscalWeek. However, in the table, I want to display the first day of the week associated with it. When I add Date to the select and groupby cause, my granularity changes (which I know is wrong)

I want something like this:

Instead I am getting this when I put date in the select and the group by clause

Here is my Query:

select cal.FiscalYear, cal.FiscalWeek, CONVERT(VARCHAR(10), cal.Date, 111) AS Date, sum(sd.Used) as Actual, sd.ShipGrp

from ods.adhoc.MktFiscalCalendar as cal,
Details as sd

where cal.daykey=sd.sys1dt
and cal.FiscalYear in ('2018')

Group by cal.FiscalYear, cal.FiscalWeek, Date, sd.ShipGrp

Body:
I think you can do this in a windows function.  Please try something like below.  Note that we remove the date from the group by clause and use the MIN() aggregate function in the SELECT clause.  Partitioning by week, will change the result for each week - be sure to order it or the results can look deceiving.

SELECT cal.FiscalYear
       , cal.FiscalWeek
       , MIN(cal.Date)
           OVER (
             PARTITION BY cal.FiscalWeek) AS Date
       , sum(sd.Used)                     AS Actual
       , sd.ShipGrp
FROM   ods.adhoc.MktFiscalCalendar AS cal,
       Details AS sd
WHERE  cal.daykey = sd.sys1dt
       AND cal.FiscalYear IN ( '2018' )
GROUP  BY cal.FiscalYear
          , cal.FiscalWeek
          , sd.ShipGrp


问:
What is the point of initializing a base class object as a derived class object
If I want to initialize a class Square

```<code>class Square : public Rectangle {
    public Square(int length)
    {
        this->length = length;
        this->width = length;
    }
}
</code>```

derived from a class Rectangle

```<code>class Rectangle {
    protected int length, width;

    public Rectangle(int length, int width)
    {
        this->length = length;
        this->width = width;
    }

    public int getArea() { return length * width; }
}
</code>```

I'll do it like

```<code>Square * s = new Square(5);
cout << s->getArea() << endl;
</code>```

What are the benefits of doing it like

```<code>Rectangle * r = new Square(5);
cout << r->getArea() << endl;
</code>```

instead and initializing the object as a base class object?

答:
You have an interface and an implementation of that interface. This is part of how inheritance and polymorphism work together.

Rectangle *r = new Square works only if Square derives from Rectangle.  Any object that is a Rectangle descendant can be assigned to a Rectangle* pointer.

Say all your code needs is a Rectangle* pointer to do its work.  The code doesn't need to care whether it operates on a Square object in memory.  Perhaps you have to make that decision based on user input at run-time, or certain business rules, etc.  Polymorphism allows that.  The interface ensures that the needed Rectangle functionality is available, and how to use it.  The compiler takes care of delegating to the implementation accordingly.

Body:
If I want to initialize a class Square

class Square : public Rectangle {
    public Square(int length)
    {
        this->length = length;
        this->width = length;
    }
}

derived from a class Rectangle

class Rectangle {
    protected int length, width;

    public Rectangle(int length, int width)
    {
        this->length = length;
        this->width = width;
    }

    public int getArea() { return length * width; }
}

I'll do it like

Square * s = new Square(5);
cout << s->getArea() << endl;

What are the benefits of doing it like

Rectangle * r = new Square(5);
cout << r->getArea() << endl;

instead and initializing the object as a base class object?


问:
C array is overwriting an index
I am reading from 2 different files and running this function on each.
The file format is

```<code>2
3
8 7 6
5 4 3
</code>```

The code I am using is

```<code>void readFile(char txtName[], int k, int matrix){
    int c = 0;
    int i = 0;
    int j = 0;
    int x = 0;
    //Open file
    FILE *txt;
    txt = fopen(txtName, "r");
    //Go till the end of the file
    while( fscanf(txt, "%d", &c) != EOF ){
        //For assigning matrix A
        if(matrix == 1){
            //Used to skip over the first 2 inputs.
            if(x > 1){
                //Got to the end of the row increase to the next row.
                if(j == k){
                    i++;
                    j = 0;
                }
                //Assiging c to A
                A[i][j] = c;
                printf("%d A in matrix %d %d\n", A[i][j], i, j);
                j++;
            }
        x++;
        }
    }
    fclose(txt);
}

int main( int argc, char *argv[] )  {
    readFile(argv[1], k, 1);
    int m = 2;
    int k = 3;
    int i;
    int j;
    for(i=0; i < m; i++){
        for(j=0; j < k; j++){
            printf("%d", A[i][j]);
        }
        printf("\n");
    }
}
</code>```

I am trying to initialize an 2 dimensional array with the file so that it is a matrix. The first value of the file is the m and the second is the k. So from the file posted. it is a 2x3 matrix with the values below it. A is a global array set to A[2][3];

The issue I am having is when I run this code my array comes out with

```<code>8 7 5
5 4 3
</code>```

and I have no clue why. I have put a lot of print statements for debugging. When it comes to i = 0 and j = 2 it prints out 6. But when I print the array after the function A[0][2] = 5. Where is the error that I am making?

答: Your problem probably with while( fscanf(txt, "%d", &c) != EOF ). Just try with while( fscanf(txt, "%d", &c)) and check.

Title: C array is overwriting an index

Body:
I am reading from 2 different files and running this function on each.
The file format is

2
3
8 7 6
5 4 3

The code I am using is

void readFile(char txtName[], int k, int matrix){
    int c = 0;
    int i = 0;
    int j = 0;
    int x = 0;
    //Open file
    FILE *txt;
    txt = fopen(txtName, "r");
    //Go till the end of the file
    while( fscanf(txt, "%d", &c) != EOF ){
        //For assigning matrix A
        if(matrix == 1){
            //Used to skip over the first 2 inputs.
            if(x > 1){
                //Got to the end of the row increase to the next row.
                if(j == k){
                    i++;
                    j = 0;
                }
                //Assiging c to A
                A[i][j] = c;
                printf("%d A in matrix %d %d\n", A[i][j], i, j);
                j++;
            }
        x++;
        }
    }
    fclose(txt);
}

int main( int argc, char *argv[] )  {
    readFile(argv[1], k, 1);
    int m = 2;
    int k = 3;
    int i;
    int j;
    for(i=0; i < m; i++){
        for(j=0; j < k; j++){
            printf("%d", A[i][j]);
        }
        printf("\n");
    }
}

I am trying to initialize an 2 dimensional array with the file so that it is a matrix. The first value of the file is the m and the second is the k. So from the file posted. it is a 2x3 matrix with the values below it. A is a global array set to A[2][3];

The issue I am having is when I run this code my array comes out with

8 7 5
5 4 3

and I have no clue why. I have put a lot of print statements for debugging. When it comes to i = 0 and j = 2 it prints out 6. But when I print the array after the function A[0][2] = 5. Where is the error that I am making?


问:
Calculate broadcast by IP and mask
i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why?

```<code> IP = '192.168.32.16'
 MASK = '255.255.0.0'

 def get_ID(ip, mask):
    ip = ip.split('.')
    mask = mask.split('.')
    ip = [int(bin(int(octet)), 2) for octet in ip]
    mask = [int(bin(int(octet)), 2) for octet in mask]
    subnet = [str(int(bin(ioctet & moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    host = [str(int(bin(ioctet & ~moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess
    print('Subnet: {0}'.format('.'.join(subnet)))
    print('Host: {0}'.format('.'.join(host)))
    print('Broadcast address: {0}'.format('.'.join(broadcast)))
</code>```

答:
Instead of optimizing the Python code, use the ipaddress module to do the work.
https://docs.python.org/3/library/ipaddress.html

```<code>import ipaddress

IP = '192.168.32.16'
MASK = '255.255.0.0'

host = ipaddress.IPv4Address(IP)
net = ipaddress.IPv4Network(IP + '/' + MASK, False)
print('IP:', IP)
print('Mask:', MASK)
print('Subnet:', ipaddress.IPv4Address(int(host) & int(net.netmask)))
print('Host:', ipaddress.IPv4Address(int(host) & int(net.hostmask)))
print('Broadcast:', net.broadcast_address)
</code>```

OUTPUT:

```<code>IP: 192.168.32.16
Mask: 255.255.0.0
Subnet: 192.168.0.0
Host: 0.0.32.16
Broadcast: 192.168.255.255
</code>```

Title: Calculate broadcast by IP and mask

Body:
i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why?

 IP = '192.168.32.16'
 MASK = '255.255.0.0'

 def get_ID(ip, mask):
    ip = ip.split('.')
    mask = mask.split('.')
    ip = [int(bin(int(octet)), 2) for octet in ip]
    mask = [int(bin(int(octet)), 2) for octet in mask]
    subnet = [str(int(bin(ioctet & moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    host = [str(int(bin(ioctet & ~moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess
    print('Subnet: {0}'.format('.'.join(subnet)))
    print('Host: {0}'.format('.'.join(host)))
    print('Broadcast address: {0}'.format('.'.join(broadcast)))

Body:
Instead of optimizing the Python code, use the ipaddress module to do the work.
https://docs.python.org/3/library/ipaddress.html

import ipaddress

IP = '192.168.32.16'
MASK = '255.255.0.0'

host = ipaddress.IPv4Address(IP)
net = ipaddress.IPv4Network(IP + '/' + MASK, False)
print('IP:', IP)
print('Mask:', MASK)
print('Subnet:', ipaddress.IPv4Address(int(host) & int(net.netmask)))
print('Host:', ipaddress.IPv4Address(int(host) & int(net.hostmask)))
print('Broadcast:', net.broadcast_address)

OUTPUT:

IP: 192.168.32.16
Mask: 255.255.0.0
Subnet: 192.168.0.0
Host: 0.0.32.16
Broadcast: 192.168.255.255


问:
Revert To Previous Version In Github, only editing in Github
I am probably missing something very simple somewhere...

What I would like to do is revert to a previous version of a READ.ME file which I have only edited in Github.  Everything I have found to do this involves using the Git CLI, but there must be a way to do this directly in Github without having to clone the repo?

I am trying to create some gh-pages and was planning on only editing in Github.

Thanks.

答:
To revert to a previous version of a README.md file by only editing it via the Github UI:

Simply open a list of your commits (you will see several tabs at the top of the window containing your project's files and folders: commits, branches, releases etc.);

Select one of your previous commits in the list and click on it;

Click on Browse files button;

Select the file you want to copy the content from, open and copy it to the clipboard;

Go back to your last commit by clicking on your project's name on the top of the window and paste the copied text back to your README.md)


问:
PHP SQL - Json like search
I'm sending json via dataloader like this:

```<code>{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}
</code>```

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

```<code>...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...
</code>```

答:
Loop your name array to create a new array with LIKE operator and implode it with OR operator in your query.</p>

```<code>$data = '{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}';

$arr = json_decode($data,true);

$name = $arr['person']['name'];
$search_term =array();
// loop it to add like operator
foreach($name as $t=>$tag){
    $search_term[] = "name LIKE '%".$tag['tag']."%'";
}

$query = "SELECT name, id FROM accounts WHERE visible != '1'";
if (!empty($search_term)) {
    // implode you like with or operator
    $query.=" AND ".implode( ' OR ' , $search_term);
}
$query.=" ORDER BY name DESC";

echo $query;

SELECT name, id FROM accounts WHERE visible != '1' AND name LIKE '%peter%' OR name LIKE '%frank%' OR name LIKE '%jeff%' ORDER BY name DESC
</code>```

Title: PHP SQL - Json like search

Body:
I'm sending json via dataloader like this:

{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...

Body:
Loop your name array to create a new array with LIKE operator and implode it with OR operator in your query.

$data = '{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}';

$arr = json_decode($data,true);

$name = $arr['person']['name'];
$search_term =array();
// loop it to add like operator
foreach($name as $t=>$tag){
    $search_term[] = "name LIKE '%".$tag['tag']."%'";
}

$query = "SELECT name, id FROM accounts WHERE visible != '1'";
if (!empty($search_term)) {
    // implode you like with or operator
    $query.=" AND ".implode( ' OR ' , $search_term);
}
$query.=" ORDER BY name DESC";

echo $query;

SELECT name, id FROM accounts WHERE visible != '1' AND name LIKE '%peter%' OR name LIKE '%frank%' OR name LIKE '%jeff%' ORDER BY name DESC


问:
On click, select more than one element with Jquery
I have 4 buttons, where I have to select one in each row.

I have to choose one button of the first two and one button of the last two. So, two buttons.
I was able to make the JavaScript for the first two, but now i want to improve my code so I can select one of each button.

JavaScript:

```<code>$(document).ready(function(){
    //show content by default
    $(".opt-container button:first-child").addClass("active");

    $('.opt-container button').click(function(){
      $('.opt-container button').removeClass('active');
      $(this).addClass('active');

    });
});
</code>```

HTML:

```<code><div class="row">
<div class="opt-container" style="display: flex; margin: auto; padding-bottom:15px;">
    <button class="opt1-img active" dir="rtl">
        <img class="" src="../lp.8/img/venus.png">
        <p class="col-xs-12 text-center" style="margin-top:10px; font-weight: 700;" dir="rtl">أنا امرأة</p>
    </button>
    <button class="opt2-img" dir="rtl">
        <img class="" src="../lp.8/img/mars.png">
        <p class="col-xs-12 text-center" style="margin-top:13px; font-weight: 700;" dir="rtl">أنا رجل</p>
    </button>
</div>

<div class="opt-container" style="display: flex; margin: auto;">
    <button class="opt1-img active" dir="rtl">
        <img class="" src="../lp.8/img/loupe.png">
        <p class="col-xs-12 text-center" style="margin-top:10px; font-weight: 700;" dir="rtl">وحيد</p>
    </button>
    <button class="opt2-img" dir="rtl">
        <img class="" src="../lp.8/img/wedding-rings.png">
        <p class="col-xs-12 text-center" style="margin-top:13px; font-weight: 700;" dir="rtl">متزوج</p>
    </button>
</div>
</code>```

How can I do this?
I'm novice to javaScript and all help is welcome. :)

答:
You can look for the siblings with the active class.  In this case, it will be the "other" button.

```<code>$(document).ready(function(){
    //show content by default
    $(".opt-container button:first-child").addClass("active");

    $('.opt-container button').click(function(){
      $(this).siblings('.active').removeClass('active');
      $(this).addClass('active');
    });
});
</code>```

Here is a Fiddle Demo: https://jsfiddle.net/zephyr_hex/45t7gpzj/

Body:
I have 4 buttons, where I have to select one in each row.

I have to choose one button of the first two and one button of the last two. So, two buttons.
I was able to make the JavaScript for the first two, but now i want to improve my code so I can select one of each button.

JavaScript:

$(document).ready(function(){
    //show content by default
    $(".opt-container button:first-child").addClass("active");

    $('.opt-container button').click(function(){
      $('.opt-container button').removeClass('active');
      $(this).addClass('active');

    });
});

HTML:

    <button class="opt1-img active" dir="rtl">

أنا امرأة

    </button>
    <button class="opt2-img" dir="rtl">

أنا رجل

    </button>

    <button class="opt1-img active" dir="rtl">

وحيد

    </button>
    <button class="opt2-img" dir="rtl">

متزوج

    </button>

How can I do this?
I'm novice to javaScript and all help is welcome. :)

Body:
You can look for the siblings with the active class.  In this case, it will be the "other" button.

$(document).ready(function(){
    //show content by default
    $(".opt-container button:first-child").addClass("active");

    $('.opt-container button').click(function(){
      $(this).siblings('.active').removeClass('active');
      $(this).addClass('active');
    });
});

Here is a Fiddle Demo: https://jsfiddle.net/zephyr_hex/45t7gpzj/


问:
Use VBA to hide/unhide columns (named ranges) in a table based on selection made in a separate cell on a different sheet
I have a selection criteria cell on Sheet1 and have a table on Sheet 2. Sheet 1 Cell B3 will have a dropdown with different options. I want to be able to make a selection in this dropdown which will accordingly hide/unhide certain columns in the table on Sheet2. So far the code i have below is based on selections being made on the same sheet as the table and i'm stuck as the code isnt working as i expect it to.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 2 And Target.Row = 3 And Target.Value = "CustomView" Then

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = True

Else

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = False

End If

End Sub
</code>```

The named ranges i specified using the formulas section. "Months" is in column G, and "Fruits" is in column I, yet the code currently hides columns G, H and I, instead of just column G and column I. Furthermore, everytime i try to move the selection criteria to a separate sheet, i get errors. Any help or suggestions would be appreciated.

答:
I would like to propose a re-write that will help you simplify the readability and maintainability of this code moving forward.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$3" Then
        Range("Fruits,Months").EntireColumn.Hidden = Target.Value = "CustomView"
    End If

End Sub
</code>```

To be clear, this should not be marked as answer, because tigeravatar already fixed your issue.

Body:
I have a selection criteria cell on Sheet1 and have a table on Sheet 2. Sheet 1 Cell B3 will have a dropdown with different options. I want to be able to make a selection in this dropdown which will accordingly hide/unhide certain columns in the table on Sheet2. So far the code i have below is based on selections being made on the same sheet as the table and i'm stuck as the code isnt working as i expect it to.

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 2 And Target.Row = 3 And Target.Value = "CustomView" Then

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = True

Else

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = False

End If

End Sub

The named ranges i specified using the formulas section. "Months" is in column G, and "Fruits" is in column I, yet the code currently hides columns G, H and I, instead of just column G and column I. Furthermore, everytime i try to move the selection criteria to a separate sheet, i get errors. Any help or suggestions would be appreciated.

Body:
I would like to propose a re-write that will help you simplify the readability and maintainability of this code moving forward.

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$3" Then
        Range("Fruits,Months").EntireColumn.Hidden = Target.Value = "CustomView"
    End If

End Sub

To be clear, this should not be marked as answer, because tigeravatar already fixed your issue.


问:
I am looking to copy latest data entered in excel to be copied to another excel file in share point without openning it. Is it possible?
I have created a work tracker with online help for my team. Couldn't attach it in here.
If needed, let me know your e-mail address so I can forward it to you.

I want that whenever any of my team member is updating the file on their local storage, then the updated lines should be copied in sharepoint as well without openning any other file.

Please suggest the best way, either to create new file on every instance or to copy the data in to the first empty row of destination.

Thank you!

答: Is there a reason why people can't edit the file in the browser and use the co-authoring features of Excel Online?</p>


问:
linking file menu items to buttons
I'm in need of linking some buttons in a 'document based' application to the file menu (bold text, italic text, make text bigger etc.). The issue is that since its a document based application, the MainMenu.xib is a completely different XIB file than the MyDocument.xib, so I can't drag the connections in Interface Builder like I usually would. Does anyone have a workaround? Is there a way to link button actions to a separate XIB files' built in menu functions?

Zach

答:
Generally, you use the First Responder place-holder object.

About the First Responder

"In Interface Builder, the First Responder is a proxy object that represents the first object in your application’s dynamically determined responder chain. Because the responder chain of an application cannot be determined at design time, the First Responder proxy acts as a stand-in target for any action messages that need to be directed at the application’s responder chain. Menu items commonly target the First Responder proxy. For example, the Minimize menu item in the Window menu hides the frontmost window in an application, not just a specific window, and the Copy menu item should copy the current selection, not just the selection of a single control or view. Other objects in your application can target the First Responder as well."

Also see:
Connecting Menu Items Across Nib Files

Also, if you want to create buttons whose actions are basically the same as the Format > Bold, etc. commands, see: Connecting the Font Menu in Interface Builder 3

ContentLicense: CC BY-SA 2.5

Title: linking file menu items to buttons


问:
Filtering an ElementsCollection
I'm trying to create a function to filter an ElementsCollection, with a condition on a child of each element instead of the element itself.

Here's what I came up with:

```<code> public static ElementsCollection filterByChild(ElementsCollection elementsCollection, String childCssSelector,
        Condition condition) {

        Predicate<SelenideElement> childHasConditionPredicate = element -> element.$(childCssSelector).has(condition);
        elementsCollection.removeIf(childHasConditionPredicate);
        return elementsCollection;
    }
</code>```

When calling this function like this:

```<code>myCollection = SelenideHelpers.filterByChild(myCollection, "a", Condition.text("http://www.link.com");
</code>```

I'm getting the following error message:

```<code>java.lang.UnsupportedOperationException: Cannot remove elements from web page
</code>```

I did not found any relevant informations on this error message that could be applied to my code. I would like to know why is this message appearing.

答:
Check how SelenideElementIterator is designed:

```<code>@Override
public void remove() {
  throw new UnsupportedOperationException("Cannot remove elements from web page");
}
</code>```

To make it work you need to create your custom condition like:

```<code>import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static com.codeborne.selenide.Selenide.$$;

public static Condition hasChildWithCondition(final By locator, final Condition condition) {
    return new Condition("hasChildWithCondition") {
        @Override
        public boolean apply(WebElement element) {
            return element.findElements(locator).stream().anyMatch(child -> condition.apply(child));
        }

        public String toString() {
            return this.name
        }
    };
}
</code>```

and then use it to filter:

```<code>ElementsCollection collection = $$(".parent");
Condition hasChild = hasChildWithCondition(By.cssSelector("a"), Condition.text("http://www.link.com"));
collection.filterBy(hasChild);
</code>```

Title: Filtering an ElementsCollection

Body:
I'm trying to create a function to filter an ElementsCollection, with a condition on a child of each element instead of the element itself.

Here's what I came up with:

 public static ElementsCollection filterByChild(ElementsCollection elementsCollection, String childCssSelector,
        Condition condition) {

        Predicate<SelenideElement> childHasConditionPredicate = element -> element.$(childCssSelector).has(condition);
        elementsCollection.removeIf(childHasConditionPredicate);
        return elementsCollection;
    }

When calling this function like this:

myCollection = SelenideHelpers.filterByChild(myCollection, "a", Condition.text("http://www.link.com");

I'm getting the following error message:

java.lang.UnsupportedOperationException: Cannot remove elements from web page

I did not found any relevant informations on this error message that could be applied to my code. I would like to know why is this message appearing.

Body:
Check how SelenideElementIterator is designed:

@Override
public void remove() {
  throw new UnsupportedOperationException("Cannot remove elements from web page");
}

To make it work you need to create your custom condition like:

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static com.codeborne.selenide.Selenide.$$;

public static Condition hasChildWithCondition(final By locator, final Condition condition) {
    return new Condition("hasChildWithCondition") {
        @Override
        public boolean apply(WebElement element) {
            return element.findElements(locator).stream().anyMatch(child -> condition.apply(child));
        }

        public String toString() {
            return this.name
        }
    };
}

and then use it to filter:

ElementsCollection collection = $$(".parent");
Condition hasChild = hasChildWithCondition(By.cssSelector("a"), Condition.text("http://www.link.com"));
collection.filterBy(hasChild);

ContentLicense: CC BY-SA 4.0


问:
When will objects allocated on a thread be freed after the thread completes?
in this code

```<code>    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();
</code>```

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?

答: there is no direct way to free memory in java. GC will run and takes care of this. If you think that you will get outofmemoryexception, then note that, java will run garbage collector to free some memory before throwing that error. Hope this helps</p>

Body:
in this code

    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?


问:
find intersect by rows in r
I am trying to find common targets affected by drugs (shown as entry number in following table).

```<code>IDARUBICIN <- c(1,5,12,13,18,27,NA,NA,NA,NA,NA,NA)
EPIRUBICIN <- c(1,2,5,6,12,13,17,18,19,21,23,24)
DAUNORUBICIN <- c(1,4,5,11,12,13,16,18,19,27,41,44)
VINBLASTINE <- c(1,4,5,12,13,18,19,27,30,37,39,44)
VINORELBINE <- c(1,5,12,13,18,19,27,41,44,NA,NA,NA)
all <- rbind(IDARUBICIN,EPIRUBICIN,DAUNORUBICIN,VINBLASTINE,VINORELBINE)
> all
             [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
IDARUBICIN      1    5   12   13   18   27   NA   NA   NA    NA    NA    NA
EPIRUBICIN      1    2    5    6   12   13   17   18   19    21    23    24
DAUNORUBICIN    1    4    5   11   12   13   16   18   19    27    41    44
VINBLASTINE     1    4    5   12   13   18   19   27   30    37    39    44
VINORELBINE     1    5   12   13   18   19   27   41   44    NA    NA    NA
</code>```

I tried finding intersect using each row that worked fine

```<code>ans <- Reduce(intersect, list(all[1,],all[2,],all[3,],all[4,],all[5,]))
> ans
[1]  1  5 12 13 18
</code>```

But I have 30 rows (i.e. 30 drugs) so I can't use this method.
Can someone please tell me how to find intersect of a table by rows?
I can't use my above mentioned solution, because it requires me to type each row and I don't want to do that

答:
```<code>library(tibble)
library(purrr)

t(all) %>%
  as_tibble() %>%
  reduce(intersect)
</code>```

Title: find intersect by rows in r

Body:
I am trying to find common targets affected by drugs (shown as entry number in following table).

IDARUBICIN <- c(1,5,12,13,18,27,NA,NA,NA,NA,NA,NA)
EPIRUBICIN <- c(1,2,5,6,12,13,17,18,19,21,23,24)
DAUNORUBICIN <- c(1,4,5,11,12,13,16,18,19,27,41,44)
VINBLASTINE <- c(1,4,5,12,13,18,19,27,30,37,39,44)
VINORELBINE <- c(1,5,12,13,18,19,27,41,44,NA,NA,NA)
all <- rbind(IDARUBICIN,EPIRUBICIN,DAUNORUBICIN,VINBLASTINE,VINORELBINE)
> all
             [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
IDARUBICIN      1    5   12   13   18   27   NA   NA   NA    NA    NA    NA
EPIRUBICIN      1    2    5    6   12   13   17   18   19    21    23    24
DAUNORUBICIN    1    4    5   11   12   13   16   18   19    27    41    44
VINBLASTINE     1    4    5   12   13   18   19   27   30    37    39    44
VINORELBINE     1    5   12   13   18   19   27   41   44    NA    NA    NA

I tried finding intersect using each row that worked fine

ans <- Reduce(intersect, list(all[1,],all[2,],all[3,],all[4,],all[5,]))
> ans
[1]  1  5 12 13 18

But I have 30 rows (i.e. 30 drugs) so I can't use this method.
Can someone please tell me how to find intersect of a table by rows?
I can't use my above mentioned solution, because it requires me to type each row and I don't want to do that


问:
Uncaught TypeError: Cannot redefine property: nativeReduce
I have a Rails app, with turbolinks. I get this error when I refresh pages

Uncaught TypeError: Cannot redefine property: nativeReduce
      at Function.defineProperty ()
      at visitor.js:1
      (anonymous) @visitor.js:1

In head tag I have this code:

```<code>    :coffeescript
  ready = ->
    fc_CSS = document.createElement('link')
    fc_CSS.setAttribute 'rel', 'stylesheet'
    fc_isSecured = window.location and window.location.protocol == 'https:'
    fc_lang = document.getElementsByTagName('html')[0].getAttribute('lang')
    fc_rtlLanguages = [
      'ar'
      'he'
    ]
    fc_rtlSuffix = if fc_rtlLanguages.indexOf(fc_lang) >= 0 then '-rtl' else ''
    fc_CSS.setAttribute 'type', 'text/css'

    // freshdesk widget generated code

  $(document).ready(ready)
  $(document).on('turbolinks:load', ready)
</code>```

ready function is executed every time, but that error occurred. If I remove turbolinks it's working, but I want to keep turbolink.

All I want is to make a freshdesk widget appear  without refreshing pages.

答:
I'm not absolutely certain how FreshDesk's widget works, but for most things like this (Google Analytics, etc.) you typically need to destroy the widget before render (if it exists) and re-initialize.

Some good leads here: http://reed.github.io/turbolinks-compatibility/

Body:
I have a Rails app, with turbolinks. I get this error when I refresh pages

Uncaught TypeError: Cannot redefine property: nativeReduce
      at Function.defineProperty ()
      at visitor.js:1
      (anonymous) @visitor.js:1

In head tag I have this code:

    :coffeescript
  ready = ->
    fc_CSS = document.createElement('link')
    fc_CSS.setAttribute 'rel', 'stylesheet'
    fc_isSecured = window.location and window.location.protocol == 'https:'
    fc_lang = document.getElementsByTagName('html')[0].getAttribute('lang')
    fc_rtlLanguages = [
      'ar'
      'he'
    ]
    fc_rtlSuffix = if fc_rtlLanguages.indexOf(fc_lang) >= 0 then '-rtl' else ''
    fc_CSS.setAttribute 'type', 'text/css'

    // freshdesk widget generated code

  $(document).ready(ready)
  $(document).on('turbolinks:load', ready)

ready function is executed every time, but that error occurred. If I remove turbolinks it's working, but I want to keep turbolink.

All I want is to make a freshdesk widget appear  without refreshing pages.


问:
GraphQL error update mutation "Resolve function for \"User.id\" returned undefined"
I am a newbie to GraphQL and trying to write an update mutation.  However, I am receiving Resolve function for \"User.id\" returned undefined" error although the database is actually got updated.

What am I doing wrong?

userSchema.js:

import Sequelize from 'sequelize';
import SqlHelper from '../helpers/sqlhelper';

const config = require('../../config');

const sequelizer = new SqlHelper(config).Init();

const createUser = sequelizer.define(
  'createUser',
  {
    ...
    }
);
const updateUser = sequelizer.define(
  'updateUser',
  {
    id: {
      type: Sequelize.UUID,
      field: 'Id',
      primaryKey: true,
      defaultValue: Sequelize.UUIDV4,
    },
    username: {
      type: Sequelize.STRING,
      field: 'Username',
      allowNull: true,
    },
    email: {
      type: Sequelize.STRING,
      field: 'Email',
      allowNull: true,
    },
    firstname: {
      type: Sequelize.STRING,
      field: 'FirstName',
      allowNull: true,
    },
    lastname: {
      type: Sequelize.STRING,
      field: 'LastName',
      allowNull: true,
    },
   ....
  },
  {
    // define the table's name
    tableName: 'Users',
  },
);

module.exports = User;```
</div>
</div>
</p>

<p><strong>UserResolver.js:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import User from '../dbschemas/user';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default {

  Mutation: {
    createUser: async (obj, args) =>
      (await User.create(args)),
    updateUser: async (obj, args) =>
      (await User.update(args,
        {
          where: {
            id: args.id,
          },
          returning: true
        }))

  }
};</code>```

Although calling updateUser from GraphiQL updates the records (in db), it results in a "Resolve function for \"User.id\" returned undefined" error:

mutation{
  updateUser(id: "2ecd38ca-cf12-4e79-ac93-e922f24af9e3",
    username: "newUserTesting",
    email: "testemail@yahoo.com",
    lastname: "TestUserLName",
    firstname: "fname1") {
   id
  }
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "data": null,
  "errors": [
    {
      "message": "Resolve function for \"User.id\" returned undefined",
      "locations": [
        {
          "line": 16,
          "column": 4
        }
      ],
      "path": [
        "updateUser",
        "id"
      ]
    }
  ]
}</code>```

答:
The issue is clear, your resolver does not return an object containing id.
The docs say that Model.update returns an array in which the 2nd element is the affected row.
Hence, your resolver should look like:

```<code>async updateUser(obj, args) {
  const resultArray = await User.update( ... )
  return resultArray[1]
}
</code>```

... To be replaced by whatever you need.

Body:
I am a newbie to GraphQL and trying to write an update mutation.  However, I am receiving Resolve function for \"User.id\" returned undefined" error although the database is actually got updated.

What am I doing wrong?

userSchema.js:

import Sequelize from 'sequelize';
import SqlHelper from '../helpers/sqlhelper';

const config = require('../../config');

const sequelizer = new SqlHelper(config).Init();

const createUser = sequelizer.define(
  'createUser',
  {
    ...
    }
);
const updateUser = sequelizer.define(
  'updateUser',
  {
    id: {
      type: Sequelize.UUID,
      field: 'Id',
      primaryKey: true,
      defaultValue: Sequelize.UUIDV4,
    },
    username: {
      type: Sequelize.STRING,
      field: 'Username',
      allowNull: true,
    },
    email: {
      type: Sequelize.STRING,
      field: 'Email',
      allowNull: true,
    },
    firstname: {
      type: Sequelize.STRING,
      field: 'FirstName',
      allowNull: true,
    },
    lastname: {
      type: Sequelize.STRING,
      field: 'LastName',
      allowNull: true,
    },
   ....
  },
  {
    // define the table's name
    tableName: 'Users',
  },
);

module.exports = User;

UserResolver.js:

import User from '../dbschemas/user';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default {

  Mutation: {
    createUser: async (obj, args) =>
      (await User.create(args)),
    updateUser: async (obj, args) =>
      (await User.update(args,
        {
          where: {
            id: args.id,
          },
          returning: true
        }))

  }
};

Although calling updateUser from GraphiQL updates the records (in db), it results in a "Resolve function for \"User.id\" returned undefined" error:

mutation{
  updateUser(id: "2ecd38ca-cf12-4e79-ac93-e922f24af9e3",
    username: "newUserTesting",
    email: "testemail@yahoo.com",
    lastname: "TestUserLName",
    firstname: "fname1") {
   id
  }
}

{
  "data": null,
  "errors": [
    {
      "message": "Resolve function for \"User.id\" returned undefined",
      "locations": [
        {
          "line": 16,
          "column": 4
        }
      ],
      "path": [
        "updateUser",
        "id"
      ]
    }
  ]
}

Body:
The issue is clear, your resolver does not return an object containing id.
The docs say that Model.update returns an array in which the 2nd element is the affected row.
Hence, your resolver should look like:

async updateUser(obj, args) {
  const resultArray = await User.update( ... )
  return resultArray[1]
}

... To be replaced by whatever you need.


问:
Premium SMS billing solution
Are their any good solutions for sending mobile content to users for a monthly fee? I'd like to have it so they enter a number in the web-based opt-in page and then they have to confirm a pin to confirm their subscription. I can't find any arregator that allows for monthly billing for US carriers. Any ideas?

My application is in PHP an API would be necessary and I'd like to have the payments go on their mobile phone bill (not manage myself)

答:
If you're wanting to use an aggregator and bill to the customer's cell phone bill, you can use mBlox. If you want to bill clients yourself and just send content to them, check out Twilio (to send the texts/calls) and Braintree (to handle payments).

Whatever option you choose, you would still need to build your application to interface with these providers.

Title: Premium SMS billing solution


问:
How to create and join multiple derived tables in sql server
I'm pretty new to SQL and am hitting a wall and would really appreciate any help!

I'm using SQL Server in Azure. I have a table called Votes that has the columns:

arenaId

eventId

userId

vote

active

groupA

groupB

In here, I've got multiple users voting on various events (eventId) which are part of various arenas (arenaId).  The user can belong to either/both/none of groupA,and groupB.  The vote column can have a value of 0,1,2. The active column filters out which vote to count as each user can only cast a single vote per eventId. So if they cast multiple votes, all subsequent votes will have active=0 and the latest will have active=1

Each arena would have multiple events associated with it, but the event is unique to a specific arena.

My goal is to be able to count the types of votes per arena per group.

Sample Table Setup:

```<code>arenaId | eventId | userId | vote | active | groupA | groupB
------------------------------------------------------------
abc123 |   123   |   5    |   0  |    1   |    0   |    0
abc123 |   124   |   5    |   2  |    1   |    0   |    0
abc123 |   125   |   5    |   1  |    1   |    0   |    0
abc123 |   126   |   5    |   1  |    1   |    0   |    0
------------------------------------------------------------
abc123 |   123   |   6    |   1  |    1   |    1   |    0
abc123 |   124   |   6    |   1  |    1   |    1   |    0
abc123 |   125   |   6    |   2  |    1   |    1   |    0
abc123 |   126   |   6    |   1  |    1   |    1   |    0
------------------------------------------------------------
abc123 |   123   |   7    |   2  |    1   |    1   |    1
abc123 |   124   |   7    |   1  |    1   |    1   |    1
abc123 |   125   |   7    |   2  |    1   |    1   |    1
abc123 |   126   |   7    |   1  |    1   |    1   |    1
------------------------------------------------------------
abc123 |   123   |   8    |   2  |    1   |    0   |    1
abc123 |   124   |   8    |   1  |    1   |    0   |    1
abc123 |   125   |   8    |   2  |    1   |    0   |    1
abc123 |   126   |   8    |   2  |    1   |    0   |    1
------------------------------------------------------------
def321 |   127   |   5    |   1  |    1   |    0   |    0
def321 |   128   |   5    |   1  |    1   |    0   |    0
def321 |   129   |   5    |   2  |    1   |    0   |    0
def321 |   130   |   5    |   0  |    1   |    0   |    0
------------------------------------------------------------
def321 |   127   |   6    |   0  |    1   |    1   |    0
def321 |   128   |   6    |   2  |    1   |    1   |    0
def321 |   129   |   6    |   2  |    1   |    1   |    0
def321 |   130   |   6    |   1  |    1   |    1   |    0
------------------------------------------------------------
def321 |   127   |   7    |   1  |    1   |    1   |    1
def321 |   128   |   7    |   1  |    1   |    1   |    1
def321 |   129   |   7    |   2  |    1   |    1   |    1
def321 |   130   |   7    |   2  |    1   |    1   |    1
------------------------------------------------------------
def321 |   127   |   8    |   2  |    1   |    0   |    1
def321 |   128   |   8    |   2  |    1   |    0   |    1
def321 |   129   |   8    |   2  |    1   |    0   |    1
def321 |   130   |   8    |   2  |    1   |    0   |    1
</code>```

Desired Result:

```<code>arenaId | tVotes0 | tVotes1 | tVotes2 | aVotes0 | aVotes1 | aVotes2 | bVotes0 | bVotes1 | bVotes2
-------------------------------------------------------------------------------------------------------------
abc123  |    1    |    8    |    7    |    0    |    5    |    3    |    0    |    3    |    5
def321  |    2    |    5    |    9    |    1    |    3    |    4    |    0    |    2    |    6
</code>```

tVotes is the total votes, not taking into account what group the user is in. So tVotes0 = total votes of value 0, tVotes1 = total votes of value 1, tVotes2 = total votes of value 2. aVotes are just the votes cast by users who belong in groupA. bVotes are just the votes of users who belong in groupB

So the value in the desired results view, the row with arenaId abc123 has a value of 1 for tVotes0 means there was a total count of 1 vote with a value of 0 within that arena. The reason aVotes0 and bVotes0 are 0 is because the user who cast the vote with value 0 was not part of either group A or B.

I can get the result only if I specify an arenaId, doing something like the query below:

```<code>SELECT (
         SELECT COUNT(eventId) AS voteCount
         FROM (
                SELECT eventId
                FROM Votes
                WHERE arenaId = 'abc123'
                      AND active = 1
                      AND vote = 1
                AND groupA = 1
                GROUP BY userId, eventId
              ) AS t1
       ) AS aVotes1
</code>```

But I'd like to get a result where I can see all the vote summaries per arena:

Thank you all so much in advance!

答:
```<code>SELECT
    arenaId
    ,COUNT(DISTINCT eventId) as NumberOfEvents
    ,COUNT(CASE WHEN vote = 0 THEN 1 END) as tVotes0
    ,COUNT(CASE WHEN vote = 1 THEN 1 END) as tVotes1
    ,COUNT(CASE WHEN vote = 2 THEN 1 END) as tVotes2
    ,COUNT(CASE WHEN vote = 0 AND groupA = 1 THEN 1 END) as aVotes0
    ,COUNT(CASE WHEN vote = 1 AND groupA = 1 THEN 1 END) as aVotes1
    ,COUNT(CASE WHEN vote = 2 AND groupA = 1 THEN 1 END) as aVotes2
    ,COUNT(CASE WHEN vote = 0 AND groupB = 1 THEN 1 END) as aVotes0
    ,COUNT(CASE WHEN vote = 1 AND groupB = 1 THEN 1 END) as aVotes1
    ,COUNT(CASE WHEN vote = 2 AND groupB = 1 THEN 1 END) as aVotes2
FROM
    Votes
WHERE
    active = 1
GROUP BY
    arenaId
</code>```

It really seems like you are more looking to PIVOT the data.  There are a few ways you could do that but instead of preparing and then pivoting you can just do it as a single operation using CONDITIONAL AGGREGATION.

If you actually have multiple tables involved as I suspect then you could just use the technique with joins.

Here is the example in action so you can see the results: http://rextester.com/SZGGR60834

Body:
I'm pretty new to SQL and am hitting a wall and would really appreciate any help!

I'm using SQL Server in Azure. I have a table called Votes that has the columns:

arenaId

eventId

userId

vote

active

groupA

groupB

In here, I've got multiple users voting on various events (eventId) which are part of various arenas (arenaId).  The user can belong to either/both/none of groupA,and groupB.  The vote column can have a value of 0,1,2. The active column filters out which vote to count as each user can only cast a single vote per eventId. So if they cast multiple votes, all subsequent votes will have active=0 and the latest will have active=1

Each arena would have multiple events associated with it, but the event is unique to a specific arena.

My goal is to be able to count the types of votes per arena per group.

Sample Table Setup:

arenaId | eventId | userId | vote | active | groupA | groupB
------------------------------------------------------------
abc123 |   123   |   5    |   0  |    1   |    0   |    0
abc123 |   124   |   5    |   2  |    1   |    0   |    0
abc123 |   125   |   5    |   1  |    1   |    0   |    0
abc123 |   126   |   5    |   1  |    1   |    0   |    0
------------------------------------------------------------
abc123 |   123   |   6    |   1  |    1   |    1   |    0
abc123 |   124   |   6    |   1  |    1   |    1   |    0
abc123 |   125   |   6    |   2  |    1   |    1   |    0
abc123 |   126   |   6    |   1  |    1   |    1   |    0
------------------------------------------------------------
abc123 |   123   |   7    |   2  |    1   |    1   |    1
abc123 |   124   |   7    |   1  |    1   |    1   |    1
abc123 |   125   |   7    |   2  |    1   |    1   |    1
abc123 |   126   |   7    |   1  |    1   |    1   |    1
------------------------------------------------------------
abc123 |   123   |   8    |   2  |    1   |    0   |    1
abc123 |   124   |   8    |   1  |    1   |    0   |    1
abc123 |   125   |   8    |   2  |    1   |    0   |    1
abc123 |   126   |   8    |   2  |    1   |    0   |    1
------------------------------------------------------------
def321 |   127   |   5    |   1  |    1   |    0   |    0
def321 |   128   |   5    |   1  |    1   |    0   |    0
def321 |   129   |   5    |   2  |    1   |    0   |    0
def321 |   130   |   5    |   0  |    1   |    0   |    0
------------------------------------------------------------
def321 |   127   |   6    |   0  |    1   |    1   |    0
def321 |   128   |   6    |   2  |    1   |    1   |    0
def321 |   129   |   6    |   2  |    1   |    1   |    0
def321 |   130   |   6    |   1  |    1   |    1   |    0
------------------------------------------------------------
def321 |   127   |   7    |   1  |    1   |    1   |    1
def321 |   128   |   7    |   1  |    1   |    1   |    1
def321 |   129   |   7    |   2  |    1   |    1   |    1
def321 |   130   |   7    |   2  |    1   |    1   |    1
------------------------------------------------------------
def321 |   127   |   8    |   2  |    1   |    0   |    1
def321 |   128   |   8    |   2  |    1   |    0   |    1
def321 |   129   |   8    |   2  |    1   |    0   |    1
def321 |   130   |   8    |   2  |    1   |    0   |    1

Desired Result:

arenaId | tVotes0 | tVotes1 | tVotes2 | aVotes0 | aVotes1 | aVotes2 | bVotes0 | bVotes1 | bVotes2
-------------------------------------------------------------------------------------------------------------
abc123  |    1    |    8    |    7    |    0    |    5    |    3    |    0    |    3    |    5
def321  |    2    |    5    |    9    |    1    |    3    |    4    |    0    |    2    |    6

tVotes is the total votes, not taking into account what group the user is in. So tVotes0 = total votes of value 0, tVotes1 = total votes of value 1, tVotes2 = total votes of value 2. aVotes are just the votes cast by users who belong in groupA. bVotes are just the votes of users who belong in groupB

So the value in the desired results view, the row with arenaId abc123 has a value of 1 for tVotes0 means there was a total count of 1 vote with a value of 0 within that arena. The reason aVotes0 and bVotes0 are 0 is because the user who cast the vote with value 0 was not part of either group A or B.

I can get the result only if I specify an arenaId, doing something like the query below:

SELECT (
         SELECT COUNT(eventId) AS voteCount
         FROM (
                SELECT eventId
                FROM Votes
                WHERE arenaId = 'abc123'
                      AND active = 1
                      AND vote = 1
                AND groupA = 1
                GROUP BY userId, eventId
              ) AS t1
       ) AS aVotes1

But I'd like to get a result where I can see all the vote summaries per arena:

Thank you all so much in advance!

Body:
SELECT
    arenaId
    ,COUNT(DISTINCT eventId) as NumberOfEvents
    ,COUNT(CASE WHEN vote = 0 THEN 1 END) as tVotes0
    ,COUNT(CASE WHEN vote = 1 THEN 1 END) as tVotes1
    ,COUNT(CASE WHEN vote = 2 THEN 1 END) as tVotes2
    ,COUNT(CASE WHEN vote = 0 AND groupA = 1 THEN 1 END) as aVotes0
    ,COUNT(CASE WHEN vote = 1 AND groupA = 1 THEN 1 END) as aVotes1
    ,COUNT(CASE WHEN vote = 2 AND groupA = 1 THEN 1 END) as aVotes2
    ,COUNT(CASE WHEN vote = 0 AND groupB = 1 THEN 1 END) as aVotes0
    ,COUNT(CASE WHEN vote = 1 AND groupB = 1 THEN 1 END) as aVotes1
    ,COUNT(CASE WHEN vote = 2 AND groupB = 1 THEN 1 END) as aVotes2
FROM
    Votes
WHERE
    active = 1
GROUP BY
    arenaId

It really seems like you are more looking to PIVOT the data.  There are a few ways you could do that but instead of preparing and then pivoting you can just do it as a single operation using CONDITIONAL AGGREGATION.

If you actually have multiple tables involved as I suspect then you could just use the technique with joins.

Here is the example in action so you can see the results: http://rextester.com/SZGGR60834


问:
How can i print a multi line code with built in variables?
Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know.</p>

```<code>def radar():
    measures = {}
    angle = 18
    servo(0)
    for x in range(9):
        servo(angle)
        dist = distance()
        measures[angle] = dist
        angle += 18

    for number in measures:
        if number < min_distance:
            print('Too close!', number)
            can_move_forward = False

def visual_radar():

    print """
                     %f              %f
           %f                                %f

       %f                                       %f

    """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54]))

radar()
visual_radar()
</code>```

答:
As said by Verv earlier, your error comes from multiple % after the last " inside your print function.

I suggest you to try the pair "{} .format" in your print or when you construct a string variable, a path and so.

It is according to me a generalization of the % because you don't have to know precisely what is the type of your variable.

To give you a simple example of how to use it :

```<code>a = [i**2 for i in xrange(4)]
print ("{}".format(a)) # ints
>>> [0, 1, 4, 9]

a.append("s") # string
a.append(2.4) # float
print "{}, {}".format(a[-1], a[-2])
>>> 's', 2.4
</code>```

Here again you only have to write .format once and near the last " and to match the number of {} with the number of elements you put in the .format()

I hope this will be useful

Body:
Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know.

def radar():
    measures = {}
    angle = 18
    servo(0)
    for x in range(9):
        servo(angle)
        dist = distance()
        measures[angle] = dist
        angle += 18

    for number in measures:
        if number < min_distance:
            print('Too close!', number)
            can_move_forward = False

def visual_radar():

    print """
                     %f              %f
           %f                                %f

       %f                                       %f

    """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54]))

radar()
visual_radar()

Body:
As said by Verv earlier, your error comes from multiple % after the last " inside your print function.

I suggest you to try the pair "{} .format" in your print or when you construct a string variable, a path and so.

It is according to me a generalization of the % because you don't have to know precisely what is the type of your variable.

To give you a simple example of how to use it :

a = [i**2 for i in xrange(4)]
print ("{}".format(a)) # ints
>>> [0, 1, 4, 9]

a.append("s") # string
a.append(2.4) # float
print "{}, {}".format(a[-1], a[-2])
>>> 's', 2.4

Here again you only have to write .format once and near the last " and to match the number of {} with the number of elements you put in the .format()

I hope this will be useful


答:
```<code>Reduce(intersect, data.frame(t(all)))
# [1]  1  5 12 13 18
</code>```

No extra dependencies needed!

Title: find intersect by rows in r

Body:
Reduce(intersect, data.frame(t(all)))
# [1]  1  5 12 13 18

No extra dependencies needed!


问:
How to most correctly work with Interfaces?
Is this code correct as a pattern? Which way is better, like this or via Parent class Message.

Or is it better to use only 3 classes and 1 Interface? Where I type something like:

INotification Notify = new SystemMessage();

```<code>public interface INotification { void ShowNotification(String text); }

    class Message : INotification
    {
        static internal Message CurrentMessageType { get; set; }
        public virtual void ShowNotification(string text) {
            if (CurrentMessageType == null) CurrentMessageType = new SystemMessage();
        }
    }

    class SystemMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("SYSTEM: " + text);
        }
    }

    class ConsoleMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("CONSOLE: " + text);
        }
    }

    class NotifyMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("NOTIFY: " + text);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.Write("MSG: ");
                String rsp = Console.ReadLine();
                switch (rsp)
                {
                    case "sys":
                        Message.CurrentMessageType = new SystemMessage();
                        break;
                    case "con":
                        Message.CurrentMessageType = new ConsoleMessage();
                        break;
                    case "not":
                        Message.CurrentMessageType = new NotifyMessage();
                        break;
                    case "exit":
                        return;
                }

                Message.CurrentMessageType.ShowNotification("test message");

            }
        }
    }
</code>```

答:
I don't see why you need that interface INotification at all. Rather you have a class hierarchy or inheritance relationship here and in such case having Message as your abstract base class would probably suffice all

```<code>public abstract class Message
{
    static internal Message CurrentMessageType { get; set; }
    public virtual void ShowNotification(string text) {
        if (CurrentMessageType == null)
               CurrentMessageType = new SystemMessage();
    }
}
</code>```

Per your comment: am not here to argue what's better but you should go by OOP concept I believe. Thus you should use class hierarchy if there exists some relationship between your classes. If not, then using interface would be good and in that case you would say that all those classes provide a similar kind of functionality with different implementation may be but they may not be related.

Body:
Is this code correct as a pattern? Which way is better, like this or via Parent class Message.

Or is it better to use only 3 classes and 1 Interface? Where I type something like:

INotification Notify = new SystemMessage();

public interface INotification { void ShowNotification(String text); }

    class Message : INotification
    {
        static internal Message CurrentMessageType { get; set; }
        public virtual void ShowNotification(string text) {
            if (CurrentMessageType == null) CurrentMessageType = new SystemMessage();
        }
    }

    class SystemMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("SYSTEM: " + text);
        }
    }

    class ConsoleMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("CONSOLE: " + text);
        }
    }

    class NotifyMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("NOTIFY: " + text);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.Write("MSG: ");
                String rsp = Console.ReadLine();
                switch (rsp)
                {
                    case "sys":
                        Message.CurrentMessageType = new SystemMessage();
                        break;
                    case "con":
                        Message.CurrentMessageType = new ConsoleMessage();
                        break;
                    case "not":
                        Message.CurrentMessageType = new NotifyMessage();
                        break;
                    case "exit":
                        return;
                }

                Message.CurrentMessageType.ShowNotification("test message");

            }
        }
    }

Body:
I don't see why you need that interface INotification at all. Rather you have a class hierarchy or inheritance relationship here and in such case having Message as your abstract base class would probably suffice all

public abstract class Message
{
    static internal Message CurrentMessageType { get; set; }
    public virtual void ShowNotification(string text) {
        if (CurrentMessageType == null)
               CurrentMessageType = new SystemMessage();
    }
}

Per your comment: am not here to argue what's better but you should go by OOP concept I believe. Thus you should use class hierarchy if there exists some relationship between your classes. If not, then using interface would be good and in that case you would say that all those classes provide a similar kind of functionality with different implementation may be but they may not be related.


问:
What is the best way to copy S3 bucket including all the versions
I am trying to copy S3 bucket's objects across region. My source bucket is having version enabled and I need my destination bucket should retain all the versions present in my source bucket(though I think we can't preserve the actual timestamp while copying). I would prefer to have some officially supported tool.

答:
Amazon S3 Cross-Region Replication (CRR) will do this for you. In fact, it requires versioning to be activated.

However, it will only take effect after it is activated. Any existing objects and versions will not be replicated.


问:
using getline() to input strings into the program is causing some kind of overflow into the next input
I am having a number of problems in my program that all have to do with input.
The first thing in the program I ask the user to input is their name which I do so with this

```<code>cout << "Please tell me your name." << endl;
getline(cin, user_name);
cout << "Hello " << user_name << " and welcome to Fantasy Battle!" << endl;
</code>```

where user_name is declared as a string variable elsewhere. This part seems to have no problems as the following message displays to the screen correctly

The next input from the user comes from this code

```<code>{
cout << "Hello, what would you like to do?" << endl;
cout << "1. Play" << endl << "2. Exit" << endl;
cout << "Please enter the number corresponding to your choice from the list
above." << endl;
for(;;)
{
    if(cin >> menuChoice)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(10000, '\n');
        }
        if(menuChoice == 1 || menuChoice == 2)
            break;
        else
        {
            cout << "You did not enter a valid menu option. Please try
            again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    else
    {
        cout << "You did not enter a valid menu option. Please try again."
        << endl;
        cin.clear();
        cin.ignore(100000, '\n');
    }
}
if(menuChoice == 2)
{
    return 2;
}
else
{
    //setup a fight code further down
}
</code>```

One the first run through if I enter 2 it will exit the program successfully from main or if  enter 1 it will run through the fight function. However, if I go through 1 fight and get back the program asking me to either enter 1 or 2 to play or exit, I can enter 2 infinite times and it will not exit the program. I am not sure what it causing this.

```<code>for(;;)
    {
        game = menu();
        if(game == 2)
        {
            break;
        }
        else
        {
            fight();
        }
     }
     return 0;
</code>```

The code inside the menu() function of my program is as follows and is where the rest of the input for my program is contained. I am using getline(cin, fighterName) to get a string from the user to use as a name for each character they want to create
The problem I am having is that it starts to just save the name of characters as empty without asking.

```<code>cout << "How many fighters should be on Team 1?" << endl;
//Input Validation
for(;;)
{
    if(cin.get() == '.')
    {
        cin.clear();
        cin.ignore(100000, '\n');
    }
    if(cin >> team1Size)
    {
        if(team1Size <= 0)
        {
            cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
        else
        {
            break;
        }
    }
    else
    {
        cout << "You did not enter a valid number. Please try again." << endl;
           cin.clear();
            cin.ignore(100000, '\n');
    }
}

cout << "How many fighters should be on Team 2?" << endl;
//Input Validation
for(;;)
{
    if(cin.get() == '.')
    {
        cin.clear();
        cin.ignore(100000, '\n');
    }
    if(cin >> team2Size)
    {
        if(team2Size <= 0)
        {
            cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
        else
        {
            break;
        }
    }
    else
    {
        cout << "You did not enter a valid number. Please try again." << endl;
           cin.clear();
            cin.ignore(100000, '\n');
    }
}

//Set up team 1
cout << "Begin setup for team 1:" << endl << endl;
for(int i = 0; i < team1Size; i++)
{
    cout << "Which character type should fighter " << i+1 << " be?" << endl;
    cout << "1. Barbarian" << endl;
    cout << "2. BlueMen" << endl;
    cout << "3. Vampire" << endl;
    cout << "4. Medusa" << endl;
    cout << "5. Harry Potter" << endl;
    cout << "Please enter the number corresponding to your choice from the list above." << endl;
    for(;;)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(100000, '\n');
        }
        if(cin >> fighterType)
        {
            if(fighterType < 1 || fighterType > 5)
            {
                cout << "You did not enter a valid choice. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter a valid choice. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    //Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
    //representing team 1. We will do so by calling the add function of the linked list
    cout << "Please enter the name of this fighter." << endl;
    getline(cin, fighterName);
    if(fighterType == 1)
    {
        team1.addBack("Barbarian", fighterName);
    }
    else if(fighterType == 2)
    {
        team1.addBack("BlueMen", fighterName);
    }
    else if(fighterType == 3)
    {
        team1.addBack("Vampire", fighterName);
    }
    else if(fighterType == 4)
    {
        team1.addBack("Medusa", fighterName);
    }
    else
    {
        team1.addBack("HarryPotter", fighterName);
    }

}

cout << "Team 1 has been created!" << endl << endl;

//Set up team 2
cout << "Begin setup for team 2:" << endl << endl;
for(int i = 0; i < team2Size; i++)
{
    cout << "Which character type should fighter " << i+1 << " be?" << endl;
    cout << "1. Barbarian" << endl;
    cout << "2. BlueMen" << endl;
    cout << "3. Vampire" << endl;
    cout << "4. Medusa" << endl;
    cout << "5. Harry Potter" << endl;
    cout << "Please enter the number corresponding to your choice from the list above." << endl;
    for(;;)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(100000, '\n');
        }
        if(cin >> fighterType)
        {
            if(fighterType < 1 || fighterType > 5)
            {
                cout << "You did not enter a valid choice. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter a valid choice. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    //Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
    //representing team 2. We will do so by calling the add function of the linked list
    cout << "Please enter the name of this fighter." << endl;
    getline(cin, fighterName);
    if(fighterType == 1)
    {
        team2.addBack("Barbarian", fighterName);
    }
    else if(fighterType == 2)
    {
        team2.addBack("BlueMen", fighterName);
    }
    else if(fighterType == 3)
    {
        team2.addBack("Vampire", fighterName);
    }
    else if(fighterType == 4)
    {
        team2.addBack("Medusa", fighterName);
    }
    else
    {
        team2.addBack("HarryPotter", fighterName);
    }
}

cout << "Team 2 has been created!" << endl << endl;

cout << "Let the fight begin!" << endl << endl;

return 0;
</code>```

}

The final piece of input from my code is the following which simply asks the user to enter a character either y or n and then executes a function if y is entered.

```<code>cout << "Would you like to see the contents of the loserPile?" << endl;
    cout << "Please enter y for yes or n for no" << endl;
    for(;;)
    {
        if(cin >> displayLosers)
        {
            if(displayLosers != 'y' && displayLosers != 'n')
            {
                cout << "You did not enter either y or n. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter either y or n. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    if(displayLosers == 'y')
    {
        losers.displayPile();
    }
</code>```

If someone could point out where I am making the error in obtaining user input I would appreciate it as I am running out of things to try that I know of.

答:
You are creating a lot of problems by adding if(cin.get() == '.')

The >> operator will convert the input string "1." to 1, and if you call ignore(...,'\n') the . and any other characters before \n will be ignored. Test for if(cin >> number){...} is also not necessary. You can initialize the value to -1 to indicate an error:

```<code>int menuChoice;
for(;;)
{
    menuChoice = -1;
    cin >> menuChoice;
    cout << menuChoice;
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    if(menuChoice == 1 || menuChoice == 2)
    {
        cout << menuChoice << "\n";
        break;
    }
    cout << "You did not enter a valid menu option. Please try again." << endl;
}
</code>```

Just make sure you are using the right input. For Yes or No option the input should be char:

```<code>cout << "enter y or n\n";
for(;;)
{
    char val;
    cin >> val;
    if(val != 'y' && val != 'n')
    {
        cout << "You did not enter either y or n. Please try again." << endl;
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    else
        break;
}
</code>```

Body:
I am having a number of problems in my program that all have to do with input.
The first thing in the program I ask the user to input is their name which I do so with this

cout << "Please tell me your name." << endl;
getline(cin, user_name);
cout << "Hello " << user_name << " and welcome to Fantasy Battle!" << endl;

where user_name is declared as a string variable elsewhere. This part seems to have no problems as the following message displays to the screen correctly

The next input from the user comes from this code

{
cout << "Hello, what would you like to do?" << endl;
cout << "1. Play" << endl << "2. Exit" << endl;
cout << "Please enter the number corresponding to your choice from the list
above." << endl;
for(;;)
{
    if(cin >> menuChoice)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(10000, '\n');
        }
        if(menuChoice == 1 || menuChoice == 2)
            break;
        else
        {
            cout << "You did not enter a valid menu option. Please try
            again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    else
    {
        cout << "You did not enter a valid menu option. Please try again."
        << endl;
        cin.clear();
        cin.ignore(100000, '\n');
    }
}
if(menuChoice == 2)
{
    return 2;
}
else
{
    //setup a fight code further down
}

One the first run through if I enter 2 it will exit the program successfully from main or if  enter 1 it will run through the fight function. However, if I go through 1 fight and get back the program asking me to either enter 1 or 2 to play or exit, I can enter 2 infinite times and it will not exit the program. I am not sure what it causing this.

for(;;)
    {
        game = menu();
        if(game == 2)
        {
            break;
        }
        else
        {
            fight();
        }
     }
     return 0;

The code inside the menu() function of my program is as follows and is where the rest of the input for my program is contained. I am using getline(cin, fighterName) to get a string from the user to use as a name for each character they want to create
The problem I am having is that it starts to just save the name of characters as empty without asking.

cout << "How many fighters should be on Team 1?" << endl;
//Input Validation
for(;;)
{
    if(cin.get() == '.')
    {
        cin.clear();
        cin.ignore(100000, '\n');
    }
    if(cin >> team1Size)
    {
        if(team1Size <= 0)
        {
            cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
        else
        {
            break;
        }
    }
    else
    {
        cout << "You did not enter a valid number. Please try again." << endl;
           cin.clear();
            cin.ignore(100000, '\n');
    }
}

cout << "How many fighters should be on Team 2?" << endl;
//Input Validation
for(;;)
{
    if(cin.get() == '.')
    {
        cin.clear();
        cin.ignore(100000, '\n');
    }
    if(cin >> team2Size)
    {
        if(team2Size <= 0)
        {
            cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
        else
        {
            break;
        }
    }
    else
    {
        cout << "You did not enter a valid number. Please try again." << endl;
           cin.clear();
            cin.ignore(100000, '\n');
    }
}

//Set up team 1
cout << "Begin setup for team 1:" << endl << endl;
for(int i = 0; i < team1Size; i++)
{
    cout << "Which character type should fighter " << i+1 << " be?" << endl;
    cout << "1. Barbarian" << endl;
    cout << "2. BlueMen" << endl;
    cout << "3. Vampire" << endl;
    cout << "4. Medusa" << endl;
    cout << "5. Harry Potter" << endl;
    cout << "Please enter the number corresponding to your choice from the list above." << endl;
    for(;;)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(100000, '\n');
        }
        if(cin >> fighterType)
        {
            if(fighterType < 1 || fighterType > 5)
            {
                cout << "You did not enter a valid choice. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter a valid choice. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    //Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
    //representing team 1. We will do so by calling the add function of the linked list
    cout << "Please enter the name of this fighter." << endl;
    getline(cin, fighterName);
    if(fighterType == 1)
    {
        team1.addBack("Barbarian", fighterName);
    }
    else if(fighterType == 2)
    {
        team1.addBack("BlueMen", fighterName);
    }
    else if(fighterType == 3)
    {
        team1.addBack("Vampire", fighterName);
    }
    else if(fighterType == 4)
    {
        team1.addBack("Medusa", fighterName);
    }
    else
    {
        team1.addBack("HarryPotter", fighterName);
    }

}

cout << "Team 1 has been created!" << endl << endl;

//Set up team 2
cout << "Begin setup for team 2:" << endl << endl;
for(int i = 0; i < team2Size; i++)
{
    cout << "Which character type should fighter " << i+1 << " be?" << endl;
    cout << "1. Barbarian" << endl;
    cout << "2. BlueMen" << endl;
    cout << "3. Vampire" << endl;
    cout << "4. Medusa" << endl;
    cout << "5. Harry Potter" << endl;
    cout << "Please enter the number corresponding to your choice from the list above." << endl;
    for(;;)
    {
        if(cin.get() == '.')
        {
            cin.clear();
            cin.ignore(100000, '\n');
        }
        if(cin >> fighterType)
        {
            if(fighterType < 1 || fighterType > 5)
            {
                cout << "You did not enter a valid choice. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter a valid choice. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    //Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
    //representing team 2. We will do so by calling the add function of the linked list
    cout << "Please enter the name of this fighter." << endl;
    getline(cin, fighterName);
    if(fighterType == 1)
    {
        team2.addBack("Barbarian", fighterName);
    }
    else if(fighterType == 2)
    {
        team2.addBack("BlueMen", fighterName);
    }
    else if(fighterType == 3)
    {
        team2.addBack("Vampire", fighterName);
    }
    else if(fighterType == 4)
    {
        team2.addBack("Medusa", fighterName);
    }
    else
    {
        team2.addBack("HarryPotter", fighterName);
    }
}

cout << "Team 2 has been created!" << endl << endl;

cout << "Let the fight begin!" << endl << endl;

return 0;

}

The final piece of input from my code is the following which simply asks the user to enter a character either y or n and then executes a function if y is entered.

cout << "Would you like to see the contents of the loserPile?" << endl;
    cout << "Please enter y for yes or n for no" << endl;
    for(;;)
    {
        if(cin >> displayLosers)
        {
            if(displayLosers != 'y' && displayLosers != 'n')
            {
                cout << "You did not enter either y or n. Please try again." << endl;
                cin.clear();
                cin.ignore(100000, '\n');
            }
            else
                break;
        }
        else
        {
            cout << "You did not enter either y or n. Please try again." << endl;
            cin.clear();
            cin.ignore(100000, '\n');
        }
    }
    if(displayLosers == 'y')
    {
        losers.displayPile();
    }

If someone could point out where I am making the error in obtaining user input I would appreciate it as I am running out of things to try that I know of.

Body:
You are creating a lot of problems by adding if(cin.get() == '.')

The >> operator will convert the input string "1." to 1, and if you call ignore(...,'\n') the . and any other characters before \n will be ignored. Test for if(cin >> number){...} is also not necessary. You can initialize the value to -1 to indicate an error:

int menuChoice;
for(;;)
{
    menuChoice = -1;
    cin >> menuChoice;
    cout << menuChoice;
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    if(menuChoice == 1 || menuChoice == 2)
    {
        cout << menuChoice << "\n";
        break;
    }
    cout << "You did not enter a valid menu option. Please try again." << endl;
}

Just make sure you are using the right input. For Yes or No option the input should be char:

cout << "enter y or n\n";
for(;;)
{
    char val;
    cin >> val;
    if(val != 'y' && val != 'n')
    {
        cout << "You did not enter either y or n. Please try again." << endl;
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    else
        break;
}


问:
parseException in pyspark
I have a pyspark code that is written which reads three JSON files and converts the JSON files to DataFrames and the DataFrames are converted to tables on which SQL queries are performed.

```<code>    import pyspark.sql
    from pyspark.sql import SparkSession
    from pyspark.sql import SQLContext
    from pyspark.sql import *
    from pyspark.sql import Row
    import json
    from pyspark.sql.types import StructType, StructField, StringType
    from pyspark.sql.types import *

    spark = SparkSession \
    .builder \
    .appName("project") \
    .getOrCreate()
    sc = spark.sparkContext
    sqlContext=SQLContext(sc)

reviewFile= sqlContext.read.json("review.json")
usersFile=sqlContext.read.json("user.json")
businessFile=sqlContext.read.json("business.json")
reviewFile.createOrReplaceTempView("review")
usersFile.createOrReplaceTempView("user")
businessFile.createOrReplaceTempView("business")
review_user = spark.sql("select r.review_id,r.user_id,r.business_id,r.stars,r.date,u.name,u.review_count,u.yelping_since from (review r join user u on r.user_id = u.user_id)")
review_user.createOrReplaceTempView("review_user")
review_user_business= spark.sql("select r.review_id,r.user_id,r.business_id,r.stars,r.date,r.name,r.review_count,r.yelping_since,b.address,b.categories,b.city,b.latitude,b.longitude,b.name,b.neighborhood,b.postal_code,b.review_count,b.stars,b.state from review_user r join business b on r.business_id= b.business_id")
review_user_business.createOrReplaceTempView("review_user_business")
#categories= spark.sql("select distinct(categories) from review_user_business")
categories= spark.sql("select distinct(r.categories) from review_user_business r where 'Food' in r.categories")

print categories.show(50)
</code>```

You guys can find the description of the data in the below link.
    https://www.yelp.com/dataset/documentation/json

What I'm trying to do is get the rows which has food as a part of its category.
Can some one help me with it??

答:
When using expression A in B in pyspark A should be a column object not a constant value.

What you are looking for is array_contains:

categories= spark.sql("select distinct(r.categories) from review_user_business r \
                      where array_contains(r.categories, 'Food')")
```

Title: parseException in pyspark

Body:
I have a pyspark code that is written which reads three JSON files and converts the JSON files to DataFrames and the DataFrames are converted to tables on which SQL queries are performed.

    import pyspark.sql
    from pyspark.sql import SparkSession
    from pyspark.sql import SQLContext
    from pyspark.sql import *
    from pyspark.sql import Row
    import json
    from pyspark.sql.types import StructType, StructField, StringType
    from pyspark.sql.types import *

    spark = SparkSession \
    .builder \
    .appName("project") \
    .getOrCreate()
    sc = spark.sparkContext
    sqlContext=SQLContext(sc)

reviewFile= sqlContext.read.json("review.json")
usersFile=sqlContext.read.json("user.json")
businessFile=sqlContext.read.json("business.json")
reviewFile.createOrReplaceTempView("review")
usersFile.createOrReplaceTempView("user")
businessFile.createOrReplaceTempView("business")
review_user = spark.sql("select r.review_id,r.user_id,r.business_id,r.stars,r.date,u.name,u.review_count,u.yelping_since from (review r join user u on r.user_id = u.user_id)")
review_user.createOrReplaceTempView("review_user")
review_user_business= spark.sql("select r.review_id,r.user_id,r.business_id,r.stars,r.date,r.name,r.review_count,r.yelping_since,b.address,b.categories,b.city,b.latitude,b.longitude,b.name,b.neighborhood,b.postal_code,b.review_count,b.stars,b.state from review_user r join business b on r.business_id= b.business_id")
review_user_business.createOrReplaceTempView("review_user_business")
#categories= spark.sql("select distinct(categories) from review_user_business")
categories= spark.sql("select distinct(r.categories) from review_user_business r where 'Food' in r.categories")

print categories.show(50)

You guys can find the description of the data in the below link.
    https://www.yelp.com/dataset/documentation/json

What I'm trying to do is get the rows which has food as a part of its category.
Can some one help me with it??


问:
Mulesoft MMC Deployment unreconciled
We have a cluster server for MuleSoft. All the applications are deployed correctly and working perfectly but the deployments are showing in red on on-premise MMC. </p>

<p>Each deployment says "Deployment unreconciled" when hover over the deployment. Mule_ee.logs doesn't give anything specific. Where could I find the logs to see why is MMC giving this message. </p>

答:
Which version of Mule MMC you are using - we had the same issue where MuleSoft suggested to upgrade the MMC to the latest version ie 3.8.2. This seems to be a known bug in the MMC version 3.5.2.

The deployment showing red because of the following reasons -
- Servers are shown as down in MMC but they're up and running.
- Alerts for server down are triggered even though the server was never down.
- Any operation over the servers is throwing an error as they're detected as being down.
- Applications may appear as offline when they're actually deployed.

Most of the above listed problems are caused by problems in the network that communicates MMC with the Mule instances. MMC does a ping over the instances which is in charge of updating the servers statuses. In order to avoid the mentioned problems, the frequency of the ping can be changed so it allows the tweaking for a value that suits the current network.

In order to do this you need to the edit the file /WEB-INF/classes/META-INF/applicationContext.xml and modify the bean with id="pinger" to include a new constructor argument of type int (last argument). The value will define the socket timeout of the server status call. Value is expressed in ms-

```<code><bean id="pinger" class="com.mulesoft.mmc.heartbeat.Pinger">
  <constructor-arg ref="serverManager" />
  <constructor-arg ref="statusServiceAdaptor" />
  <constructor-arg ref="eventManager" />
  <constructor-arg ref="pingServerExecutor" />
  <constructor-arg type="int"><value>10000</value></constructor-arg>
</bean>
</code>```

After making this change, please restart MMC and check if the servers still experience the same problem.

Note: the default value of the ping is 1000 (one second) for MMC version 3.6.x and 5000 for MMC 3.7.x.

Regards,
Sanjeet Pandey

Title: Mulesoft MMC Deployment unreconciled

Body:
We have a cluster server for MuleSoft. All the applications are deployed correctly and working perfectly but the deployments are showing in red on on-premise MMC.

Each deployment says "Deployment unreconciled" when hover over the deployment. Mule_ee.logs doesn't give anything specific. Where could I find the logs to see why is MMC giving this message.

Body:
Which version of Mule MMC you are using - we had the same issue where MuleSoft suggested to upgrade the MMC to the latest version ie 3.8.2. This seems to be a known bug in the MMC version 3.5.2.

The deployment showing red because of the following reasons -
- Servers are shown as down in MMC but they're up and running.
- Alerts for server down are triggered even though the server was never down.
- Any operation over the servers is throwing an error as they're detected as being down.
- Applications may appear as offline when they're actually deployed.

Most of the above listed problems are caused by problems in the network that communicates MMC with the Mule instances. MMC does a ping over the instances which is in charge of updating the servers statuses. In order to avoid the mentioned problems, the frequency of the ping can be changed so it allows the tweaking for a value that suits the current network.

In order to do this you need to the edit the file /WEB-INF/classes/META-INF/applicationContext.xml and modify the bean with id="pinger" to include a new constructor argument of type int (last argument). The value will define the socket timeout of the server status call. Value is expressed in ms-

<bean id="pinger" class="com.mulesoft.mmc.heartbeat.Pinger">
  <constructor-arg ref="serverManager" />
  <constructor-arg ref="statusServiceAdaptor" />
  <constructor-arg ref="eventManager" />
  <constructor-arg ref="pingServerExecutor" />
  <constructor-arg type="int"><value>10000</value></constructor-arg>
</bean>

After making this change, please restart MMC and check if the servers still experience the same problem.

Note: the default value of the ping is 1000 (one second) for MMC version 3.6.x and 5000 for MMC 3.7.x.

Regards,
Sanjeet Pandey


问:
Calculate Scala average
I need to calculate the average of three ages in Scala. I have tried the method shown below, but it did not work. Please help.</p>

```<code>sealed abstract class Component
case class Life (age:Int) extends Component

object Life extends Component{
  def main(args: Array[String]){
    val lives = List{Life(10), Life(20), Life(30)}
    def livesMean (l:List[Life]):Double = {
        println(livesMean)
    }
  }
}
</code>```

答:
The syntax you're using to create lives isn't valid.  This should work:

```<code>abstract class Component

case class Life(age: Int) extends Component

object Life extends Component {
    def main(args: Array[String]) {
        val lives = List(new Life(10), new Life(20), new Life(30))
        val livesMean: Double = lives.map(_.age).sum / lives.size
        println(livesMean) // 20.0
    }
}
</code>```

Scala fiddle: https://scalafiddle.io/sf/Lyu9VRf/0

Title: Calculate Scala average

Body:
I need to calculate the average of three ages in Scala. I have tried the method shown below, but it did not work. Please help.

sealed abstract class Component
case class Life (age:Int) extends Component

object Life extends Component{
  def main(args: Array[String]){
    val lives = List{Life(10), Life(20), Life(30)}
    def livesMean (l:List[Life]):Double = {
        println(livesMean)
    }
  }
}

Body:
The syntax you're using to create lives isn't valid.  This should work:

abstract class Component

case class Life(age: Int) extends Component

object Life extends Component {
    def main(args: Array[String]) {
        val lives = List(new Life(10), new Life(20), new Life(30))
        val livesMean: Double = lives.map(_.age).sum / lives.size
        println(livesMean) // 20.0
    }
}

Scala fiddle: https://scalafiddle.io/sf/Lyu9VRf/0