问:
Algorithm not showing right output
The Question was:

You are given a binary matrix (i.e. each element of matrix is either 0 or 1) of size n × n. You want to re-arrange 1's in such a way that they form a rectangular region. Note that the rectangular region should be made of only 1's, and all the 1's of the entire matrix should be in this rectangular region.

For achieving rectangular region, you can swap any two elements of the matrix. Please find out the minimum number of swaps needed. If it is not possible to re-arrange 1's in the desired way, please print -1.

Input

First line of the input contains a single integer T denoting number of test cases.
Description of T test cases follows.
First line of each test case will contain a single integer n denoting dimension of matrix.
Each of next n lines will contain n space separated integers denoting the ith row of the matrix.

Output

For each test case, print a single line containing a single integer denoting minimum number of swaps needed or -1 depending on the situation.

Example

Input:

```<code>2

2

0 1

1 0

2

1 1

1 0
</code>```

Output:

```<code>1

-1
</code>```

Explanation

Example case 1. You can swap 1 of second row first column with 0 of first row first column.
After the swap, matrix will look as follows.

```<code>1 1
0 0
</code>```

Here all the 1's form a rectangular region of dimension 1 × 2. In this case, 1 swap will be needed.

Note that you can also swap 1 at first row second column with 0 at second row second column too.
Matrix after this swap will be following.

```<code>0 0
1 1
</code>```

So you need 1 swap in this case too.

So overall, you need 1 swap.

Example case 2. There is no way to create a rectangular region containing 3 1's in a matrix of dimension 2 × 2, hence answer is -1.

My Algorithm [Edit]

First i am Taking Number of Cases from user

Then the order of matrix [will be of nxn order].

So logic is that if matrix is 1x1 then it will simply print 0

else while taking input from user [that will be only 1 or 0] i am counting 1's because the logic i develop that when in a matrix of odd order the 1's will be even then it cannot be arranged in rectangular form.and for even order of matrix if 1's are odd , not arrange able .

Next i am traversing each index if i find one then i move to next element else i try to find 1 in the same colomn if dont find than i am breaking loop showing -1 that it is not arrange able in rectangular form

Than after arranging a row i check the next row whether it is already arranged or not if it is than i break everything and moves to next case

n rectangular form

My Solution

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    static long startTime;

    public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
            int numberOfOnes = 0;
            int T = scanner.nextInt();

            for (int t = 1; t <= T; t++) {
                int n = scanner.nextInt();

                int loopCounter, swapCounter = 0;
                boolean rowContainsZero = false;
                int array[][] = new int[n][n];
                boolean reject = true;
                //Worst and the most simpler conditions
                if (n == 1) {
                    System.out.print("0");
                    exitingSystem();
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        array[i][j] = scanner.nextInt();
                        if (array[i][j] == 1) {
                            numberOfOnes++;
                        }
                    }
                }
                if (n % 2 == 0 && numberOfOnes % 2 != 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;

                } else if (n % 2 != 0 && numberOfOnes % 2 == 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;
                }
                //     System.out.println("Here i am");
                //From here swaping processes will take the place
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (array[i][j] == 1) {
                            continue;
                        } else if (array[i][j] == 0) {
                            loopCounter = i;
                            reject = true;
                            while (loopCounter < n) {
                                if (array[loopCounter][j] == 1) {
                                    int temp = array[loopCounter][j];
                                    array[loopCounter][j] = array[i][j];
                                    array[i][j] = temp;
                                    reject = false;
                                    swapCounter += 1;
                                    break;
                                }
                                loopCounter++;
                            }
                             if (rowContainsZero) {
                                System.out.println("" + swapCounter);
                                    break;
                            }
                            if (reject == true) {
                                System.out.println("-1");
                                break;
                            } else {
                                for (int m = i + 1; m < n; m++) {
                                    for (int k = 0; k < n; k++) {
                                        if (array[m][k] == 0) {
                                            rowContainsZero = true;
                                        } else {
                                            rowContainsZero = false;
                                            break;
                                        }
                                    }
                                }
                            }

                        } else {
                            System.out.println("0's and 1's were Expected :(");
                            exitingSystem();
                        }
                    }
                    if (reject == true) {
                        break;
                    }
                }
            }

    }

    public static void exitingSystem() {
        System.exit(0);
    }

}
</code>```

BUT THE CODECHEF COMPUTER SAYING WRONG ANSWER + They allowed to take input from keyboard too

答:
This is not the way you are trying to solve problem. Suppose you have

```<code>                                                                 0 0 1
                                                                 0 1 1
                                                                 0 0 1
</code>```

This is a perfect example of solveable matrix but you can't simply use random swap and then acquire result. You need to use A* search algorithm with manhatten distance.

Make a priority queue

Define manhatten distance.

Create a function which creates succesors of each board. Like if i have above board then it will give you a collection of boards back:

0 0 1
 0 1 1 ==> colection
 0 0 1

0 1 1
 0 0 1
 0 0 1

0 0 1
 0 0 1
 0 1 1

0 1 0
 0 1 1
 0 0 1

0 0 1
 0 1 1
 0 1 0

Description of A:*

an initial lis to store visited boar so that you don't visit them again.

i will call MinPriority queue a pq

`insert the initial_board in pq

while(!pq.isEmpty() && !foundGoal(pq.min)) //You find goal when your
manhatten distance is 0.

board = pq.delMin(); //you have to override the distance method in
priority queue so it will return you that board whoms manhatten
distance is smallest.

for(boards b :board.getSuccesors(); // give you collection of boards.

if(notvisited(b,vistiedList)) // so that you don't come in same state again and
again.

pq.insert(b);
visitedList.add(b);`

In first year i had to solve 8-puzzle and you can solve this way however you can also use hamming distance but that's not efficient and here is 8-puzzle code(with A* implementation).

Title: Algorithm not showing right output

Body:
The Question was:

You are given a binary matrix (i.e. each element of matrix is either 0 or 1) of size n × n. You want to re-arrange 1's in such a way that they form a rectangular region. Note that the rectangular region should be made of only 1's, and all the 1's of the entire matrix should be in this rectangular region.

For achieving rectangular region, you can swap any two elements of the matrix. Please find out the minimum number of swaps needed. If it is not possible to re-arrange 1's in the desired way, please print -1.

Input

First line of the input contains a single integer T denoting number of test cases.
Description of T test cases follows.
First line of each test case will contain a single integer n denoting dimension of matrix.
Each of next n lines will contain n space separated integers denoting the ith row of the matrix.

Output

For each test case, print a single line containing a single integer denoting minimum number of swaps needed or -1 depending on the situation.

Example

Input:

2

2

0 1

1 0

2

1 1

1 0

Output:

1

-1

Explanation

Example case 1. You can swap 1 of second row first column with 0 of first row first column.
After the swap, matrix will look as follows.

1 1
0 0

Here all the 1's form a rectangular region of dimension 1 × 2. In this case, 1 swap will be needed.

Note that you can also swap 1 at first row second column with 0 at second row second column too.
Matrix after this swap will be following.

0 0
1 1

So you need 1 swap in this case too.

So overall, you need 1 swap.

Example case 2. There is no way to create a rectangular region containing 3 1's in a matrix of dimension 2 × 2, hence answer is -1.

My Algorithm [Edit]

First i am Taking Number of Cases from user

Then the order of matrix [will be of nxn order].

So logic is that if matrix is 1x1 then it will simply print 0

else while taking input from user [that will be only 1 or 0] i am counting 1's because the logic i develop that when in a matrix of odd order the 1's will be even then it cannot be arranged in rectangular form.and for even order of matrix if 1's are odd , not arrange able .

Next i am traversing each index if i find one then i move to next element else i try to find 1 in the same colomn if dont find than i am breaking loop showing -1 that it is not arrange able in rectangular form

Than after arranging a row i check the next row whether it is already arranged or not if it is than i break everything and moves to next case

n rectangular form

My Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    static long startTime;

    public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
            int numberOfOnes = 0;
            int T = scanner.nextInt();

            for (int t = 1; t <= T; t++) {
                int n = scanner.nextInt();

                int loopCounter, swapCounter = 0;
                boolean rowContainsZero = false;
                int array[][] = new int[n][n];
                boolean reject = true;
                //Worst and the most simpler conditions
                if (n == 1) {
                    System.out.print("0");
                    exitingSystem();
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        array[i][j] = scanner.nextInt();
                        if (array[i][j] == 1) {
                            numberOfOnes++;
                        }
                    }
                }
                if (n % 2 == 0 && numberOfOnes % 2 != 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;

                } else if (n % 2 != 0 && numberOfOnes % 2 == 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;
                }
                //     System.out.println("Here i am");
                //From here swaping processes will take the place
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (array[i][j] == 1) {
                            continue;
                        } else if (array[i][j] == 0) {
                            loopCounter = i;
                            reject = true;
                            while (loopCounter < n) {
                                if (array[loopCounter][j] == 1) {
                                    int temp = array[loopCounter][j];
                                    array[loopCounter][j] = array[i][j];
                                    array[i][j] = temp;
                                    reject = false;
                                    swapCounter += 1;
                                    break;
                                }
                                loopCounter++;
                            }
                             if (rowContainsZero) {
                                System.out.println("" + swapCounter);
                                    break;
                            }
                            if (reject == true) {
                                System.out.println("-1");
                                break;
                            } else {
                                for (int m = i + 1; m < n; m++) {
                                    for (int k = 0; k < n; k++) {
                                        if (array[m][k] == 0) {
                                            rowContainsZero = true;
                                        } else {
                                            rowContainsZero = false;
                                            break;
                                        }
                                    }
                                }
                            }

                        } else {
                            System.out.println("0's and 1's were Expected :(");
                            exitingSystem();
                        }
                    }
                    if (reject == true) {
                        break;
                    }
                }
            }

    }

    public static void exitingSystem() {
        System.exit(0);
    }

}

BUT THE CODECHEF COMPUTER SAYING WRONG ANSWER + They allowed to take input from keyboard too

Body:
This is not the way you are trying to solve problem. Suppose you have

                                                                 0 0 1
                                                                 0 1 1
                                                                 0 0 1

This is a perfect example of solveable matrix but you can't simply use random swap and then acquire result. You need to use A* search algorithm with manhatten distance.

Make a priority queue

Define manhatten distance.

Create a function which creates succesors of each board. Like if i have above board then it will give you a collection of boards back:

0 0 1
 0 1 1 ==> colection
 0 0 1

0 1 1
 0 0 1
 0 0 1

0 0 1
 0 0 1
 0 1 1

0 1 0
 0 1 1
 0 0 1

0 0 1
 0 1 1
 0 1 0

Description of A:*

an initial lis to store visited boar so that you don't visit them again.

i will call MinPriority queue a pq

`insert the initial_board in pq

while(!pq.isEmpty() && !foundGoal(pq.min)) //You find goal when your
manhatten distance is 0.

board = pq.delMin(); //you have to override the distance method in
priority queue so it will return you that board whoms manhatten
distance is smallest.

for(boards b :board.getSuccesors(); // give you collection of boards.

if(notvisited(b,vistiedList)) // so that you don't come in same state again and
again.

pq.insert(b);
visitedList.add(b);`

In first year i had to solve 8-puzzle and you can solve this way however you can also use hamming distance but that's not efficient and here is 8-puzzle code(with A* implementation).


来源: stackexchange

问:
Blitting multisampled FBO with multiple color attachments in OpenGL
I have a frame buffer object in an OpenGL program with multiple colour attachments, and am trying to upgrade it to a multisampled FBO.

As I understand it, a multisampled FBO is only able to use render buffers, specifically ones created using glRenderbufferStorageMultisampleEXT. If I want something rendered to this FBO in a texture, I need to create a second FBO with textures for its attachments, then blit the multisampled FBO to the regular FBO using glBlitFramebufferEXT.

The very, very sparse examples I've seen assume a single colour attachment.  What do I do when I want to blit multiple colour attachments?

答:
You can create a new Fbo and assign the renderbuffer in slot 1 to it at slot 0. Then bind for reading and blit from that to your final destination Fbx.

i.e. An Fbo can be created purely for binding an existing renderbuffer that was written to by another Fbo. An Fbo doesn't actually own the buffers that are connected to it so multiple Fbx can be bound to the same textures/renderbuffers(though not at the same time).

// Render to Fbo0
Fbo0 : [ColorBuffer0, ColorBuffer1, DethBuffer]

// Bind another fbo with ColorBuffer1 at slot 0 for reading
Fbo1 : [ColorBuffer1]

// blit Fbo0 ColorBuffer0 > Fbo2 Texture0
Fbo0 : [ColorBuffer0, ColorBuffer1, DethBuffer] => Fbo2 : [Texture0]

//blit Fbo1 ColorBuffer1 (bound at slot0) > Fbo3 Texture1 (bound at slot0)
Fbo1 : [ColorBuffer1] => Fbo3 : [Texture1]

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to make ASP.NET AJAX CalendarExtender always visible?
I'd like to be able to have the .NET AJAX CalendarExtender show on Load without having to click in a TextBox. If I can simulate a TextBox being clicked so the CalendarExtender will show I'll take that too.</p>

答:
The CalendarExtender does not support it.  You could write your own, but it would be much simpler to just use a standard Calendar control if you want a calendar that's always visible.

The extender was meant for use with a textbox when you want the calendar to pop up as needed.  Why write a new control when the basic control already exists?

Edit

To address the point in the comment about needing to switch years easily.  I COMPELTELY understand.  This is a frustration for me as well.  however, there are several ways to overcome this.  One good example can be found here: https://web.archive.org/web/20210304123649/https://www.4guysfromrolla.com/articles/090104-1.aspx


问:
Toggle between One and Two Elements Horizontally with slide animation - AngularJS
I want two states. The first with element 1 centered by itself. When a ng-click is activated another element (element 2) slides in from the right (animated) pushing element one too the side so both elements are centered on the page (second state). Then if the ng-click is toggled again the reverse happens and element 2 slides out of the view to the right and element 1 is centered back to the original first state, and ideas on how I could acheive this with angularJS?

答:
Slight improvement over previous answer if someone need to slide using a button.
This implementation is very simple for sliding between two divs.
Thanks to @Sasang

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

myApp.controller('MainCtrl', MainCtrl);

function MainCtrl($scope) {
   $scope.showFull = true
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content{
  text-align: center;
  transition: width linear 0.2s;
  overflow:hidden;
  display:inline-block;
}
.content span{
  font-size:10em;
  color: #FFFFFF;
}
.fullWidth{
  width:100%;
}
.halfWidth{
  width:50%;
}
.noWidth{
  width:0;
}
.red{
    background-color: red;
}
.blue{
    background-color: blue;
}</code>```

      <button ng-click="showFull = !showFull">Next</button>

      <button ng-click="showFull = !showFull">Prev</button>

```

Body:
Slight improvement over previous answer if someone need to slide using a button.
This implementation is very simple for sliding between two divs.
Thanks to @Sasang

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

myApp.controller('MainCtrl', MainCtrl);

function MainCtrl($scope) {
   $scope.showFull = true
}

.content{
  text-align: center;
  transition: width linear 0.2s;
  overflow:hidden;
  display:inline-block;
}
.content span{
  font-size:10em;
  color: #FFFFFF;
}
.fullWidth{
  width:100%;
}
.halfWidth{
  width:50%;
}
.noWidth{
  width:0;
}
.red{
    background-color: red;
}
.blue{
    background-color: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
  <div class="content red" ng-class="showFull ? 'fullWidth' : 'noWidth'" >
      <span><button ng-click="showFull = !showFull">Next</button></span>
  </div><div class="content blue" ng-class="showFull ? 'noWidth' : 'fullWidth'">
      <span><button ng-click="showFull = !showFull">Prev</button></span>
  </div>
</div>


问:
writing the results of json to a csv
I'm using DictWriter cause I thought it would be easier but I'm getting no where. I trying to write my json file to a csv file with each field in it's own column.

json file:

```<code>[ {"district": "4",
"id": "DEL000027",
"full_name": "Gerald L. Brady", "party": "Democratic",
"email": "Gerald.Brady@state.de.us"},
{"district": "37",
"id": "DEL000028", "full_name": "Ruth Briggs  King",
"party": "Republican",
"email": "Ruth.BriggsKing@state.de.us"}]
</code>```

here is the script that I wrote:

```<code>import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values)

writer.writeheader()
for item in data:
    writer.writerows(item)<----- error but don't know why it's an error
</code>```

答:
The function is called writerows (with an s). So the function does not expect a single dictionary, you need to pass an iterable of dictionaries, so you can write:

```<code>import json, csv

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values<b>, extrasaction='ignore'</b>)

    writer.writeheader()

    writer.writerows(<b>data</b>)</code>```

You need to use the extrasaction='ignore' here since your dictionaries contain extra keys that are not present in the values list. The writer will error if you do not provide a way to resolve this.

You also need to write the data in the body of the with clause, since after the (end of the) with, the file is closed again.

This snippet produces:

```<code>full_name,party,district,email
Gerald L. Brady,Democratic,4,Gerald.Brady@state.de.us
Ruth Briggs  King,Republican,37,Ruth.BriggsKing@state.de.us
</code>```

Title: writing the results of json to a csv

Body:
I'm using DictWriter cause I thought it would be easier but I'm getting no where. I trying to write my json file to a csv file with each field in it's own column.

json file:

[ {"district": "4",
"id": "DEL000027",
"full_name": "Gerald L. Brady", "party": "Democratic",
"email": "Gerald.Brady@state.de.us"},
{"district": "37",
"id": "DEL000028", "full_name": "Ruth Briggs  King",
"party": "Republican",
"email": "Ruth.BriggsKing@state.de.us"}]

here is the script that I wrote:

import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values)

writer.writeheader()
for item in data:
    writer.writerows(item)<----- error but don't know why it's an error

Body:
The function is called writerows (with an s). So the function does not expect a single dictionary, you need to pass an iterable of dictionaries, so you can write:

import json, csv

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore')

    writer.writeheader()

    writer.writerows(data)

You need to use the extrasaction='ignore' here since your dictionaries contain extra keys that are not present in the values list. The writer will error if you do not provide a way to resolve this.

You also need to write the data in the body of the with clause, since after the (end of the) with, the file is closed again.

This snippet produces:

full_name,party,district,email
Gerald L. Brady,Democratic,4,Gerald.Brady@state.de.us
Ruth Briggs  King,Republican,37,Ruth.BriggsKing@state.de.us


问:
Snapshot testing on Angular 1.x with Jest
I'd like to use Jest to snapshot-test my angular 1.x directives.
I've already got a working test environment with jest, but I'm not sure how (and if I can) snapshot test my directives/components.

I don't think I can use the renderer object used in this example (looks like a react-specific object) http://facebook.github.io/jest/docs/en/snapshot-testing.html#content and I'm not sure how to use the .toJSON() function in order to serialize my directive/components.

This is the only link I've found on Jest+Angular 1.x usage:
https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251 and I can't find any answer about snapshot testing.

Thanks in advance,

Federico

答:
It works.

test.js

```<code>const angular = require('angular');
require('angular-mocks');

describe('Renderer', () => {
  let element;
  let scope;

  beforeEach(
    angular.mock.inject(($rootScope, $compile) => {
      scope = $rootScope.$new();
      element = $compile(
        '<div><label ng-show="label.show">1</label><label ng-hide="label.show">2</label></div>'
      )(scope);
      scope.$digest();
    })
  );

  it('should render the element', () => {
    expect(element).toBeDefined();
    expect(element[0]).toMatchSnapshot();
  });
});
</code>```

Snapshot

```<code>exports[`Renderer should render the element 1`] = `
<div
  class="ng-scope"
>
  <label
    class="ng-hide"
    ng-show="label.show"
  >
    1
  </label>
  <label
    ng-hide="label.show"
  >
    2
  </label>
</div>
`;
</code>```

Body:
It works.

test.js

const angular = require('angular');
require('angular-mocks');

describe('Renderer', () => {
  let element;
  let scope;

  beforeEach(
    angular.mock.inject(($rootScope, $compile) => {
      scope = $rootScope.$new();
      element = $compile(
        '<div><label ng-show="label.show">1</label><label ng-hide="label.show">2</label></div>'
      )(scope);
      scope.$digest();
    })
  );

  it('should render the element', () => {
    expect(element).toBeDefined();
    expect(element[0]).toMatchSnapshot();
  });
});

Snapshot

exports[`Renderer should render the element 1`] = `
<div
  class="ng-scope"
>
  <label
    class="ng-hide"
    ng-show="label.show"
  >
    1
  </label>
  <label
    ng-hide="label.show"
  >
    2
  </label>
</div>
`;


问:
How to split string by line from url
I have the following url

"https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"

where I need to split the string by line and store it in a list and return that list. I currently have the following:

```<code>val url_alcohol =
  "https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"
def get_csv_page(url: String) : List[String] =
{
    val p: Pattern = Pattern.compile("\\r?\\n")
            val m:Matcher = p.matcher(url)
            if(m.find())
              // add to list
}
</code>```

It is not complete as I don't know how to do it.

Thanks for your time

答:
As per your comments, here is my edited answer:

```<code>val url = "https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"

def get_csv_page(url: String): List[String] = {
  val body = scala.io.Source.fromURL(url).mkString
  body.split("\n").toList
}

println(get_csv_page(url))
</code>```

You will probably want to add a little more logic, like maybe taking off the first line (the csv headers)

Title: How to split string by line from url

Body:
I have the following url

"https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"

where I need to split the string by line and store it in a list and return that list. I currently have the following:

val url_alcohol =
  "https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"
def get_csv_page(url: String) : List[String] =
{
    val p: Pattern = Pattern.compile("\\r?\\n")
            val m:Matcher = p.matcher(url)
            if(m.find())
              // add to list
}

It is not complete as I don't know how to do it.

Thanks for your time

Body:
As per your comments, here is my edited answer:

val url = "https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv"

def get_csv_page(url: String): List[String] = {
  val body = scala.io.Source.fromURL(url).mkString
  body.split("\n").toList
}

println(get_csv_page(url))

You will probably want to add a little more logic, like maybe taking off the first line (the csv headers)


问:
Simple UML tools
I am looking for a simple UML-tool that will let me do for example a sequence diagram quicker and better than Word from scratch (Without spending to much time on learning the tool, and with the tool more supporting me than constraining me)

Primary choice is Visio.

答:
Try Use Online Versions Sometime , It's Lite And Saved My Brain From Blow-up Many Times When I Was Out With No Tools , If U Need Simple One I Suggest This But Search Out Many Online Tools Available

http://www.websequencediagrams.com/

LucidChart WebBased Is Also Really Awesome ( Free Account With Some Limitations )

http://www.lucidchart.com/

Desktop -

Eclipse UML2 Tools Is Perfect If u Need Desktop Version

Rise Is Great And Freeware For C# Also Simple Sequence Diagrams

http://www.risetobloome.com/

*And*As Sometimes People Need UML For Managing Mind Thoughts And Ideas If U Do , As I See U Point At Visio And Word , Try Find Some Mind Management ( Just Thought )

MindApp Is Fastest And Easiest , I Like It So Much

Title: Simple UML tools


问:
Output different sized dataframes on one .txt file in R
I have two dataframes of different size that I want to output into a .txt file.
I've been using the write.table function but I can only output one on a .txt file.

```<code>dataframe1=data.frame(x=c(1:10), y=c(1:10), z=c(1:10))
dataframe2=data.frame(a=c(1:5), b=c(1:5))
write.table( C(dataframe1,dataframe2),
             file = "dataframes.txt",
             append = F,
             sep = ",",
             row.names = F,
             col.names = F,
             na="",
             quote = F)
</code>```

I'm trying to get them shown as stacked on top of each other but it is not working. Any suggestions?

答:
You have a few problems in your code.

First, C(dataframe1,dataframe2) creates an error because you used a capital C.

Second, c(dataframe1,dataframe2) outputs a list with 5 items. This is NOT a dataframe or a matrix. This will be coerced into a matrix when you save. Any rows with missing data will be filled automatically which you may not want. That would result in in your code outputting:

```<code>1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5
</code>```

The problem here is that you are trying to concatenate two different dataframes that have different numbers of columns. You can either cbind them together as one large table and save it. But beware that any missing row data may be automatically filled in which you don't want (a and b only have 5 rows compared to xyz with 10 rows).

```<code>write.table( cbind(dataframe1,dataframe2),
              file = "dataframes.txt",
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)
</code>```

Which will output:

```<code>x,y,z,a,b
1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5
</code>```

Or if you really want them on top of each other you can use separate calls and turn on append.

```<code>write.table( dataframe1,
              file = "dataframes.txt",
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)
write( "\n Next Dataframe \n", file = "dataframes.txt", append = T)
write.table( dataframe2,
              file = "dataframes.txt",
              append = T,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)

Which will output:
x,y,z
1,1,1
2,2,2
3,3,3
4,4,4
5,5,5
6,6,6
7,7,7
8,8,8
9,9,9
10,10,10

 Next Dataframe

a,b
1,1
2,2
3,3
4,4
5,5
</code>```

Body:
I have two dataframes of different size that I want to output into a .txt file.
I've been using the write.table function but I can only output one on a .txt file.

dataframe1=data.frame(x=c(1:10), y=c(1:10), z=c(1:10))
dataframe2=data.frame(a=c(1:5), b=c(1:5))
write.table( C(dataframe1,dataframe2),
             file = "dataframes.txt",
             append = F,
             sep = ",",
             row.names = F,
             col.names = F,
             na="",
             quote = F)

I'm trying to get them shown as stacked on top of each other but it is not working. Any suggestions?

Body:
You have a few problems in your code.

First, C(dataframe1,dataframe2) creates an error because you used a capital C.

Second, c(dataframe1,dataframe2) outputs a list with 5 items. This is NOT a dataframe or a matrix. This will be coerced into a matrix when you save. Any rows with missing data will be filled automatically which you may not want. That would result in in your code outputting:

1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5

The problem here is that you are trying to concatenate two different dataframes that have different numbers of columns. You can either cbind them together as one large table and save it. But beware that any missing row data may be automatically filled in which you don't want (a and b only have 5 rows compared to xyz with 10 rows).

write.table( cbind(dataframe1,dataframe2),
              file = "dataframes.txt",
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)

Which will output:

x,y,z,a,b
1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5

Or if you really want them on top of each other you can use separate calls and turn on append.

write.table( dataframe1,
              file = "dataframes.txt",
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)
write( "\n Next Dataframe \n", file = "dataframes.txt", append = T)
write.table( dataframe2,
              file = "dataframes.txt",
              append = T,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)

Which will output:
x,y,z
1,1,1
2,2,2
3,3,3
4,4,4
5,5,5
6,6,6
7,7,7
8,8,8
9,9,9
10,10,10

 Next Dataframe

a,b
1,1
2,2
3,3
4,4
5,5


问:
Where does world state store physically
Ok, we have a commiting peers - running containers. As i assume, there is an LevelDB or CouchDB database server in containers, that stores world state. As far as i know, data must be available only from blockchain. Why can't I just connect to that database throught container and see the data or change it? If it protected, tell me, please, how protection is creating.</p>

答:
By default, the CouchDB container cannot be accessed from the outside--only the attached peer is allowed to access it. Also, it can be set up with name/password login.
LevelDB does not have its own container.</p>

Title: Where does world state store physically


问:
Type map in C++
I'll begin with a context that will lead to the actual question.

I'm trying to build a class whose every instance will manage how data is tied together into objects.
The class should preferably contain methods:

```<code>class DataManager {
  Object CreateObject();
  void DestoryObject();

  template<typename DataType>
  DataType* AddDataToObject(Object o)

  template<typename DataType>
  DataType* GetDataForObject(Object o)

  template<typename DataType>
  void RemoveDataFromObject(Object o)
};
</code>```

Object in the code above is just some identifier - int at this point and does not contain any data or methods (this should not change). DataType used above can be basically any class, however the general situation is that this is just a struct with no methods. The complete list of things that can be used as DataType is known at compile time but should not be encoded as it changes quite often.

The two goals I try to achieve are:
- Maintainability/Speed - The user should be able to add new DataType structures without modifying this code
- Speed - should be as fast as possible :)

Now the best thing idea I had so far is to make a container classes:

```<code>class ContainerBase;

template<typename DataType>
class DataTypeContainer : ContainerBase;
</code>```

The data structure then would be something like:

```<code>map< DataTypeType, map< Object, ContainerBase* > >
</code>```

Sow how can one achieve this?
Would boost::mpl::map help and how?

In essence this should be possible to do since all DataType's are known at compile time.

答:
You could create a tuple with the mapping between your types like that:

```<code>template < std::size_t sz, typename... Types >
struct TypeMap {
    TypeMap (std::array< std::tuple< Types... >, sz > m) : mapping (m) {
    }

    std::array< std::tuple< Types... >, sz > mapping;
};
</code>```

Then specify a function to convert

```<code>template < typename To, typename From, std::size_t sz, typename... T >
To convert (From from, TypeMap< sz, T... > m) {
    for (auto entry : m.mapping) {
        if (utils::get< From > (entry) == from) {
            return utils::get< To > (entry); //Tricky part here
        }
    }

    throw std::logic_error ("No entry in the typemap");
}
</code>```

Then specify the mapping

```<code>const auto map = TypeMap{{std::make_tuple (red, "red", 1),
                          std::make_tuple (green, "green", 2),
                          std::make_tuple (blue, "blue", 3)}};
</code>```

and finally you can call your convert function and convert any type to any other type ;)

See my article here:
https://cpptelepathy.wordpress.com/

You would need this file
https://github.com/alekstheod/tnnlib/blob/master/src/Utilities/MPL/Tuple.h

for util::get

Title: Type map in C++

Body:
I'll begin with a context that will lead to the actual question.

I'm trying to build a class whose every instance will manage how data is tied together into objects.
The class should preferably contain methods:

class DataManager {
  Object CreateObject();
  void DestoryObject();

  template<typename DataType>
  DataType* AddDataToObject(Object o)

  template<typename DataType>
  DataType* GetDataForObject(Object o)

  template<typename DataType>
  void RemoveDataFromObject(Object o)
};

Object in the code above is just some identifier - int at this point and does not contain any data or methods (this should not change). DataType used above can be basically any class, however the general situation is that this is just a struct with no methods. The complete list of things that can be used as DataType is known at compile time but should not be encoded as it changes quite often.

The two goals I try to achieve are:
- Maintainability/Speed - The user should be able to add new DataType structures without modifying this code
- Speed - should be as fast as possible :)

Now the best thing idea I had so far is to make a container classes:

class ContainerBase;

template<typename DataType>
class DataTypeContainer : ContainerBase;

The data structure then would be something like:

map< DataTypeType, map< Object, ContainerBase* > >

Sow how can one achieve this?
Would boost::mpl::map help and how?

In essence this should be possible to do since all DataType's are known at compile time.

Body:
You could create a tuple with the mapping between your types like that:

template < std::size_t sz, typename... Types >
struct TypeMap {
    TypeMap (std::array< std::tuple< Types... >, sz > m) : mapping (m) {
    }

    std::array< std::tuple< Types... >, sz > mapping;
};

Then specify a function to convert

template < typename To, typename From, std::size_t sz, typename... T >
To convert (From from, TypeMap< sz, T... > m) {
    for (auto entry : m.mapping) {
        if (utils::get< From > (entry) == from) {
            return utils::get< To > (entry); //Tricky part here
        }
    }

    throw std::logic_error ("No entry in the typemap");
}

Then specify the mapping

const auto map = TypeMap{{std::make_tuple (red, "red", 1),
                          std::make_tuple (green, "green", 2),
                          std::make_tuple (blue, "blue", 3)}};

and finally you can call your convert function and convert any type to any other type ;)

See my article here:
https://cpptelepathy.wordpress.com/

You would need this file
https://github.com/alekstheod/tnnlib/blob/master/src/Utilities/MPL/Tuple.h

for util::get


问:
Efficiency of Filtering Clauses with Dynamic SQL
I am trying to write a relatively generic dynamic query generator and am curious about some techniques.  I have a list page with anywhere between 20 and 100 filters.  Each filter will be either "standard" in that the SqlGenerator class knows how to create the SQL or "custom" so that the filter provides the SqlGenerator with a strategy for what needs to be INCLUDEd and a WHERE clause.

1.) What is the best way to do the filtering clauses?

a) Very straightforward as far as keeping each filter separate and contained:

```<code>and exists (select 'x' from [company] c
            where c.CompanyId = p.CompayId
            and c.Rating >= 4)
and exists (select 'x' from [company] c
            where c.CompanyId = p.CompayId
           and c.CityId = 5)
</code>```

b) Consolidated to a single exists but removes the need to build/manage INCLUDEs.

```<code>and exists (
    select 'x'
    from [company] c
    where c.CompanyId = p.CompayId
    and c.Rating >= 4 and c.CityId = 5)
</code>```

c) Difficult to build dynamically but reads the cleanest to me and seems like it would execute most efficiently.

```<code>select x, y, z
from product p
join company c on p.CompanyId = p.ProductId
where c.Rating >= 4 and c.CityId = 5
</code>```

d) I've also seen, on occasion, that putting certain pieces of the where clause in the join make queries more efficient.  Does it make sense to do this:

```<code>select x, y, z
from product p
join company c on p.CompanyId = p.ProductId and c.Rating >= 4 and c.CityId = 5
</code>```

2.) Since this is dynamic, I'm afraid I'm losing all benefit of query cache plans and indexes.  Does it make sense to always include certain joins and clauses in hopes they get optimized away in order to use the same plan/indexes?

```<code>select x, y, z
from product p
join company c on p.CompanyId = p.ProductId
where c.Rating >= ISNULL(@Rating, c.Rating)
and c.CityId = ISNULL(@CityId, c.CityId)
</code>```

3.) Lastly, does the order of clauses and joins affect query plan caching?  That is, if I switch the order of the AND statements, are those 2 different plans?

答:
Your queries do different things.  You should choose the version that does what you want semantically.

(1a) and (1b), do different things.  Under some circumstances, they do the same thing -- notably if companyid is unique in the table.  I don't know whether or not that is true for this table or for other tables.

(1a)/(1b) and (1c) do different things, especially if companyId can be duplicated.

(1c)/(1d) -- I have never seen a difference in moving a condition from the where to an on clause for an inner join.  Of course, this can make a difference for an outer join.

(2) I would be much more concerned about using indexes rather than query caches.  Reading just a few extra data pages pretty is going to take longer than recompiling in most cases.

(3) For a long complex query, the ordering of conditions and tables can matter, but this is not generally a major concern.

Body:
I am trying to write a relatively generic dynamic query generator and am curious about some techniques.  I have a list page with anywhere between 20 and 100 filters.  Each filter will be either "standard" in that the SqlGenerator class knows how to create the SQL or "custom" so that the filter provides the SqlGenerator with a strategy for what needs to be INCLUDEd and a WHERE clause.

1.) What is the best way to do the filtering clauses?

a) Very straightforward as far as keeping each filter separate and contained:

and exists (select 'x' from [company] c
            where c.CompanyId = p.CompayId
            and c.Rating >= 4)
and exists (select 'x' from [company] c
            where c.CompanyId = p.CompayId
           and c.CityId = 5)

b) Consolidated to a single exists but removes the need to build/manage INCLUDEs.

and exists (
    select 'x'
    from [company] c
    where c.CompanyId = p.CompayId
    and c.Rating >= 4 and c.CityId = 5)

c) Difficult to build dynamically but reads the cleanest to me and seems like it would execute most efficiently.

select x, y, z
from product p
join company c on p.CompanyId = p.ProductId
where c.Rating >= 4 and c.CityId = 5

d) I've also seen, on occasion, that putting certain pieces of the where clause in the join make queries more efficient.  Does it make sense to do this:

select x, y, z
from product p
join company c on p.CompanyId = p.ProductId and c.Rating >= 4 and c.CityId = 5

2.) Since this is dynamic, I'm afraid I'm losing all benefit of query cache plans and indexes.  Does it make sense to always include certain joins and clauses in hopes they get optimized away in order to use the same plan/indexes?

select x, y, z
from product p
join company c on p.CompanyId = p.ProductId
where c.Rating >= ISNULL(@Rating, c.Rating)
and c.CityId = ISNULL(@CityId, c.CityId)

3.) Lastly, does the order of clauses and joins affect query plan caching?  That is, if I switch the order of the AND statements, are those 2 different plans?


问:
How can I create and reference a table in WebAssembly?
Can someone please share the syntax to create a table statically having certain elements and reference it? I could not find any web assembly code doing so.

Also some details like can I have multiple columns, what happens if index doesn't lie in the table etc. would be helpful?

答:
(Updated for Wasm 2.0 in in 2022)

In the text format, a table is declared with its table type, i.e., (initial) size and element type -- currently funcref and externref are the only supported types:

```<code>(table $name 100 funcref)
</code>```

Since Wasm 2.0, there can be multiple tables in a module.

A table can be initialised within a module by providing one or more active element segments:

```<code>(elem (i32.const 0) $f1 $f2 $f3)
</code>```

where the expression denotes the offset and is followed by a list of functions defined in the module.

Since Wasm 2.0, tables can furhter be accessed and modified through instructions like table.get, table.set, table.size, table.grow, etc.

Before 2.0, the only way to use a table was through the call_indirect instruction:

```<code>(call_indirect (type $t) (arg1) ... (argn) (index))
</code>```

You can find a few simple examples in the Wasm spec test suite, e.g. here:

https://github.com/WebAssembly/spec/blob/master/test/core/table.wast

https://github.com/WebAssembly/spec/blob/master/test/core/elem.wast

https://github.com/WebAssembly/spec/blob/master/test/core/table_get.wast

https://github.com/WebAssembly/spec/blob/master/test/core/table_set.wast

A table does not have columns. As for execution, out of bounds access causes a trap, as does accessing an uninitialised index or a type mismatch.

Body:
(Updated for Wasm 2.0 in in 2022)

In the text format, a table is declared with its table type, i.e., (initial) size and element type -- currently funcref and externref are the only supported types:

(table $name 100 funcref)

Since Wasm 2.0, there can be multiple tables in a module.

A table can be initialised within a module by providing one or more active element segments:

(elem (i32.const 0) $f1 $f2 $f3)

where the expression denotes the offset and is followed by a list of functions defined in the module.

Since Wasm 2.0, tables can furhter be accessed and modified through instructions like table.get, table.set, table.size, table.grow, etc.

Before 2.0, the only way to use a table was through the call_indirect instruction:

(call_indirect (type $t) (arg1) ... (argn) (index))

You can find a few simple examples in the Wasm spec test suite, e.g. here:

https://github.com/WebAssembly/spec/blob/master/test/core/table.wast

https://github.com/WebAssembly/spec/blob/master/test/core/elem.wast

https://github.com/WebAssembly/spec/blob/master/test/core/table_get.wast

https://github.com/WebAssembly/spec/blob/master/test/core/table_set.wast

A table does not have columns. As for execution, out of bounds access causes a trap, as does accessing an uninitialised index or a type mismatch.

ContentLicense: CC BY-SA 4.0


问:
Who is wrong about the http://0:port?
The Plack suite commonly uses the http://0:port. E.g. the following

```<code>plackup -MPlack::App::Directory -e 'Plack::App::Directory->new(root=>".");'
</code>```

prints

```<code>HTTP::Server::PSGI: Accepting connections at http://0:5000/
</code>```

However, the LWP::UserAgent (or some deeper called modules) didn't accepts it, e.g. the:

```<code>perl -MLWP::UserAgent -E '$u=LWP::UserAgent->new;$res=$u->get("http://0:5000/valid/path");print $res->status_line'
</code>```

prints:

```<code>500 No Host option provided
</code>```

but the

```<code>perl -MLWP::UserAgent -E '$u=LWP::UserAgent->new;$res=$u->get("http://localhost:5000/valid/path");print $res->status_line'
</code>```

prints

```<code>200 OK
</code>```

The question is: who is wrong?

Is the http://0:port valid, e.g. the LWP is "wrong"

or it isn't valid and the PSGI uses it as only "randomly valid" shortcut?

答:
Safari 11, curl and wget resolve http://0:5000 to http://0.0.0.0:5000 and connect to the localhost.

I just tested it, after seeing the URL and finding the answer to the question dissatisfying.

Title: Who is wrong about the http://0:port?

Body:
The Plack suite commonly uses the http://0:port. E.g. the following

plackup -MPlack::App::Directory -e 'Plack::App::Directory->new(root=>".");'

prints

HTTP::Server::PSGI: Accepting connections at http://0:5000/

However, the LWP::UserAgent (or some deeper called modules) didn't accepts it, e.g. the:

perl -MLWP::UserAgent -E '$u=LWP::UserAgent->new;$res=$u->get("http://0:5000/valid/path");print $res->status_line'

prints:

500 No Host option provided

but the

perl -MLWP::UserAgent -E '$u=LWP::UserAgent->new;$res=$u->get("http://localhost:5000/valid/path");print $res->status_line'

prints

200 OK

The question is: who is wrong?

Is the http://0:port valid, e.g. the LWP is "wrong"

or it isn't valid and the PSGI uses it as only "randomly valid" shortcut?


问:
Is is possible to add .Where() on a child collection property using nhibernate linq?
i have this query that i am running to do an upfront join between these tables:

Table - columns

- Project  - id, name, description

- ProjectSponsor (bridge table) - id, sponsorid, projectid, isPrimarySponsor

- Sponsor - id, first, last

here is the nhibernate 3 linq query i am running to do a join:

```<code> IEnumerable<Project> list = Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor);
</code>```

how do i add a where clause to only include a sponsor where the sponsorName = "Joe"

i remember seeing that fetch always much come at the end of a nhibernate linq query but it seems like a i need to do a where after the "ThenFetch" to make this work?

Can anyone please let me know how i can add a "where clause" equivalent on the Sponsor

NOTE:

i can't just have a simple many to many direct mapping from Project to Sponsor because of the "isPrimarySponsor" field needed in the bridge table.

答:
First let me show my understanding of what you are trying to achieve. You want to fetch ALL Projects and into these projects you want to fetch their corresponding ProjectSponsors which include Sponsors but you only want such ProjectSponsors that have a Sponsor with specific name.

So if there is no "Joe" sponsor for a project, then its ProjectSponsors collection will be empty. Is that right?

If so, you want to do left join between projects and sponsors. Also, you want to fetch it all at once, that is the reason you want to use these Fetch methods.

As far as I could find out, there really is no way to add a Where into your statement. But even if there was, I think it would not help you. If you could write:

```<code>Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor).Where(s => s.Name == "Joe")
</code>```

what kind of SQL would it generate? Something like this:

```<code>SELECT
    *
FROM
    Project P
    LEFT JOIN ProjectSponsors PS ON PS.ProjectId = P.ProjectId
    LEFT JOIN Sponsors S ON S.SponsorId = PS.SponsorId
WHERE
    S.Name = 'Joe'
</code>```

That would, however, result into selecting only those projects which have at least one Sponsor named Joe.

What you want, actually, is to filter ProjectSponsors to only select those which have their Sponsor named Joe.

Now I don't know if this is an acceptable solution for you, but this is how I would do it. I would define and set a filter in my mapping for ProjectSponsors association in Project entity like this:

```<code><class name="Project" table="Project">
...
<set name="ProjectSponsors" table="ProjectSponsor">
  <key column="ProjectId" />
  <one-to-many class="ProjectSponsor" />
  <filter name="SponsorName" condition="EXISTS (SELECT * FROM Sponsor where Sponsor.SponsorId = SponsorId AND Sponsor.Name=:name)" />
</set>
</class>
<filter-def name="SponsorName">
    <filter-param name="name" type="String"/>
</filter-def>
</code>```

With that, I'd use your original statement after enabling and setting the filter:

```<code>Session.EnableFilter("SponsorName").SetParameter("name", "Joe");
var projects = Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor);
</code>```

That would generate SQL like this:

```<code>SELECT
    *
FROM
    Project P
    LEFT JOIN ProjectSponsors PS ON PS.ProjectId = P.ProjectId AND EXISTS (SELECT * FROM Sponsor where Sponsor.SponsorId = PS.SponsorId AND Sponsor.Name = 'Joe')
    LEFT JOIN Sponsors S ON S.SponsorId = PS.SponsorId
</code>```

which would select all Projects but for them only such ProjectSponsor combinations which have Joe as Sponsor.

I'm not sure if this is the best approach but hope it will help.

Body:
i have this query that i am running to do an upfront join between these tables:

Table - columns

- Project  - id, name, description

- ProjectSponsor (bridge table) - id, sponsorid, projectid, isPrimarySponsor

- Sponsor - id, first, last

here is the nhibernate 3 linq query i am running to do a join:

 IEnumerable<Project> list = Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor);

how do i add a where clause to only include a sponsor where the sponsorName = "Joe"

i remember seeing that fetch always much come at the end of a nhibernate linq query but it seems like a i need to do a where after the "ThenFetch" to make this work?

Can anyone please let me know how i can add a "where clause" equivalent on the Sponsor

NOTE:

i can't just have a simple many to many direct mapping from Project to Sponsor because of the "isPrimarySponsor" field needed in the bridge table.

Body:
First let me show my understanding of what you are trying to achieve. You want to fetch ALL Projects and into these projects you want to fetch their corresponding ProjectSponsors which include Sponsors but you only want such ProjectSponsors that have a Sponsor with specific name.

So if there is no "Joe" sponsor for a project, then its ProjectSponsors collection will be empty. Is that right?

If so, you want to do left join between projects and sponsors. Also, you want to fetch it all at once, that is the reason you want to use these Fetch methods.

As far as I could find out, there really is no way to add a Where into your statement. But even if there was, I think it would not help you. If you could write:

Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor).Where(s => s.Name == "Joe")

what kind of SQL would it generate? Something like this:

SELECT
    *
FROM
    Project P
    LEFT JOIN ProjectSponsors PS ON PS.ProjectId = P.ProjectId
    LEFT JOIN Sponsors S ON S.SponsorId = PS.SponsorId
WHERE
    S.Name = 'Joe'

That would, however, result into selecting only those projects which have at least one Sponsor named Joe.

What you want, actually, is to filter ProjectSponsors to only select those which have their Sponsor named Joe.

Now I don't know if this is an acceptable solution for you, but this is how I would do it. I would define and set a filter in my mapping for ProjectSponsors association in Project entity like this:

<class name="Project" table="Project">
...
<set name="ProjectSponsors" table="ProjectSponsor">
  <key column="ProjectId" />
  <one-to-many class="ProjectSponsor" />
  <filter name="SponsorName" condition="EXISTS (SELECT * FROM Sponsor where Sponsor.SponsorId = SponsorId AND Sponsor.Name=:name)" />
</set>
</class>
<filter-def name="SponsorName">
    <filter-param name="name" type="String"/>
</filter-def>

With that, I'd use your original statement after enabling and setting the filter:

Session.EnableFilter("SponsorName").SetParameter("name", "Joe");
var projects = Session.Query<Project>().FetchMany(r => r.ProjectSponsors).ThenFetch(r => r.Sponsor);

That would generate SQL like this:

SELECT
    *
FROM
    Project P
    LEFT JOIN ProjectSponsors PS ON PS.ProjectId = P.ProjectId AND EXISTS (SELECT * FROM Sponsor where Sponsor.SponsorId = PS.SponsorId AND Sponsor.Name = 'Joe')
    LEFT JOIN Sponsors S ON S.SponsorId = PS.SponsorId

which would select all Projects but for them only such ProjectSponsor combinations which have Joe as Sponsor.

I'm not sure if this is the best approach but hope it will help.


问:
Foreign key in SQLite
I am creating two tables, one for books and one for stores.I want to link every Book in BookStore Table to StoreTable by giving it a Store_ID.
That Store_Id will be the primary key in StoreTable.I am having trouble with the syntax of the foreign key.I also checked http://www.sqlite.org/foreignkeys.html for reference but that didn't provide me with enough clarification.I would be much obliged if anyone helps me.</p>

```<code>public class DatabaseHelper  extends SQLiteOpenHelper{

//Name of databases
public static final String DATABASE_NAME = "Library.db";
//Version of database
public static final int  DATABASE_VERSION = 1;

//Table of Stores
public static final String STORE_TABLE = "Store_Table";
public static final String STORE_ID = "Store_ID";
public static final String STORE_NAME = "Store_name";
public static final String STORE_Address = "Store_Address";
public static final String STORE_LAT = "lat";
public static final String STORE_LNG = "lng";

//Table of Books
public static final String BOOKS_TABLE = "Books_Table";
public static final String BOOK_ID = "Book_ID";
public static final String BOOK_NAME = "Book_name";
public static final String BOOK_AUTHOR = "Book_Author";
public static final String BOOKStore = "BookStore_ID";

//Creating Stores Table
private static final String SQL_CREATE_TABLE_STORE = "CREATE TABLE " + STORE_TABLE + "("
        + STORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + STORE_NAME + " TEXT NOT NULL, "
        + STORE_Address + " TEXT NOT NULL, "
        + STORE_LAT + " TEXT NOT NULL, "
        + STORE_LNG + " TEXT NOT NULL"
        +");";
//Creating Books Table
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
        + BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + BOOK_NAME + " TEXT NOT NULL, "
        + BOOK_AUTHOR + " TEXT NOT NULL, "
 //How to relate BookStore with Store_ID here?
        +FOREIGN KEY(BOOKStore) REFERENCES STORE_TABLE(STORE_ID));
        +");";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    SQLiteDatabase db = this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

    sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STORE);
    sqLiteDatabase.execSQL(SQL_CREATE_TABLE_BOOKS);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    //Clear all data
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE);
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);

    //RECREAT THE TABLES
    onCreate(sqLiteDatabase);

}
}
</code>```

答:
This is the correct answer:</p>

```<code>private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
        + BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + BOOK_NAME + " TEXT NOT NULL, "
        + BOOK_AUTHOR + " TEXT NOT NULL, "
 //How to relate BookStore with Store_ID here?
        + " FOREIGN KEY ("+ BOOKStore +") REFERENCES "+STORE_TABLE+"("+STORE_ID+"));";
</code>```

Title: Foreign key in SQLite

Body:
I am creating two tables, one for books and one for stores.I want to link every Book in BookStore Table to StoreTable by giving it a Store_ID.
That Store_Id will be the primary key in StoreTable.I am having trouble with the syntax of the foreign key.I also checked http://www.sqlite.org/foreignkeys.html for reference but that didn't provide me with enough clarification.I would be much obliged if anyone helps me.

public class DatabaseHelper  extends SQLiteOpenHelper{

//Name of databases
public static final String DATABASE_NAME = "Library.db";
//Version of database
public static final int  DATABASE_VERSION = 1;

//Table of Stores
public static final String STORE_TABLE = "Store_Table";
public static final String STORE_ID = "Store_ID";
public static final String STORE_NAME = "Store_name";
public static final String STORE_Address = "Store_Address";
public static final String STORE_LAT = "lat";
public static final String STORE_LNG = "lng";

//Table of Books
public static final String BOOKS_TABLE = "Books_Table";
public static final String BOOK_ID = "Book_ID";
public static final String BOOK_NAME = "Book_name";
public static final String BOOK_AUTHOR = "Book_Author";
public static final String BOOKStore = "BookStore_ID";

//Creating Stores Table
private static final String SQL_CREATE_TABLE_STORE = "CREATE TABLE " + STORE_TABLE + "("
        + STORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + STORE_NAME + " TEXT NOT NULL, "
        + STORE_Address + " TEXT NOT NULL, "
        + STORE_LAT + " TEXT NOT NULL, "
        + STORE_LNG + " TEXT NOT NULL"
        +");";
//Creating Books Table
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
        + BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + BOOK_NAME + " TEXT NOT NULL, "
        + BOOK_AUTHOR + " TEXT NOT NULL, "
 //How to relate BookStore with Store_ID here?
        +FOREIGN KEY(BOOKStore) REFERENCES STORE_TABLE(STORE_ID));
        +");";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    SQLiteDatabase db = this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

    sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STORE);
    sqLiteDatabase.execSQL(SQL_CREATE_TABLE_BOOKS);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    //Clear all data
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE);
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);

    //RECREAT THE TABLES
    onCreate(sqLiteDatabase);

}
}

Body:
This is the correct answer:

private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
        + BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + BOOK_NAME + " TEXT NOT NULL, "
        + BOOK_AUTHOR + " TEXT NOT NULL, "
 //How to relate BookStore with Store_ID here?
        + " FOREIGN KEY ("+ BOOKStore +") REFERENCES "+STORE_TABLE+"("+STORE_ID+"));";


问:
Array formula to return an ARRAY without duplicates, without VBA
I would like to know whether it's possible to return an array from a single cell formula, which is filtered to remove duplicates, and which is built purely on Excel formulas.

I'm aware of approaches to return a list of values where the duplicates are removed (see this question), where the list is spread over multiple cells. However I specifically want to return an array intermediate.

E.g. For the list in A1:A5, I can get an array of values {0.1,0.2,0.2,0.7,0.3}, from which I want a second array {0.1,0.2,0.7,0.3}, as an intermediate in an array formula. Current approaches use single-end anchored ranges (like C$1:C1) to iterate through the items in the array geometrically (by dragging down column C). I would like to leave the array un-iterated, within the formula. I can then manipulate this as I would any other array.

All this should take place in a single cell if possible.

NB

Both MacroMarc's and Barry Houdini's answers are perfectly valid, and I ran a speed check on each - there was negligible difference (any difference was smaller than the variation between test runs). Both scored ~ 1.0±0.2 ms

答:
I have used a defined name for the Range (A1:A5) and called it myList. You can do the same, or substitute in the Address $A$1:$A$5 if you wish:

{=INDEX(myList, N(IF({1}, MODE.MULT(IF(MATCH(myList, myList, 0) = ROW(myList), ROW(myList)*{1,1})))), 1)}

EDIT: Above wasn't robust to handle if the column list is further down the sheet, and a shorter minrow routine courtesy of OP:

{=INDEX(myList, N(IF({1}, MODE.MULT(IF(MATCH(myList, myList, 0)=ROW(myList)-MIN(ROW(myList))+1, (ROW(myList)-MIN(ROW(myList))+1)*{1,1})))), 1)}

This should be ok for you. Needless to say, these are array formulas..


问:
Input and Print
I am trying to get a input to be typed after the "Choice: " but i also want to continue "*" around the whole text... Im  not sure how to do it even after trying multiple times with variations and research i couldn't dind an answer...

```<code>print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *                Choice: ") & print(" *  ")
</code>```

so that it is printed with "Choice:(here will be the input) * "

答:
I can do it this way. But I feel this is really a hack...</p>

```<code>x = input('''
  ********School Quizes********
  *                           *
  *       A) Register         *
  *       B) Loging           *
  *       C) Quit             *
  *                           *
                              *\r  *             Choice:    ''')
</code>```

Title: Input and Print

Body:
I am trying to get a input to be typed after the "Choice: " but i also want to continue "*" around the whole text... Im  not sure how to do it even after trying multiple times with variations and research i couldn't dind an answer...

print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *                Choice: ") & print(" *  ")

so that it is printed with "Choice:(here will be the input) * "

Body:
I can do it this way. But I feel this is really a hack...

x = input('''
  ********School Quizes********
  *                           *
  *       A) Register         *
  *       B) Loging           *
  *       C) Quit             *
  *                           *
                              *\r  *             Choice:    ''')


问:
.FormatString property having no effect on binding
I have this line in my code

```<code>UserLoginLabel.DataBindings.Add(new Binding("Text", Foo, "bar.Username"));
</code>```

Which display the username (and just the username) in the textbox correctly. How come this code

```<code>Binding b = new Binding("Text", Foo, "bar.Username")
{
    FormatString = "Logged in as {0}.",
    FormattingEnabled = true
};
UserLoginLabel.DataBindings.Add(b);
</code>```

has the exact same effect? Is this not how to format a data binding?

答:
You need to use the Format event for this:

```<code>var b = new Binding("Text", Foo, "bar.Username");
b.FormattingEnabled = true;
b.Format += b_Format;
UserLoginLabel.DataBindings.Add(b);

private void b_Format(Object sender, ConvertEventArgs e)
{
    if (e.DesiredType == typeof(String))  //optional, you decide
        e.Value = $"Logged in as {e.Value}.";
}
</code>```

What you have to watch out for is that this will be called every time the value is to be formatted.  That can happen for multiple reasons, so you could get an already-formatted e.Value.

Body:
I have this line in my code

UserLoginLabel.DataBindings.Add(new Binding("Text", Foo, "bar.Username"));

Which display the username (and just the username) in the textbox correctly. How come this code

Binding b = new Binding("Text", Foo, "bar.Username")
{
    FormatString = "Logged in as {0}.",
    FormattingEnabled = true
};
UserLoginLabel.DataBindings.Add(b);

has the exact same effect? Is this not how to format a data binding?

Body:
You need to use the Format event for this:

var b = new Binding("Text", Foo, "bar.Username");
b.FormattingEnabled = true;
b.Format += b_Format;
UserLoginLabel.DataBindings.Add(b);

private void b_Format(Object sender, ConvertEventArgs e)
{
    if (e.DesiredType == typeof(String))  //optional, you decide
        e.Value = $"Logged in as {e.Value}.";
}

What you have to watch out for is that this will be called every time the value is to be formatted.  That can happen for multiple reasons, so you could get an already-formatted e.Value.


答:
What you want is writerow() since you're iterating over the rows.

writerows() takes a list of lists (of rows)

```<code>import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore')

    writer.writeheader()
    for item in data:
        writer.writerow(item)
</code>```

Alternatively, you could use writerows()

```<code>import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore')
    writer.writeheader()
    writer.writerows(data)
</code>```

Title: writing the results of json to a csv

Body:
I'm using DictWriter cause I thought it would be easier but I'm getting no where. I trying to write my json file to a csv file with each field in it's own column.

json file:

[ {"district": "4",
"id": "DEL000027",
"full_name": "Gerald L. Brady", "party": "Democratic",
"email": "Gerald.Brady@state.de.us"},
{"district": "37",
"id": "DEL000028", "full_name": "Ruth Briggs  King",
"party": "Republican",
"email": "Ruth.BriggsKing@state.de.us"}]

here is the script that I wrote:

import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values)

writer.writeheader()
for item in data:
    writer.writerows(item)<----- error but don't know why it's an error

Body:
What you want is writerow() since you're iterating over the rows.

writerows() takes a list of lists (of rows)

import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore')

    writer.writeheader()
    for item in data:
        writer.writerow(item)

Alternatively, you could use writerows()

import json, csv

mainFile = open("vote.json", "r")
data = json.load(mainFile)

with open('names.csv','w') as csvfile:
    values = ['full_name', 'party', 'district','email']
    writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore')
    writer.writeheader()
    writer.writerows(data)


问:
Limit to number of arguments in a controller method in NinjaFramework?
I'm using NinjaFramework 6.0, tried adding a 10th @Param to my controller method and now I get "No suitable method found for with(Controller[...]Index)" error compiling the Routes.java.

My method looks like this:

```<code>public Result personIndex(
        @Param("ssn") Optional<String> ssn,
        @Param("dodId") Optional<String> dodId,
        @Param("firstName") Optional<String> firstName,
        @Param("middleName") Optional<String> middleName,
        @Param("lastName") Optional<String> lastName,
        @Param("birthday") Optional<String> birthday,
        @Param("branch") Optional<String> branch,
        @Param("rateRank") Optional<String> rateRank,
        @Param("status") Optional<String> status,
        @Param("page") Optional<Integer> page) { ... }
</code>```

If I remove one of the params then everything will compile and work. Is this a hard limit?  Should I encapuslate these into some sort of form / dto object?

--

This appears to be a problem when using this type of Route configuration:

router.GET().route("/persons").with(PersonController::personIndex);

If I switch to the 'old' way it works fine:

router.GET().route("/persons").with(PersonController.class, "personIndex");

答:
While browsing Ninja docs (http://www.ninjaframework.org/documentation/basic_concepts/routing.html), I noticed the following text

The class ninja.ControllerMethods defines the various interfaces that are acceptable method signatures for Java 8 lambda expressions. A controller method returns a ninja.Result and has anywhere from 0 to 12 arguments. If you need more than 12 arguments, you can fallback to Ninja’s legacy routing strategy of Class + “method”.

Not sure if something changed from 6.0 version, but 10 params should work.

Body:
I'm using NinjaFramework 6.0, tried adding a 10th @Param to my controller method and now I get "No suitable method found for with(Controller[...]Index)" error compiling the Routes.java.

My method looks like this:

public Result personIndex(
        @Param("ssn") Optional<String> ssn,
        @Param("dodId") Optional<String> dodId,
        @Param("firstName") Optional<String> firstName,
        @Param("middleName") Optional<String> middleName,
        @Param("lastName") Optional<String> lastName,
        @Param("birthday") Optional<String> birthday,
        @Param("branch") Optional<String> branch,
        @Param("rateRank") Optional<String> rateRank,
        @Param("status") Optional<String> status,
        @Param("page") Optional<Integer> page) { ... }

If I remove one of the params then everything will compile and work. Is this a hard limit?  Should I encapuslate these into some sort of form / dto object?

--

This appears to be a problem when using this type of Route configuration:

router.GET().route("/persons").with(PersonController::personIndex);

If I switch to the 'old' way it works fine:

router.GET().route("/persons").with(PersonController.class, "personIndex");


问:
In TortoiseSVN on Windows, is there any utility that allows a user to search for text within the repo?
In TortoiseSVN on Windows, is there any utility that allows a user to search for a text string through the repo? We store a bunch of reporting SQL in SVN and would like to expedite the task of impact analysis on reports when corresponding names change etc. Not sure if all the code is within one repo or not?</p>

答:
If you have Cygwin installed, you can use grep to search all files in a directory.

Open up a Cygwin terminal, and change into your svn directory.

cd /cygdrive/c/pathtoSVNrepo

Then use the following command to search all files in the directory.

grep -REHni searchString .

Replace 'searchString' with your text that you would like to search for. Note that this can also be a regular expression.

The command will produce output in the format: fileName:lineNumber: lineWithMatchingText

Example output:

If you're only interseted in which files contain the string, just an 'l' to the options.

grep -REHnil searchString .


问:
Replace special character in data frame
I have a dataframe which contains in different cells a special character which I know which is. An example of the structure:

```<code>df = data.frame(col_1 = c("21 myspec^ch2 12",NA),
                col_2 = c("1 myspec^ch2 4","4 myspec^ch2 212"))
</code>```

The character is this  myspec^ch2 and I would like to replace with -. An example of expected output:

```<code>df = data.frame(col_1 = c("21-12",NA),
                col_2 = c("1-4","4-212"))
</code>```

I tried this but it is not working:

```<code>df [ df == " myspec^ch2 " ] <- "-"
</code>```

答:
To get gsub work on whole dataframe use apply:

```<code>apply(df, 2, function(x) gsub(" myspec\\^ch2 ", "-", x))
</code>```

Title: Replace special character in data frame

Body:
I have a dataframe which contains in different cells a special character which I know which is. An example of the structure:

df = data.frame(col_1 = c("21 myspec^ch2 12",NA),
                col_2 = c("1 myspec^ch2 4","4 myspec^ch2 212"))

The character is this  myspec^ch2 and I would like to replace with -. An example of expected output:

df = data.frame(col_1 = c("21-12",NA),
                col_2 = c("1-4","4-212"))

I tried this but it is not working:

df [ df == " myspec^ch2 " ] <- "-"

Body:
To get gsub work on whole dataframe use apply:

apply(df, 2, function(x) gsub(" myspec\\^ch2 ", "-", x))


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答:
We use JAMWiki and love it.

It is a solid application, we have had nothing but good interaction with both the application and the developers.

The guy you maintains the code does a great job answering questions and helping users out.

Title: Coding Standard Wiki

OwnerDisplayName: Berek Bryan


问:
How do I group all values in a pandas column that have a frequency of 2 or less
Here is a fictitious example:

```<code>id cluster
1 3
2 3
3 3
4 1
5 5
</code>```

So the cluster for id 4 and 5 should be replaced by some text.

So, I'm able to find which values have a frequency of less than 3 using:

```<code>counts = distclust.groupby("cluster")["cluster"].count()
counts[counts < 3].index.values
</code>```

Now, I'm not sure I go and replace these values in my dataframe with some arbitrary text (i.e. "noise")

I think that is enough information, let me know if you'd like me to include anything else:

答:
```<code>In [82]: df.groupby('cluster').filter(lambda x: len(x) <= 2)
Out[82]:
   id  cluster
3   4        1
4   5        5
</code>```

updating:

```<code>In [95]: idx = df.groupby('cluster').filter(lambda x: len(x) <= 2).index

In [96]: df.loc[idx, 'cluster'] = -999

In [97]: df
Out[97]:
   id  cluster
0   1        3
1   2        3
2   3        3
3   4     -999
4   5     -999
</code>```

Body:
Here is a fictitious example:

id cluster
1 3
2 3
3 3
4 1
5 5

So the cluster for id 4 and 5 should be replaced by some text.

So, I'm able to find which values have a frequency of less than 3 using:

counts = distclust.groupby("cluster")["cluster"].count()
counts[counts < 3].index.values

Now, I'm not sure I go and replace these values in my dataframe with some arbitrary text (i.e. "noise")

I think that is enough information, let me know if you'd like me to include anything else:

Body:
In [82]: df.groupby('cluster').filter(lambda x: len(x) <= 2)
Out[82]:
   id  cluster
3   4        1
4   5        5

updating:

In [95]: idx = df.groupby('cluster').filter(lambda x: len(x) <= 2).index

In [96]: df.loc[idx, 'cluster'] = -999

In [97]: df
Out[97]:
   id  cluster
0   1        3
1   2        3
2   3        3
3   4     -999
4   5     -999


问:
How to get from a subscriptions data to transactional data in Tableau?
I have a chunk of data with subscriptions looking as following:

```<code>customer_name    start_date   end_date     subscription_amount
A                1-7-2017     31-10-2017   4 USD/month
B                1-8-2017     30-09-2017   2 USD/month
C                1-10-2017    30-11-2017   3 USD/month
</code>```

I need to convert it to transactional data, so the end result should look as following:

```<code>customer_name    payment_date    amount
A                1-7-2017        4 USD
A                1-8-2017        4 USD
A                1-9-2017        4 USD
A                1-10-2017       4 USD
B                1-8-2017        2 USD
B                1-9-2017        2 USD
C                1-10-2017       3 USD
C                1-11-2017       3 USD
</code>```

I need to do this conversion to run the analysis in Tableau, but Excel solutions are also acceptable. I do not want to do it manually, rather I am looking for automated solution with SQL or Python (I am new to both of those)

答:
Here a  Query in MS-SQL

if object_id('tempdb..#subscriptions') IS NOT NULL DROP TABLE #subscriptions
if object_id('tempdb..#Calendar') IS NOT NULL DROP TABLE #Calendar

declare @min_date as date
declare @max_date as date

create table #subscriptions
(
   customer_name char,
   startdate date,
   end_date  date,
   subscription_amount money,
   currencyPeriod varchar(10)
)

create table #Calendar
(
    Date_f date
)

insert into #subscriptions  values('A',CAST('2017-7-01 00:00:00.000' as date),CAST('2017-07-10 00:00:00.000' as date),4,'USD/month')
insert into #subscriptions values('B',CAST('2017-8-01 00:00:00.000' as date),CAST('2017-08-04 00:00:00.000' as date),2,'USD/month')
insert into #subscriptions  values('C',CAST('2017-10-01 00:00:00' as date),CAST('2017-10-02 00:00:00.000' as date),3,'USD/month')

---here we need to get the MIN and MAX date of all register
set @min_date = (select MIN(startdate) FROM #subscriptions)
set @max_date = (select MAX(end_date) FROM #subscriptions)

--Here we Create a Temp Calendar respect of the min and max date of all register

WHILE @min_date <= @max_date
BEGIN
  INSERT INTO #Calendar (Date_f)
  SELECT @min_date

SET @min_date = DATEADD(day, 1,@min_date)
END

--FINAL RESULT
SELECT B.customer_name,A.Date_f as 'payment_date',
CONCAT(CAST(subscription_amount as int),' ','USD') as 'subscription_amount'

FROM #Calendar A
INNER JOIN #subscriptions B
ON A.Date_f BETWEEN startdate AND end_date

Body:
I have a chunk of data with subscriptions looking as following:

customer_name    start_date   end_date     subscription_amount
A                1-7-2017     31-10-2017   4 USD/month
B                1-8-2017     30-09-2017   2 USD/month
C                1-10-2017    30-11-2017   3 USD/month

I need to convert it to transactional data, so the end result should look as following:

customer_name    payment_date    amount
A                1-7-2017        4 USD
A                1-8-2017        4 USD
A                1-9-2017        4 USD
A                1-10-2017       4 USD
B                1-8-2017        2 USD
B                1-9-2017        2 USD
C                1-10-2017       3 USD
C                1-11-2017       3 USD

I need to do this conversion to run the analysis in Tableau, but Excel solutions are also acceptable. I do not want to do it manually, rather I am looking for automated solution with SQL or Python (I am new to both of those)


问:
How to get text content first preceding and following text node in DOM using given xpath?
I have a DOM say:

```<code><div>
    <span>
    Create Account
    </span>

    <label>Enter first name </label>
    <input type="text" id="firstName"> First name
    </input>

    <label>Enter last name </label>
    <input type="text" id="lastName"> Last name
    </input>

</div>
</code>```

Now, Suppose I have only Xpath for id="firstName" as //input[@id='firstName'].
Now if I want to know textContent of the first preceding("Enter first name") and following("Enter last name") text node.
How I can get that ?

I tried this: //input[@id='firstName']/preceding::*[text()][1] similarly //input[@id='firstName']/following::*[text()][1]

But they instead give me complete element node, I just want text content.

答:
Try below XPath to match both text nodes:</p>

```<code>//label[following-sibling::input[@id='firstName'][1] or preceding-sibling::input[@id='firstName'][1]]/text()
</code>```

Body:
I have a DOM say:

    Create Account

    Enter first name
    <input type="text" id="firstName"> First name
    </input>

    Enter last name
    <input type="text" id="lastName"> Last name
    </input>

Now, Suppose I have only Xpath for id="firstName" as //input[@id='firstName'].
Now if I want to know textContent of the first preceding("Enter first name") and following("Enter last name") text node.
How I can get that ?

I tried this: //input[@id='firstName']/preceding::*[text()][1] similarly //input[@id='firstName']/following::*[text()][1]

But they instead give me complete element node, I just want text content.

Body:
Try below XPath to match both text nodes:

//label[following-sibling::input[@id='firstName'][1] or preceding-sibling::input[@id='firstName'][1]]/text()


问:
Load domain cookies by XHR Request
When I send an XHR Request to an URL, how can I get the Cookies in my PHP Script:

Example:

```<code>var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xhr.open("POST", 'http://127.0.0.1/index.php', true);
</code>```

And for http://127.0.0.1 I have a lot of cookies. But when the request is send, then I can not catch the cookies.

答:
It practicaly not possible to get the cookies form the browser with XHR Request like this obove, because the call is going direct to the server but the cookies are in the browser.

The only way to do this is to generate an Iframe in similar way:

```<code>var iframe = document.createElement('iframe');
iframe.frameBorder = 0;
iframe.width = 1;
iframe.height = 1;
iframe.name= "stlconv";
iframe.scrolling = "no";
iframe.allowtransparency = "true";
iframe.vspace = "0";
iframe.hspace = "0";
iframe.marginwidth = "0";
iframe.marginheight = "0";
iframe.src = url;
document.body.appendChild(iframe);
</code>```

In this case you have an HTML element opened in the browser again and you can catch the cookies.

Title: Load domain cookies by XHR Request

Body:
When I send an XHR Request to an URL, how can I get the Cookies in my PHP Script:

Example:

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xhr.open("POST", 'http://127.0.0.1/index.php', true);

And for http://127.0.0.1 I have a lot of cookies. But when the request is send, then I can not catch the cookies.

Body:
It practicaly not possible to get the cookies form the browser with XHR Request like this obove, because the call is going direct to the server but the cookies are in the browser.

The only way to do this is to generate an Iframe in similar way:

var iframe = document.createElement('iframe');
iframe.frameBorder = 0;
iframe.width = 1;
iframe.height = 1;
iframe.name= "stlconv";
iframe.scrolling = "no";
iframe.allowtransparency = "true";
iframe.vspace = "0";
iframe.hspace = "0";
iframe.marginwidth = "0";
iframe.marginheight = "0";
iframe.src = url;
document.body.appendChild(iframe);

In this case you have an HTML element opened in the browser again and you can catch the cookies.