问:
Specify Encoding Format when Export DataTable to Excel with Open Xml SDK in c#
I am just trying to export datatable as excel using open xml. Referred the below approach,

Export DataTable to Excel with Open Xml SDK in c#

But I couldn't specify the encoding format of the excel created. I want to save or create the excecl with UTF-Encoding-8 format.

Can some one help on how could the formatting specificed using Open XML

答:
To save an Excel file with UTF-Encoding-8 Format you need to specify the encoding format under Tools -> Web Options -> Encoding while saving the excel file.

With OpenXML you need to create a new WebPublishing and add it to Workbook.

```<code>WebPublishing webPublishing1 = new WebPublishing(){ AllowPng = true, TargetScreenSize = TargetScreenSizeValues.Sz1024x768, CodePage = (UInt32Value)65001U };
workbook1.Append(webPublishing1);
//Where workbook1 is WorkbookPart.Workbook
</code>```

Body:
To save an Excel file with UTF-Encoding-8 Format you need to specify the encoding format under Tools -> Web Options -> Encoding while saving the excel file.

With OpenXML you need to create a new WebPublishing and add it to Workbook.

WebPublishing webPublishing1 = new WebPublishing(){ AllowPng = true, TargetScreenSize = TargetScreenSizeValues.Sz1024x768, CodePage = (UInt32Value)65001U };
workbook1.Append(webPublishing1);
//Where workbook1 is WorkbookPart.Workbook


来源: stackexchange

问:
Pandas Filter by string
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F
</code>```

Returns:

```<code>Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

When I change apply to filter I get an error.

Help Please!

答:
try this little fella</p>

```<code>df['mydummy'] = x['C']== T
df['mysum'] = df.groupby('A').mydummy.transform('sum')
df['mycount'] = df.groupby('A').mysum.transform('size')
df = df.loc[mysum == mycount]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pandas Filter by string

Body:
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F

Returns:

Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

When I change apply to filter I get an error.

Help Please!

Body:
try this little fella

df['mydummy'] = x['C']== T
df['mysum'] = df.groupby('A').mydummy.transform('sum')
df['mycount'] = df.groupby('A').mysum.transform('size')
df = df.loc[mysum == mycount]


问:
Java confused on how to arrange "if" statements
```<code>int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");

    System.out.println("[1 - Attack]");
    System.out.println("[2 - Flee]");

    answer = In.getInt();

    System.out.println("\n");

    if (answer == 1) {

        if (user.getP_HP() > 0) {
            d = enemies[i].getHP() - user.getP_ATK();
            enemies[i].setHP(d);

            System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
            System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
            System.out.println("\n");
        } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
        }

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}
</code>```

Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.

This works only if the player kills the goblin first, and not vice versa.

Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.

Here is the sample output if the enemy kills you first:

```<code>stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.

Hitpoints[HP]: 12
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.

Hitpoints[HP]: 11
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.
</code>```

答:
You actually want to do things in the following order (assuming that you attack):

Ask the player whether they want to attack or flee

You attack

See if you killed the monster; if so, the game is over

The monster attacks

See if the monster killed you; if so, the game is over

Repeat until either #3 or #5 occurs

You reverse #3 and #5.

Also, the following line:

```<code>else if (enemies[1].getHP() <= 0)
</code>```

has what I assume is a typo. I assume that you actually meant to do

```<code>else if (enemies[i].getHP() <= 0)
</code>```

Body:
int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");

    System.out.println("[1 - Attack]");
    System.out.println("[2 - Flee]");

    answer = In.getInt();

    System.out.println("\n");

    if (answer == 1) {

        if (user.getP_HP() > 0) {
            d = enemies[i].getHP() - user.getP_ATK();
            enemies[i].setHP(d);

            System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
            System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
            System.out.println("\n");
        } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
        }

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}

Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.

This works only if the player kills the goblin first, and not vice versa.

Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.

Here is the sample output if the enemy kills you first:

stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.

Hitpoints[HP]: 12
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.

Hitpoints[HP]: 11
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.

Body:
You actually want to do things in the following order (assuming that you attack):

Ask the player whether they want to attack or flee

You attack

See if you killed the monster; if so, the game is over

The monster attacks

See if the monster killed you; if so, the game is over

Repeat until either #3 or #5 occurs

You reverse #3 and #5.

Also, the following line:

else if (enemies[1].getHP() <= 0)

has what I assume is a typo. I assume that you actually meant to do

else if (enemies[i].getHP() <= 0)


问:
Delphi TStringList Find method cannot find item
I am writing my own class to manage the translation of android/ios app and I have produced this code. I will explain the code below but it's pretty easy and short.

```<code>unit Localization;

interface

uses
 System.Classes, System.SysUtils, Generics.Collections, Vcl.Dialogs;

//this class represents a single language (Italian, French, German...)
type
 TLanguage = class
  private
   FTranslationList: TDictionary<string, string>;
   function localize(const aWordId: string): string;
  public
   constructor Create;
   destructor Destroy; override;
   //methods
   procedure addWord(const aIndex, aWord: string);
   procedure removeWord(const aIndex: string);
 end;

//this is a "container", it gathers all the languages in one place
type
 TLocalization = class
  private
   FLanguagesList: TObjectList<TLanguage>;
   FLocaleList: TStringList;
   function getLang(Index: string): TLanguage;
  public
   constructor Create;
   destructor Destroy; override;
   //methods
   function localize(const aLocaleId: string; const aIndex: string): string;
   procedure addLanguage(const localeId: string);
   //property to manage the languages
   property Locale[Index: string]: TLanguage read getLang;
   property langCount: integer read getCount;
 end;

implementation

{ TLocalization }

{ add a new language to the class. }
{the localeId is a symbol like 'it' that represents the Italian language}
procedure TLocalization.addLanguage(const localeId: string);
begin
 //add the language to the languages container
 FLanguagesList.Add(TLanguage.Create);
 //add the representation of the language.
 FLocaleList.Add(localeId);
end;

constructor TLocalization.Create;
begin
 FLanguagesList := TObjectList<TLanguage>.Create;
 FLocaleList := TStringList.Create;
end;

destructor TLocalization.Destroy;
begin
 FLanguagesList.Free;
 FLocaleList.Free;
 inherited;
end;

//ERROR HERE
function TLocalization.getLang(Index: string): TLanguage;
var i: integer;
begin

 { I search the locale id (for example 'it') if it's in the list. }
 { if it's in the list, I return the respective TLanguage object}
 if not( FLocaleList.Find(Index, i) ) then
  Result := FLanguagesList.Items[i]
 else
  raise Exception.Create('Locale not found');

end;

function TLocalization.localize(const aLocaleId, aIndex: string): string;
var k: integer;
begin

 k := 0;

 if not( FLocaleList.Find(aLocaleId, k) ) then
  raise Exception.Create('Locale not found.');

 //ho trovato il locale, adesso basta cercare la parola
 Result := FLanguagesList.Items[k].localize(aIndex);

end;

{ TLanguage }

procedure TLanguage.addWord(const aIndex, aWord: string);
begin
 FTranslationList.Add(aIndex, aWord);
end;

constructor TLanguage.Create;
begin
 FTranslationList := TDictionary<string, string>.Create;
end;

destructor TLanguage.Destroy;
begin
 FTranslationList.Free;
 inherited;
end;

function TLanguage.localize(const aWordId: string): string;
begin

 try
  Result := FTranslationList.Items[aWordId];
 except
  Result := 'Not found.';
 end;

end;

procedure TLanguage.removeWord(const aIndex: string);
begin
 FTranslationList.Remove(aIndex);
end;

end.
</code>```

The code above is used as follows:

```<code>var a: TLocalization;
begin
  a := TLocalization.Create;

  a.addLanguage('it');
  a.addLanguage('cse');
  a.Locale['it'].addWord('test', 'Ciao mondo!');
  a.Locale['cse'].addWord('test', 'fadfa ea!');

  ButtonSomething.Text := a.localize('it', test);

end;
</code>```

The TLocalization class does all the work. As you can see I create the variable a, then I add a language to the class (this is managed internally using a dictionary/stringlist).

I can access the languages I have added using the Locale[Index: string] property which returns a TLanguage, a class that I use to indicate a single lang. At the end with the localize method I get my translation.

Oddly enough I always get the error 'Locale not found'. Any idea? Using the debugger I have discovered this:

The FLocaleList has items but I have tested this and I guess that I am doing something wrong on line 71 (where I use the Find function). Am I passing wrongly the Index maybe?

答:
Your code logic is backwards.  Find() returns True if it finds a match, otherwise it returns False.  You are accessing Items[] if Find() returns False, and raising an exception if it returns True.  You need to remove the not in your if statement:

```<code>function TLocalization.getLang(Index: string): TLanguage;
var
  i: integer;
begin
  { I search the locale id (for example 'it') if it's in the list. }
  { if it's in the list, I return the respective TLanguage object}
  if FLocaleList.Find(Index, i) then // <-- HERE
    Result := FLanguagesList.Items[i]
  else
    raise Exception.Create('Locale not found');
end;
</code>```

But, more importantly, the Find() documentation says:

Note: Only use Find with sorted lists. For unsorted lists, use the IndexOf method instead.

Your list is unsorted, as the Sorted property is false by default.  So use IndexOf() instead:

```<code>function TLocalization.getLang(Index: string): TLanguage;
var
  i: integer;
begin
  { I search the locale id (for example 'it') if it's in the list. }
  { if it's in the list, I return the respective TLanguage object}
  i := FLocaleList.IndexOf(Index);
  if i <> -1 then
    Result := FLanguagesList.Items[i]
  else
    raise Exception.Create('Locale not found');
end;
</code>```

Body:
I am writing my own class to manage the translation of android/ios app and I have produced this code. I will explain the code below but it's pretty easy and short.

unit Localization;

interface

uses
 System.Classes, System.SysUtils, Generics.Collections, Vcl.Dialogs;

//this class represents a single language (Italian, French, German...)
type
 TLanguage = class
  private
   FTranslationList: TDictionary<string, string>;
   function localize(const aWordId: string): string;
  public
   constructor Create;
   destructor Destroy; override;
   //methods
   procedure addWord(const aIndex, aWord: string);
   procedure removeWord(const aIndex: string);
 end;

//this is a "container", it gathers all the languages in one place
type
 TLocalization = class
  private
   FLanguagesList: TObjectList<TLanguage>;
   FLocaleList: TStringList;
   function getLang(Index: string): TLanguage;
  public
   constructor Create;
   destructor Destroy; override;
   //methods
   function localize(const aLocaleId: string; const aIndex: string): string;
   procedure addLanguage(const localeId: string);
   //property to manage the languages
   property Locale[Index: string]: TLanguage read getLang;
   property langCount: integer read getCount;
 end;

implementation

{ TLocalization }

{ add a new language to the class. }
{the localeId is a symbol like 'it' that represents the Italian language}
procedure TLocalization.addLanguage(const localeId: string);
begin
 //add the language to the languages container
 FLanguagesList.Add(TLanguage.Create);
 //add the representation of the language.
 FLocaleList.Add(localeId);
end;

constructor TLocalization.Create;
begin
 FLanguagesList := TObjectList<TLanguage>.Create;
 FLocaleList := TStringList.Create;
end;

destructor TLocalization.Destroy;
begin
 FLanguagesList.Free;
 FLocaleList.Free;
 inherited;
end;

//ERROR HERE
function TLocalization.getLang(Index: string): TLanguage;
var i: integer;
begin

 { I search the locale id (for example 'it') if it's in the list. }
 { if it's in the list, I return the respective TLanguage object}
 if not( FLocaleList.Find(Index, i) ) then
  Result := FLanguagesList.Items[i]
 else
  raise Exception.Create('Locale not found');

end;

function TLocalization.localize(const aLocaleId, aIndex: string): string;
var k: integer;
begin

 k := 0;

 if not( FLocaleList.Find(aLocaleId, k) ) then
  raise Exception.Create('Locale not found.');

 //ho trovato il locale, adesso basta cercare la parola
 Result := FLanguagesList.Items[k].localize(aIndex);

end;

{ TLanguage }

procedure TLanguage.addWord(const aIndex, aWord: string);
begin
 FTranslationList.Add(aIndex, aWord);
end;

constructor TLanguage.Create;
begin
 FTranslationList := TDictionary<string, string>.Create;
end;

destructor TLanguage.Destroy;
begin
 FTranslationList.Free;
 inherited;
end;

function TLanguage.localize(const aWordId: string): string;
begin

 try
  Result := FTranslationList.Items[aWordId];
 except
  Result := 'Not found.';
 end;

end;

procedure TLanguage.removeWord(const aIndex: string);
begin
 FTranslationList.Remove(aIndex);
end;

end.

The code above is used as follows:

var a: TLocalization;
begin
  a := TLocalization.Create;

  a.addLanguage('it');
  a.addLanguage('cse');
  a.Locale['it'].addWord('test', 'Ciao mondo!');
  a.Locale['cse'].addWord('test', 'fadfa ea!');

  ButtonSomething.Text := a.localize('it', test);

end;

The TLocalization class does all the work. As you can see I create the variable a, then I add a language to the class (this is managed internally using a dictionary/stringlist).

I can access the languages I have added using the Locale[Index: string] property which returns a TLanguage, a class that I use to indicate a single lang. At the end with the localize method I get my translation.

Oddly enough I always get the error 'Locale not found'. Any idea? Using the debugger I have discovered this:

The FLocaleList has items but I have tested this and I guess that I am doing something wrong on line 71 (where I use the Find function). Am I passing wrongly the Index maybe?

Body:
Your code logic is backwards.  Find() returns True if it finds a match, otherwise it returns False.  You are accessing Items[] if Find() returns False, and raising an exception if it returns True.  You need to remove the not in your if statement:

function TLocalization.getLang(Index: string): TLanguage;
var
  i: integer;
begin
  { I search the locale id (for example 'it') if it's in the list. }
  { if it's in the list, I return the respective TLanguage object}
  if FLocaleList.Find(Index, i) then // <-- HERE
    Result := FLanguagesList.Items[i]
  else
    raise Exception.Create('Locale not found');
end;

But, more importantly, the Find() documentation says:

Note: Only use Find with sorted lists. For unsorted lists, use the IndexOf method instead.

Your list is unsorted, as the Sorted property is false by default.  So use IndexOf() instead:

function TLocalization.getLang(Index: string): TLanguage;
var
  i: integer;
begin
  { I search the locale id (for example 'it') if it's in the list. }
  { if it's in the list, I return the respective TLanguage object}
  i := FLocaleList.IndexOf(Index);
  if i <> -1 then
    Result := FLanguagesList.Items[i]
  else
    raise Exception.Create('Locale not found');
end;


问:
How to construct a graphql mutation query request in php
I am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.

If I hard code the string and use it as the data in my POST request it works like this:
'{"query":"mutation{addPlay(input: {title: \"two\"}){ properties { title } } }"}'

But if I have a php array of the input values:

```<code>$test_data = array(
  'title' => 'two'
);
</code>```

I can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error Syntax Error GraphQL request (1:26) Expected Name, found String.

I ultimately need a solution that will convert a larger more complex array to something usable.

答:
Reformatting the query allowed me to use JSON directly.

So my new query looks like this:

```<code>$test_data = array(
  'title' => 'two'
);

$request_data = array(
  'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',
  'variables' => array(
    'input' => $test_data,
  ),
);

$request_data_json = json_encode($request_data);
</code>```

Then the $request_data_json is used in a POST http request.

Body:
I am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.

If I hard code the string and use it as the data in my POST request it works like this:
'{"query":"mutation{addPlay(input: {title: \"two\"}){ properties { title } } }"}'

But if I have a php array of the input values:

$test_data = array(
  'title' => 'two'
);

I can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error Syntax Error GraphQL request (1:26) Expected Name, found String.

I ultimately need a solution that will convert a larger more complex array to something usable.

Body:
Reformatting the query allowed me to use JSON directly.

So my new query looks like this:

$test_data = array(
  'title' => 'two'
);

$request_data = array(
  'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',
  'variables' => array(
    'input' => $test_data,
  ),
);

$request_data_json = json_encode($request_data);

Then the $request_data_json is used in a POST http request.


问:
Finding the greatest amount of consecutive values in an array (JS)
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

```<code>[false, false, true, false, true, false, true, false, false, false]
</code>```

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!

答:
Try this function to count number of consecutive false in array:

```<code>function countNumFalse(arr){
    var max = 0;
    var condFalse = false;
    var numFalse = 0;
    for (var i = 0; i < arr.length; i++) {
        condFalse = condFalse || arr[i];
        if(condFalse === true){
           condFalse = false;
           numFalse = 0;
        }
        else{
             numFalse++;
          if(numFalse > max){
             max = numFalse;
          }
        }
    }
    return max;
}

var arr1 = [false, false, true, false, true, false, true, false, false, false];

countNumFalse(arr1);
3
</code>```

Body:
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

[false, false, true, false, true, false, true, false, false, false]

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!

Body:
Try this function to count number of consecutive false in array:

function countNumFalse(arr){
    var max = 0;
    var condFalse = false;
    var numFalse = 0;
    for (var i = 0; i < arr.length; i++) {
        condFalse = condFalse || arr[i];
        if(condFalse === true){
           condFalse = false;
           numFalse = 0;
        }
        else{
             numFalse++;
          if(numFalse > max){
             max = numFalse;
          }
        }
    }
    return max;
}

var arr1 = [false, false, true, false, true, false, true, false, false, false];

countNumFalse(arr1);
3


问:
What is the use of Java Char array?
I have a Java code associated with BigInteger class below,

```<code>import java.math.BigInteger;

public class Main
{
    public static void main (String[] args)
    {
        BigInteger num = new BigInteger("123456789101112131415");

        String str;
        char []Char = new char[10];

        str = num.toString();
        Char = str.toCharArray();

        System.out.println(str.length());
        System.out.println(Char.length);
    }
}
</code>```

In that code, I have a BigInteger num which has 21 digits. I converted it into a String then into a Char array. But I assigned the length of that char array is just 10 before. So how this char array holds 21 characters altogether???

I really misunderstand the fact.

And one more question here, is there any method to convert BigIntegers into char arrays directly? :)

答:
To answer your first question, the variable Char (consider changing your variable names) is a reference to a char array. You set it to point to an array of size 10. But later, thanks to...

```<code>Char = str.toCharArray();
</code>```

...you are making the reference point to another array. The original array no longer has a reference associated with it and is garbage collected.

To answer your second question, you can cascade functions in a single line.

```<code>char[] Char = num.toString().toCharArray();
</code>```

Title: What is the use of Java Char array?

Body:
I have a Java code associated with BigInteger class below,

import java.math.BigInteger;

public class Main
{
    public static void main (String[] args)
    {
        BigInteger num = new BigInteger("123456789101112131415");

        String str;
        char []Char = new char[10];

        str = num.toString();
        Char = str.toCharArray();

        System.out.println(str.length());
        System.out.println(Char.length);
    }
}

In that code, I have a BigInteger num which has 21 digits. I converted it into a String then into a Char array. But I assigned the length of that char array is just 10 before. So how this char array holds 21 characters altogether???

I really misunderstand the fact.

And one more question here, is there any method to convert BigIntegers into char arrays directly? :)

Body:
To answer your first question, the variable Char (consider changing your variable names) is a reference to a char array. You set it to point to an array of size 10. But later, thanks to...

Char = str.toCharArray();

...you are making the reference point to another array. The original array no longer has a reference associated with it and is garbage collected.

To answer your second question, you can cascade functions in a single line.

char[] Char = num.toString().toCharArray();


答:
It seems like instead of using else if, what you want is something like this:

```<code>// Process both attacks first.
if (user.getP_HP() > 0) {
    d = enemies[i].getHP() - user.getP_ATK();
    enemies[i].setHP(d);

    // ...
}
if (enemies[i].getHP() > 0) {
    e = user.getP_HP() - enemies[i].getATK();
    user.setP_HP(e);

    // ...
}
// Then resolve the deaths immediately after.
if (user.getP_HP() <= 0) {
    // ...
    alive = false;
}
if (enemies[1].getHP() <= 0) {
    // ...
    alive = false;
}
</code>```

Title: Java confused on how to arrange "if" statements

Body:
It seems like instead of using else if, what you want is something like this:

// Process both attacks first.
if (user.getP_HP() > 0) {
    d = enemies[i].getHP() - user.getP_ATK();
    enemies[i].setHP(d);

    // ...
}
if (enemies[i].getHP() > 0) {
    e = user.getP_HP() - enemies[i].getATK();
    user.setP_HP(e);

    // ...
}
// Then resolve the deaths immediately after.
if (user.getP_HP() <= 0) {
    // ...
    alive = false;
}
if (enemies[1].getHP() <= 0) {
    // ...
    alive = false;
}


问:
Hibernate 'Inverse' in mapping file
Can someone explain the use of inverse in the xml mapping file, I am reading the tutorial but failing to understand its use in the mapping file??

Thanks

答:
If a collection is marked as "inverse", then Hibernate will not execute any SQL to maintain the collection in the database.

For example, one-to-many collections are often (in my experience, practically always) marked as inverse: the "many" entities (members of the collection) have a column with the parent's ID (mapped as a many-to-one property), and simply creating one of those entities means that it will be implicitly included in the collection, so no need to explicitly update them.

If using a many-to-many collection (which of course usually occur in pairs), one of the collections needs to be marked as "inverse", otherwise Hibernate will try to create the join table entries representing the collection twice.

ContentLicense: CC BY-SA 2.5

Title: Hibernate 'Inverse' in mapping file


问:
VBA - Run Macro from Word to paste values into Excel
I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word.  The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.

The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.

```<code>Sub Transfer()

Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook

Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook

WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste

End Sub
</code>```

答:
Your Selection is referring to the current application.  To refer to the Excel application you need to use ED.Selection.  But it is a bad idea to rely on Activate and Select anyway.

I suggest you change your code to:

```<code>Sub Transfer()

    Dim WD As Document
    Dim ED As Excel.Application
    Dim EDS As Excel.Workbook

    Set WD = ActiveDocument
    Set ED = CreateObject("excel.application")
    ED.Visible = True
    'Avoid "Activate"
    Set EDS = ED.Workbooks.Open(FileName:= _
             "C:\Users\Documents\AppealData.xlsx")

    WD.FormFields("AppNum").Copy
    'Avoid "Activate" and "Select" and "Selection"
    '"Paste" is a worksheet Method, use "PasteSpecial" for a Range
    'Use "xlPasteValues" to avoid formatting issues
    EDS.Sheets("Sheet1").Range("A1").PasteSpecial Excel.xlPasteValues
End Sub
</code>```

Body:
I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word.  The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.

The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.

Sub Transfer()

Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook

Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook

WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste

End Sub

Body:
Your Selection is referring to the current application.  To refer to the Excel application you need to use ED.Selection.  But it is a bad idea to rely on Activate and Select anyway.

I suggest you change your code to:

Sub Transfer()

    Dim WD As Document
    Dim ED As Excel.Application
    Dim EDS As Excel.Workbook

    Set WD = ActiveDocument
    Set ED = CreateObject("excel.application")
    ED.Visible = True
    'Avoid "Activate"
    Set EDS = ED.Workbooks.Open(FileName:= _
             "C:\Users\Documents\AppealData.xlsx")

    WD.FormFields("AppNum").Copy
    'Avoid "Activate" and "Select" and "Selection"
    '"Paste" is a worksheet Method, use "PasteSpecial" for a Range
    'Use "xlPasteValues" to avoid formatting issues
    EDS.Sheets("Sheet1").Range("A1").PasteSpecial Excel.xlPasteValues
End Sub


问:
Thrust reduction and overloaded operator-(const float3&, const float3&) won't compile
I overload operators to have a vector space over float3 (and similar structs) in vectorspace.cuh:

```<code>// Boilerplate vector space over data type Pt
#pragma once

#include <type_traits>

// float3
__device__ __host__ float3 operator+=(float3& a, const float3& b) {
    a.x += b.x; a.y += b.y; a.z += b.z;
    return a;
}

__device__ __host__ float3 operator*=(float3& a, const float b) {
    a.x *= b; a.y *= b; a.z *= b;
    return a;
}

// float4
__device__ __host__ float4 operator+=(float4& a, const float4& b) {
    a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
    return a;
}

__device__ __host__ float4 operator*=(float4& a, const float b) {
    a.x *= b; a.y *= b; a.z *= b; a.w *= b;
    return a;
}

// Generalize += and *= to +, -=, -, *, /= and /
template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator+(const Pt& a, const Pt& b) {
    auto sum = a;
    sum += b;
    return sum;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-=(Pt& a, const Pt& b) {
    a += -1*b;
    return a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-(const Pt& a, const Pt& b) {
    auto diff = a;
    diff -= b;
    return diff;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-(const Pt& a) {
    return -1*a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator*(const Pt& a, const float b) {
    auto prod = a;
    prod *= b;
    return prod;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator*(const float b, const Pt& a) {
    auto prod = a;
    prod *= b;
    return prod;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator/=(Pt& a, const float b) {
    a *= 1./b;
    return a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator/(const Pt& a, const float b) {
    auto quot = a;
    quot /= b;
    return quot;
}
</code>```

These overloads break compilation of thrust::reduce, here an example:

```<code>#include <thrust/reduce.h>
#include <thrust/execution_policy.h>

#include "vectorspace.cuh"

int main(int argc, char const *argv[]) {
    int n = 10;
    float3* d_arr;
    cudaMalloc(&d_arr, n*sizeof(float3));

    auto sum = thrust::reduce(thrust::device, d_arr, d_arr + n, float3 {0});

    return 0;
}
</code>```

Using nvcc -std=c++11 -arch=sm_52 on Ubuntu 16.04 this results in 200+ lines of compiler errors:

```<code>$ nvcc -std=c++11 -arch=sm_52 sandbox/mean.cu
sandbox/mean.cu(26): error: no operator "*" matches these operands
            operand types are: int * const thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>
          detected during:
            instantiation of "std::enable_if<<expression>, Pt>::type operator-=(Pt &, const Pt &) [with Pt=thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>]"
(35): here
            instantiation of "std::enable_if<<expression>, Pt>::type operator-(const Pt &, const Pt &) [with Pt=thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>]"

...
</code>```

How can I overload the operators without breaking thrust?

答:
(Edited following OP's edits.)

The problem is with the 'reach' of your operator overloads: You are not overloading only for the classes you're interested in, but for all classes fitting your enable_if condition - which is quite relaxed. That's already a serious bug even if things would compile.

More specifically, thrust uses arithmetic operations, e.g. on "zip iterators" (never mind what they are), and compilations of your operations for such iterators fails, understandably.

So you must either:

Specify exactly which classes the overload is relevant to (e.g., using a disjunction of std::is_same in the enable_if), or

use a trait class:

```<code>template<class T> struct needs_qivs_arithmetic_operators : public std::false_type {};

template<> struct needs_qivs_arithmetic_operators<float3> : public std::true_type {};
template<> struct needs_qivs_arithmetic_operators<float4> : public std::true_type {};
/* ... etc. You can also add specializations elsewhere in the translation unit. */
</code>```

Body:
I overload operators to have a vector space over float3 (and similar structs) in vectorspace.cuh:

// Boilerplate vector space over data type Pt
#pragma once

#include <type_traits>

// float3
__device__ __host__ float3 operator+=(float3& a, const float3& b) {
    a.x += b.x; a.y += b.y; a.z += b.z;
    return a;
}

__device__ __host__ float3 operator*=(float3& a, const float b) {
    a.x *= b; a.y *= b; a.z *= b;
    return a;
}

// float4
__device__ __host__ float4 operator+=(float4& a, const float4& b) {
    a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
    return a;
}

__device__ __host__ float4 operator*=(float4& a, const float b) {
    a.x *= b; a.y *= b; a.z *= b; a.w *= b;
    return a;
}

// Generalize += and *= to +, -=, -, *, /= and /
template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator+(const Pt& a, const Pt& b) {
    auto sum = a;
    sum += b;
    return sum;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-=(Pt& a, const Pt& b) {
    a += -1*b;
    return a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-(const Pt& a, const Pt& b) {
    auto diff = a;
    diff -= b;
    return diff;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator-(const Pt& a) {
    return -1*a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator*(const Pt& a, const float b) {
    auto prod = a;
    prod *= b;
    return prod;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator*(const float b, const Pt& a) {
    auto prod = a;
    prod *= b;
    return prod;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator/=(Pt& a, const float b) {
    a *= 1./b;
    return a;
}

template<typename Pt> __device__ __host__
typename std::enable_if<std::is_class<Pt>::value || std::is_enum<Pt>::value, Pt>::type
operator/(const Pt& a, const float b) {
    auto quot = a;
    quot /= b;
    return quot;
}

These overloads break compilation of thrust::reduce, here an example:

#include <thrust/reduce.h>
#include <thrust/execution_policy.h>

#include "vectorspace.cuh"

int main(int argc, char const *argv[]) {
    int n = 10;
    float3* d_arr;
    cudaMalloc(&d_arr, n*sizeof(float3));

    auto sum = thrust::reduce(thrust::device, d_arr, d_arr + n, float3 {0});

    return 0;
}

Using nvcc -std=c++11 -arch=sm_52 on Ubuntu 16.04 this results in 200+ lines of compiler errors:

$ nvcc -std=c++11 -arch=sm_52 sandbox/mean.cu
sandbox/mean.cu(26): error: no operator "*" matches these operands
            operand types are: int * const thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>
          detected during:
            instantiation of "std::enable_if<<expression>, Pt>::type operator-=(Pt &, const Pt &) [with Pt=thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>]"
(35): here
            instantiation of "std::enable_if<<expression>, Pt>::type operator-(const Pt &, const Pt &) [with Pt=thrust::zip_iterator<thrust::tuple<const float3 *, thrust::pointer<float3, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type>>]"

...

How can I overload the operators without breaking thrust?

Body:
(Edited following OP's edits.)

The problem is with the 'reach' of your operator overloads: You are not overloading only for the classes you're interested in, but for all classes fitting your enable_if condition - which is quite relaxed. That's already a serious bug even if things would compile.

More specifically, thrust uses arithmetic operations, e.g. on "zip iterators" (never mind what they are), and compilations of your operations for such iterators fails, understandably.

So you must either:

Specify exactly which classes the overload is relevant to (e.g., using a disjunction of std::is_same in the enable_if), or

use a trait class:

template<class T> struct needs_qivs_arithmetic_operators : public std::false_type {};

template<> struct needs_qivs_arithmetic_operators<float3> : public std::true_type {};
template<> struct needs_qivs_arithmetic_operators<float4> : public std::true_type {};
/* ... etc. You can also add specializations elsewhere in the translation unit. */


问:
Checking if a string of numbers is sorted C# in an if statement
I'm trying to figure out how to write an if statement in C# that basically does this</p>

```<code>string myString = "1234";
if( myString is sorted)
    {
        //Do some stuff
    }
else
    {
       // Do some other stuff
    }
</code>```

答:
I try to Simplify 'Rufus L' answer to help Ian Shirley. I tried to be instructive. I know that sort can be relative to culture matters but I want to explain it simple.</p>

```<code>string myString = "12343";
var sortedChar = myString.ToCharArray().ToList(); //we convert string to character

            sortedChar.Sort(); //this two lines is equivalent to OrderBy

            string sortedString =string.Join("",sortedChar);//this code concat the character or string together with specified string(here "")
            if (sortedString == myString)
            {
                Console.WriteLine("it's sorted.");

            }
            else
            {
                Console.WriteLine("it's not sorted.");

            }
</code>```

Body:
I'm trying to figure out how to write an if statement in C# that basically does this

string myString = "1234";
if( myString is sorted)
    {
        //Do some stuff
    }
else
    {
       // Do some other stuff
    }

Body:
I try to Simplify 'Rufus L' answer to help Ian Shirley. I tried to be instructive. I know that sort can be relative to culture matters but I want to explain it simple.

string myString = "12343";
var sortedChar = myString.ToCharArray().ToList(); //we convert string to character

            sortedChar.Sort(); //this two lines is equivalent to OrderBy

            string sortedString =string.Join("",sortedChar);//this code concat the character or string together with specified string(here "")
            if (sortedString == myString)
            {
                Console.WriteLine("it's sorted.");

            }
            else
            {
                Console.WriteLine("it's not sorted.");

            }


问:
Requiring Protocol and Class in Swift Properties
In Objective-C you can require a class and additional protocol implementations for properties:

```<code>@property (nonatomic) UIViewController<UISplitViewDelegate> *viewController;
</code>```

Is this possible in Swift? From the documentation it looks like you can only require either a class or a protocol.

答:
In Swift 4 you can do this by:</p>

```<code>let viewController: UIViewController & UISplitViewDelegate
</code>```

Body:
In Objective-C you can require a class and additional protocol implementations for properties:

@property (nonatomic) UIViewController<UISplitViewDelegate> *viewController;

Is this possible in Swift? From the documentation it looks like you can only require either a class or a protocol.

Body:
In Swift 4 you can do this by:

let viewController: UIViewController & UISplitViewDelegate


问:
NodeSet exception while using agilitypack
```<code>private void ShowStatistics_Click(object sender, RoutedEventArgs e)
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://www.gamerankings.com/browse.html");
        HtmlNodeCollection nodes= doc.DocumentNode.SelectNodes("//a/");
        string result = "";
        foreach (var item in nodes)
        {
            result += item.InnerText+Environment.NewLine;
        }
        Info.ItemsSource = result;

    }
</code>```

By pressing the button i want to get information from the webpage in a textbox called Info.
After pressing the button I get an exception saying that the result of expression should be NodeSet, what should I do? I'm using agility pack

答:
In addition to @Hung Cao, you can actually shorten this/work around:</p>

```<code>foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("Selector here")){
    //your code here
}
</code>```

Body:
private void ShowStatistics_Click(object sender, RoutedEventArgs e)
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://www.gamerankings.com/browse.html");
        HtmlNodeCollection nodes= doc.DocumentNode.SelectNodes("//a/");
        string result = "";
        foreach (var item in nodes)
        {
            result += item.InnerText+Environment.NewLine;
        }
        Info.ItemsSource = result;

    }

By pressing the button i want to get information from the webpage in a textbox called Info.
After pressing the button I get an exception saying that the result of expression should be NodeSet, what should I do? I'm using agility pack

Body:
In addition to @Hung Cao, you can actually shorten this/work around:

foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("Selector here")){
    //your code here
}


问:
Username in HTTP Header for SSO
I am looking to add single sign on (SSO) to one of my web applications. I don't want anything heavy at the moment, I just want to know the userId of the logged in user, without the need for them to enter a username.

The web app is an internal application, so I can guarantee they are coming from a Windows PC etc.

I have looked at jCIFS, but this doesn't seem to be supported any more, and recommends a commercial product.

I have also looked at WAFFLE, but I am building SSO for a playframework application, which does not use a Servlet stack, so I can't make use of the SecurityFilter. I have tried to make sense of the WindowsLoginModule, but couldn't really understand what I had to do to implement it.

Is it possible to just get the username from the HTTP header, or does it require some negotiation first before it will post the header?

答: The username isn't sent in the header. Even if it was this shouldn't be relied upon as a savvy user could fake the values.</p>

Title: Username in HTTP Header for SSO


问:
How to connect a Java Project to a MySQL Server
I've been browsing the internet for an up-to-date way to connect a Java project to a MySQL server/document. Any help would be greatly appreciated.

Everything I've found just seems to use links to out-of-date software.

答:
If you want to connect to a specific database type, such in your case, it is the best way to look first for a official library.

In the case of MySQL you can find this connector here:
https://dev.mysql.com/downloads/connector/j/


问:
Spring boot addInterceptors not being called in Websphere application server
I have a Spring Boot app using SpringWS. Inside of the WsConfigurerAdapter I am overriding addInterceptors in order to add logging/authentication/validation/etc.

```<code>@Configuration
@EnableCaching
@EnableWs
public class WebServiceConfig extends WsConfigurerAdapter {

    ...

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        EnvironmentSettings environment = getEnvironmentSettings();

        interceptors.add(getLogSetupInterceptor());
        interceptors.add(getAuthenticationInterceptor());
        interceptors.add(getServerLoggingInterceptor());
        interceptors.add(getAuthorizationInterceptor());
        ServerPayloadValidatingInterceptor validatingInterceptor = new ServerPayloadValidatingInterceptor();
        validatingInterceptor.setValidateRequest(environment.isValidateSoapRequest());
        validatingInterceptor.setValidateResponse(environment.isValidateSoapResponse());
        validatingInterceptor.setXsdSchema( xsdSchema());
        interceptors.add(validatingInterceptor);
    }
}
</code>```

What is strange is that when run locally, all of these interceptors are being added and run for every request just fine. However, when I deploy the application as a .war to WAS, this one method is not being run. I even added logging statements and I can tell that it's this method that's getting skipped over instead of the interceptors themselves. Does anybody know something about spring boot .war files that I don't?

Also, here is my Application class:

```<code>@SpringBootApplication
public class Application extends SpringBootServletInitializer  {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}
</code>```

答: I figured out what I did wrong. It turns out I was creating a servlet mapping in both my WebServiceConfig and my web.xml both at /*.</p>

Body:
I have a Spring Boot app using SpringWS. Inside of the WsConfigurerAdapter I am overriding addInterceptors in order to add logging/authentication/validation/etc.

@Configuration
@EnableCaching
@EnableWs
public class WebServiceConfig extends WsConfigurerAdapter {

    ...

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        EnvironmentSettings environment = getEnvironmentSettings();

        interceptors.add(getLogSetupInterceptor());
        interceptors.add(getAuthenticationInterceptor());
        interceptors.add(getServerLoggingInterceptor());
        interceptors.add(getAuthorizationInterceptor());
        ServerPayloadValidatingInterceptor validatingInterceptor = new ServerPayloadValidatingInterceptor();
        validatingInterceptor.setValidateRequest(environment.isValidateSoapRequest());
        validatingInterceptor.setValidateResponse(environment.isValidateSoapResponse());
        validatingInterceptor.setXsdSchema( xsdSchema());
        interceptors.add(validatingInterceptor);
    }
}

What is strange is that when run locally, all of these interceptors are being added and run for every request just fine. However, when I deploy the application as a .war to WAS, this one method is not being run. I even added logging statements and I can tell that it's this method that's getting skipped over instead of the interceptors themselves. Does anybody know something about spring boot .war files that I don't?

Also, here is my Application class:

@SpringBootApplication
public class Application extends SpringBootServletInitializer  {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}


问:
Http post to asmx with unnamed parameter
I have a webmethod like this:

```<code>    [WebMethod]
    public string HelloWorld(string a)
    {
        return a;
    }
</code>```

The instructions to post to my asmx webmethod say to post like this:

```<code>POST /Service1.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

a=string
</code>```

However I want to be able to accept this:

```<code>POST /Service1.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

string
</code>```

How can I do that?
Thanks

答:
Just to restate this problem. I have a similar issue where a 3rd party tool posts a json object {a:1, b:2, c:3}

my .net code looks like

```<code>public bool AcceptPush(ABCObject ObjectName)
</code>```

The 3rd party tool does not post {ObjectName:{a:1, b:2, c:3}} if it did there would not be any problem.

You could code the .net as this:

```<code>public bool AcceptPush(int a, int b, int c)
</code>```

But in reality this is much uglier and the acutal object is much more complicated than this simple example

OwnerDisplayName: bwbbwb

Body:
I have a webmethod like this:

    [WebMethod]
    public string HelloWorld(string a)
    {
        return a;
    }

The instructions to post to my asmx webmethod say to post like this:

POST /Service1.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

a=string

However I want to be able to accept this:

POST /Service1.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

string

How can I do that?
Thanks

Body:
Just to restate this problem. I have a similar issue where a 3rd party tool posts a json object {a:1, b:2, c:3}

my .net code looks like

public bool AcceptPush(ABCObject ObjectName)

The 3rd party tool does not post {ObjectName:{a:1, b:2, c:3}} if it did there would not be any problem.

You could code the .net as this:

public bool AcceptPush(int a, int b, int c)

But in reality this is much uglier and the acutal object is much more complicated than this simple example


问:
Difference in Converting Byte() to String
let us say I converted a photo to array of bytes by the following lines :

```<code>Dim Bytes() As Byte
Bytes = IO.File.ReadAllBytes("C:\DT.jpg")
</code>```

Now, the Bytes() could be converted to text and displayed in textbox via the code

```<code>TextBox1.Text = System.Convert.ToBase64String(Bytes)
</code>```

the above line will print something like :
9j/4AAQSkZJRgABAQEAYABgAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODAp ...etc.

but
when using the a function like

TextBox1.Text = System.Text.Encoding.ASCII.GetString(Bytes)
the result is just : ???? (four question marks)

I worked around and made a loop

```<code>For i As Integer = 0 To Bytes.Length - 1
    TextBox1.Text = TextBox1.Text & Chr(bytes(I))
Next
</code>```

and the textbox1 displayed something like : #3RðbrÑ $4á%ñ&'()*56789 ..etc
which is exactly the ASCII representation of each byte in the bytes().

my question is :
why it failed to return the ASCII, UTF8,UTF7, ANSI, etc representation of the Bytes using functions under namespace System.Text.Encoding. ? is there anyway to get the representation not by using the loop ?

答:
Try something like this instead:

```<code>Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function
</code>```

and:

```<code>Public Function Base64ToImage(base64String As String) As Image
    ' Convert Base64 String to byte[]
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
    Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)

    ' Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length)
    Dim image__1 As Image = Image.FromStream(ms, True)
    Return image__1
End Function
</code>```

Code stolen from here and converted to vb.net

http://www.dailycoding.com/posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

Body:
let us say I converted a photo to array of bytes by the following lines :

Dim Bytes() As Byte
Bytes = IO.File.ReadAllBytes("C:\DT.jpg")

Now, the Bytes() could be converted to text and displayed in textbox via the code

TextBox1.Text = System.Convert.ToBase64String(Bytes)

the above line will print something like :
9j/4AAQSkZJRgABAQEAYABgAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODAp ...etc.

but
when using the a function like

TextBox1.Text = System.Text.Encoding.ASCII.GetString(Bytes)
the result is just : ???? (four question marks)

I worked around and made a loop

For i As Integer = 0 To Bytes.Length - 1
    TextBox1.Text = TextBox1.Text & Chr(bytes(I))
Next

and the textbox1 displayed something like : #3RðbrÑ $4á%ñ&'()*56789 ..etc
which is exactly the ASCII representation of each byte in the bytes().

my question is :
why it failed to return the ASCII, UTF8,UTF7, ANSI, etc representation of the Bytes using functions under namespace System.Text.Encoding. ? is there anyway to get the representation not by using the loop ?

Body:
Try something like this instead:

Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function

and:

Public Function Base64ToImage(base64String As String) As Image
    ' Convert Base64 String to byte[]
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
    Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)

    ' Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length)
    Dim image__1 As Image = Image.FromStream(ms, True)
    Return image__1
End Function

Code stolen from here and converted to vb.net

http://www.dailycoding.com/posts/convert_image_to_base64_string_and_base64_string_to_image.aspx


问:
Regex match cookie value and remove hyphens
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

```<code>facility=34222%7CConner-Department-Store;
</code>```

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??

答:
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).

Simply include the cookies.js file in your application, and write:

docCookies.getItem("Connor Department Store");

Body:
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

facility=34222%7CConner-Department-Store;

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??


问:
UIView Animation Misbehaves when iPad orientation is changed
I am using this code for UIView transition effect

```<code>[UIView beginAnimations: nil context: nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[UIView commitAnimations];
</code>```

Now the problem is that when i rotated the ipad in Landscape Left it behaves weird and if i give condition whether if Landscape left than UIViewAnimationTransitionCurlDown, still the animation is not the same as it is during Landscape-right way

答:
I've got the exact same issue.
For people having hard time understanding the problem :

When you're doing "curl up" in landscape mode,with the button on the right, the page starts to flip from top right to bottom left (meaning, your turned the page with your right hand, and moved toward the left side of the book. also meaning that the book's binding is on the left).

When you're doing the very same, but with button on the left, the animation don't rotate, even when correctly rotating content, saying "shouldAutorotateToInterfaceOrientation : True" in the vc. As a result the animation goes from bottom left to top right, giving the impression that the book's binding now is on the right.

Some code to illustrate that :

```<code>- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        view1 = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
        [view1 setBackgroundColor:[UIColor greenColor]];
        [view1 setFont:[UIFont systemFontOfSize:80]];
        [view1 setText:@"VIEW 1"];

        view2 = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
        [view2 setBackgroundColor:[UIColor redColor]];
        [view2 setFont:[UIFont systemFontOfSize:80]];
        [view2 setText:@"VIEW 2"];
    }
    return self;
}

-(void)didSwipeNext
{
    [self performSelector:@selector(swipePrevious) withObject:nil afterDelay:1];
}

-(void)didSwipePrevious
{
    [self performSelector:@selector(swipeNext) withObject:nil afterDelay:1];
}

-(void)swipeNext
{
    [UIView beginAnimations:@"curl" context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationBeginsFromCurrentState:NO];
    [UIView setAnimationDidStopSelector:@selector(didSwipeNext)];

    [view1 removeFromSuperview];
    [self.view addSubview:view2];

    [UIView commitAnimations];
}

-(void)swipePrevious
{

    [UIView beginAnimations:@"curl" context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationBeginsFromCurrentState:NO];
    [UIView setAnimationDidStopSelector:@selector(didSwipePrevious)];

    [view2 removeFromSuperview];
    [self.view addSubview:view1];

    [UIView commitAnimations];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:view1];
    [self performSelector:@selector(swipeNext) withObject:nil afterDelay:1];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
</code>```

Body:
I am using this code for UIView transition effect

[UIView beginAnimations: nil context: nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[UIView commitAnimations];

Now the problem is that when i rotated the ipad in Landscape Left it behaves weird and if i give condition whether if Landscape left than UIViewAnimationTransitionCurlDown, still the animation is not the same as it is during Landscape-right way

Body:
I've got the exact same issue.
For people having hard time understanding the problem :

When you're doing "curl up" in landscape mode,with the button on the right, the page starts to flip from top right to bottom left (meaning, your turned the page with your right hand, and moved toward the left side of the book. also meaning that the book's binding is on the left).

When you're doing the very same, but with button on the left, the animation don't rotate, even when correctly rotating content, saying "shouldAutorotateToInterfaceOrientation : True" in the vc. As a result the animation goes from bottom left to top right, giving the impression that the book's binding now is on the right.

Some code to illustrate that :

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        view1 = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
        [view1 setBackgroundColor:[UIColor greenColor]];
        [view1 setFont:[UIFont systemFontOfSize:80]];
        [view1 setText:@"VIEW 1"];

        view2 = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
        [view2 setBackgroundColor:[UIColor redColor]];
        [view2 setFont:[UIFont systemFontOfSize:80]];
        [view2 setText:@"VIEW 2"];
    }
    return self;
}

-(void)didSwipeNext
{
    [self performSelector:@selector(swipePrevious) withObject:nil afterDelay:1];
}

-(void)didSwipePrevious
{
    [self performSelector:@selector(swipeNext) withObject:nil afterDelay:1];
}

-(void)swipeNext
{
    [UIView beginAnimations:@"curl" context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationBeginsFromCurrentState:NO];
    [UIView setAnimationDidStopSelector:@selector(didSwipeNext)];

    [view1 removeFromSuperview];
    [self.view addSubview:view2];

    [UIView commitAnimations];
}

-(void)swipePrevious
{

    [UIView beginAnimations:@"curl" context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationBeginsFromCurrentState:NO];
    [UIView setAnimationDidStopSelector:@selector(didSwipePrevious)];

    [view2 removeFromSuperview];
    [self.view addSubview:view1];

    [UIView commitAnimations];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:view1];
    [self performSelector:@selector(swipeNext) withObject:nil afterDelay:1];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


问:
android getPageTitle is not worked

I am working with the FragmentPagerAdapter and have a problem with the
  getPageTitle() method. Everythings is working but it. plz take a look at my code blowing and help me out.

```<code>public class MyFragmentPageAdapter extends FragmentPagerAdapter {

        final int PAGE_COUNT = 3;
        public final static String PAGE_CURRENT = "current_age";
        public final static String PAGE_ID = "id";
        int id = 0;

        public MyFragmentPageAdapter(FragmentManager fm, int id) {
            super(fm);
            this.id = id;
        }

        @Override
        public Fragment getItem(int position) {
            MyFragment myFragment = new MyFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(PAGE_CURRENT, position + 1);
            bundle.putInt(PAGE_ID, id);
            myFragment.setArguments(bundle);
            return myFragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            CharSequence title = null;
            if (position == 0) {
                title = "a";
            } else if (position == 1) {
                title = "b";
            } else if (position == 2) {
                title = "c";
            }
            return title;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return PAGE_COUNT;
        }

    }
</code>```

And in my main Activity i declared:

```<code>ViewPager pager = (ViewPager) findViewById(R.id.pager);
        pager.setOnPageChangeListener(this);
        FragmentManager fm = getSupportFragmentManager();
        MyFragmentPageAdapter fragmentAdapter = new MyFragmentPageAdapter(fm,
                id);
        pager.setAdapter(fragmentAdapter);
</code>```

答:
I had the same problem and assume it's an Android bug. Set the page title in TabLayout.createTabAtPosition(), with this code:
return newTab().setText("the page title");

Title: android getPageTitle is not worked

Body:
I am working with the FragmentPagerAdapter and have a problem with the
  getPageTitle() method. Everythings is working but it. plz take a look at my code blowing and help me out.

public class MyFragmentPageAdapter extends FragmentPagerAdapter {

        final int PAGE_COUNT = 3;
        public final static String PAGE_CURRENT = "current_age";
        public final static String PAGE_ID = "id";
        int id = 0;

        public MyFragmentPageAdapter(FragmentManager fm, int id) {
            super(fm);
            this.id = id;
        }

        @Override
        public Fragment getItem(int position) {
            MyFragment myFragment = new MyFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(PAGE_CURRENT, position + 1);
            bundle.putInt(PAGE_ID, id);
            myFragment.setArguments(bundle);
            return myFragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            CharSequence title = null;
            if (position == 0) {
                title = "a";
            } else if (position == 1) {
                title = "b";
            } else if (position == 2) {
                title = "c";
            }
            return title;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return PAGE_COUNT;
        }

    }

And in my main Activity i declared:

ViewPager pager = (ViewPager) findViewById(R.id.pager);
        pager.setOnPageChangeListener(this);
        FragmentManager fm = getSupportFragmentManager();
        MyFragmentPageAdapter fragmentAdapter = new MyFragmentPageAdapter(fm,
                id);
        pager.setAdapter(fragmentAdapter);


问:
PHP - Saving checkbox with submit button
I am attempting to build a checklist in which you will be able to select / deselect multiple checkboxes and save them to the page using a submit button.

Below is the code I am working with:

```<code><form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="submit" value="Save" name="save" id="save" />
    <ul>
        <li><input type="checkbox" />Tickets</li>
            <ul>
                <li><input type="checkbox" name="person1" id="person1" value="1" />Person 1's ticket</li>
                <li><input type="checkbox" name="person2" id="person2" value="2" checked />Person 2's ticket</li>
                <li><input type="checkbox" name="person3" id="person3" value="2" />Person 3's ticket</li>
                <li><input type="checkbox" name="person4" id="person4" value="2" checked />Person 4's ticket</li>
            </ul>
</form>
</code>```

PHP: [only shown for 1]

```<code>            <?php
            if (isset($_POST["submit"])) {
                echo "<input type='checkbox' name='person1' id='person1' value='1' checked />";
            } else {
                echo 'There was an error.';
            }
        ?>
</code>```

I cannot seem to get the checkboxes to hold the data after the page is refreshed.

Upon clicking save I would like the page to reload and the checkboxes to hold their data.

I am trying to keep this quite simple, so the least amount of code, the better. Everything I am able to find requires the use of jQuery or databases.

I am fairly new with PHP and any assistance is greatly appreciated.

A live version of my site can be seen at www.magycka.us to better understand what this is being used for.

答: This was answered by creating a mysql database and using PHP to store the values as a 1 or 0 in the db. </p>

Body:
I am attempting to build a checklist in which you will be able to select / deselect multiple checkboxes and save them to the page using a submit button.

Below is the code I am working with:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="submit" value="Save" name="save" id="save" />

<input type="checkbox" />Tickets

<input type="checkbox" name="person1" id="person1" value="1" />Person 1's ticket

<input type="checkbox" name="person2" id="person2" value="2" checked />Person 2's ticket

<input type="checkbox" name="person3" id="person3" value="2" />Person 3's ticket

<input type="checkbox" name="person4" id="person4" value="2" checked />Person 4's ticket

</form>

PHP: [only shown for 1]

            <?php
            if (isset($_POST["submit"])) {
                echo "<input type='checkbox' name='person1' id='person1' value='1' checked />";
            } else {
                echo 'There was an error.';
            }
        ?>

I cannot seem to get the checkboxes to hold the data after the page is refreshed.

Upon clicking save I would like the page to reload and the checkboxes to hold their data.

I am trying to keep this quite simple, so the least amount of code, the better. Everything I am able to find requires the use of jQuery or databases.

I am fairly new with PHP and any assistance is greatly appreciated.

A live version of my site can be seen at www.magycka.us to better understand what this is being used for.


问:
Need to Aggregate on the Last Month for a Grouped Report
I have a dataset that looks like the following:

```<code>| Location | Category |Item Name |   Month  | QTY |
| -------- | -------- | -------- | -------- | --- |
|    NY    | Hardware |   Screw  | Jan 2017 | 100 |
|    NY    | Hardware |   Screw  | Feb 2017 | 50  |
|    NY    | Hardware |   Screw  | Mar 2017 | 75  |
|    NY    | Hardware |    Bolt  | Jan 2017 | 30  |
|    NY    | Hardware |    Bolt  | Feb 2017 | 90  |
|    NY    | Hardware |    Bolt  | Mar 2017 | 50  |
|    CA    | Hardware |   Screw  | Jan 2017 | 100 |
|    CA    | Hardware |   Screw  | Feb 2017 | 50  |
|    CA    | Hardware |   Screw  | Mar 2017 | 75  |
|    CA    | Hardware |    Bolt  | Jan 2017 | 30  |
|    CA    | Hardware |    Bolt  | Feb 2017 | 90  |
|    CA    | Hardware |    Bolt  | Mar 2017 | 50  |
</code>```

My report needs to look like the following:

```<code>|      Hardware      | Screw |  Bolt |
|Current Month Total |  150  |  100  |
|Yearly Total        |  450  |  340  |
</code>```

I need a way to limit the current month total to ONLY the current month but aggregate the values for the yearly total. I've tried using LAST in the aggregate but you can't. I've tried the following for the current month total aggregate. My Date value is the 1st day of the month and my parameter is the last day of the month, so I needed a way to match the 2 that is why there is the date addition. The jist is to try and match the current month, which is a parameter to the date column:

=iif( DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!Sale_DATE.Value)) = Parameters!ReportingDate.Value, iif(isnothing(sum(Fields!Total.Value)),"",sum(Fields!Total.Value)),sum(0))

but it only works if the query that returns the dataset returns ONLY the current month. If the query returns all of the months in the year it shows 0's. I need a way to filter the cells so they aggregate the values correctly

If I limit my report to only the current month I can't get the yearly aggregate and if I select all of the months I can't get the current month total.

答:
You can do this using the built-in grouping functions without any fancy expressions.

Add a row group by month. Filter the row group to the current month. Add a column group by Item Name. Add a row outside and below the row group to get your yearly totals. The expressions will all simply be a sum of the Qty. The report will take care of summing the values within each group scope.

Body:
I have a dataset that looks like the following:

| Location | Category |Item Name |   Month  | QTY |
| -------- | -------- | -------- | -------- | --- |
|    NY    | Hardware |   Screw  | Jan 2017 | 100 |
|    NY    | Hardware |   Screw  | Feb 2017 | 50  |
|    NY    | Hardware |   Screw  | Mar 2017 | 75  |
|    NY    | Hardware |    Bolt  | Jan 2017 | 30  |
|    NY    | Hardware |    Bolt  | Feb 2017 | 90  |
|    NY    | Hardware |    Bolt  | Mar 2017 | 50  |
|    CA    | Hardware |   Screw  | Jan 2017 | 100 |
|    CA    | Hardware |   Screw  | Feb 2017 | 50  |
|    CA    | Hardware |   Screw  | Mar 2017 | 75  |
|    CA    | Hardware |    Bolt  | Jan 2017 | 30  |
|    CA    | Hardware |    Bolt  | Feb 2017 | 90  |
|    CA    | Hardware |    Bolt  | Mar 2017 | 50  |

My report needs to look like the following:

|      Hardware      | Screw |  Bolt |
|Current Month Total |  150  |  100  |
|Yearly Total        |  450  |  340  |

I need a way to limit the current month total to ONLY the current month but aggregate the values for the yearly total. I've tried using LAST in the aggregate but you can't. I've tried the following for the current month total aggregate. My Date value is the 1st day of the month and my parameter is the last day of the month, so I needed a way to match the 2 that is why there is the date addition. The jist is to try and match the current month, which is a parameter to the date column:

=iif( DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!Sale_DATE.Value)) = Parameters!ReportingDate.Value, iif(isnothing(sum(Fields!Total.Value)),"",sum(Fields!Total.Value)),sum(0))

but it only works if the query that returns the dataset returns ONLY the current month. If the query returns all of the months in the year it shows 0's. I need a way to filter the cells so they aggregate the values correctly

If I limit my report to only the current month I can't get the yearly aggregate and if I select all of the months I can't get the current month total.


问:
Add existent style to a Paragraph in OpenXML
I need to add a style to a paragraph using OpenXML. I have the following code and it's running but, the style is not the one I am trying to add.

```<code>var file = WordprocessingDocument.Open(fileName, true);

var text = new Text("Hello world");
var run = new Run(text);
var paragraph = new Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties(
new ParagraphStyleId() { Val = "Body Text" });

file.MainDocumentPart.Document.Body.AppendChild(paragraph);
file.MainDocumentPart.Document.Save();
</code>```

Is there something that I am doing wrong???
How to add some of the existent styles to a paragraph using OpenXML.

答:
As illustrated here</p>

```<code>private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart,
    string styleid, string stylename)
{
    // Get access to the root element of the styles part.
    Styles styles = styleDefinitionsPart.Styles;

    // Create a new paragraph style and specify some of the properties.
    Style style = new Style() { Type = StyleValues.Paragraph,
        StyleId = styleid,
        CustomStyle = true };
    StyleName styleName1 = new StyleName() { Val = stylename };
    BasedOn basedOn1 = new BasedOn() { Val = "Normal" };
    NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" };
    style.Append(styleName1);
    style.Append(basedOn1);
    style.Append(nextParagraphStyle1);

    // Create the StyleRunProperties object and specify some of the run properties.
    StyleRunProperties styleRunProperties1 = new StyleRunProperties();
    Bold bold1 = new Bold();
    Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
    RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" };
    Italic italic1 = new Italic();
    // Specify a 12 point size.
    FontSize fontSize1 = new FontSize() { Val = "24" };
    styleRunProperties1.Append(bold1);
    styleRunProperties1.Append(color1);
    styleRunProperties1.Append(font1);
    styleRunProperties1.Append(fontSize1);
    styleRunProperties1.Append(italic1);

    // Add the run properties to the style.
    style.Append(styleRunProperties1);

    // Add the style to the styles part.
    styles.Append(style);
}
</code>```

Body:
I need to add a style to a paragraph using OpenXML. I have the following code and it's running but, the style is not the one I am trying to add.

var file = WordprocessingDocument.Open(fileName, true);

var text = new Text("Hello world");
var run = new Run(text);
var paragraph = new Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties(
new ParagraphStyleId() { Val = "Body Text" });

file.MainDocumentPart.Document.Body.AppendChild(paragraph);
file.MainDocumentPart.Document.Save();

Is there something that I am doing wrong???
How to add some of the existent styles to a paragraph using OpenXML.

Body:
As illustrated here

private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart,
    string styleid, string stylename)
{
    // Get access to the root element of the styles part.
    Styles styles = styleDefinitionsPart.Styles;

    // Create a new paragraph style and specify some of the properties.
    Style style = new Style() { Type = StyleValues.Paragraph,
        StyleId = styleid,
        CustomStyle = true };
    StyleName styleName1 = new StyleName() { Val = stylename };
    BasedOn basedOn1 = new BasedOn() { Val = "Normal" };
    NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" };
    style.Append(styleName1);
    style.Append(basedOn1);
    style.Append(nextParagraphStyle1);

    // Create the StyleRunProperties object and specify some of the run properties.
    StyleRunProperties styleRunProperties1 = new StyleRunProperties();
    Bold bold1 = new Bold();
    Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
    RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" };
    Italic italic1 = new Italic();
    // Specify a 12 point size.
    FontSize fontSize1 = new FontSize() { Val = "24" };
    styleRunProperties1.Append(bold1);
    styleRunProperties1.Append(color1);
    styleRunProperties1.Append(font1);
    styleRunProperties1.Append(fontSize1);
    styleRunProperties1.Append(italic1);

    // Add the run properties to the style.
    style.Append(styleRunProperties1);

    // Add the style to the styles part.
    styles.Append(style);
}


问:
Pandas Filter by string
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F
</code>```

Returns:

```<code>Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

When I change apply to filter I get an error.

Help Please!

答:
You can use filter after groupby to check if all rows in the groups have T in column C.</p>

```<code>df.groupby('A').filter(lambda x: len(x[x.C=='T'])==len(x))
Out[41]:
  Index   A   B  C
3     3  A2  B5  T
4     4  A2  F5  T
5     5  A3  F4  T
</code>```

Title: Pandas Filter by string

Body:
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F

Returns:

Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

When I change apply to filter I get an error.

Help Please!

Body:
You can use filter after groupby to check if all rows in the groups have T in column C.

df.groupby('A').filter(lambda x: len(x[x.C=='T'])==len(x))
Out[41]:
  Index   A   B  C
3     3  A2  B5  T
4     4  A2  F5  T
5     5  A3  F4  T


问:
Am I writing this code wrong?
This looks wrong to me, am i right? This is the code that I am using:

```<code>_editButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(editButtonPressed:)];

// If we have no threads we don't have the edit button
self.navigationItem.leftBarButtonItem = _editButton ; nil;
</code>```

Mainly I am concerned with self.navigationItem.leftBarButtonItem = _editButton ; nil; the _editButton ; nil; looks wrong to me.

Should the code look like this? self.navigationItem.leftBarButtonItem = _editButton;

答: It's not wrong per se, but it is unnecessary.  The ; after _editButton ends the statement making nil; a statement of its own, and as you might imagine that does nothing whatsoever.  The two are functionally identical, so you may as well take out the extra code.

Title: Am I writing this code wrong?

Body:
This looks wrong to me, am i right? This is the code that I am using:

_editButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(editButtonPressed:)];

// If we have no threads we don't have the edit button
self.navigationItem.leftBarButtonItem = _editButton ; nil;

Mainly I am concerned with self.navigationItem.leftBarButtonItem = _editButton ; nil; the _editButton ; nil; looks wrong to me.

Should the code look like this? self.navigationItem.leftBarButtonItem = _editButton;


问:
Class conforming to protocol as function parameter in Swift
In Objective-C, it's possible to specify a class conforming to a protocol as a method parameter. For example, I could have a method that only allows a UIViewController that conforms to UITableViewDataSource:

```<code>- (void)foo:(UIViewController<UITableViewDataSource> *)vc;
</code>```

I can't find a way to do this in Swift (perhaps it's not possible yet). You can specify multiple protocols using func foo(obj: protocol<P1, P2>), but how do you require that the object is of a particular class as well?

答:
In Swift 4 you can achieve this with the new & sign:</p>

```<code>let vc: UIViewController & UITableViewDataSource
</code>```

Body:
In Objective-C, it's possible to specify a class conforming to a protocol as a method parameter. For example, I could have a method that only allows a UIViewController that conforms to UITableViewDataSource:

- (void)foo:(UIViewController<UITableViewDataSource> *)vc;

I can't find a way to do this in Swift (perhaps it's not possible yet). You can specify multiple protocols using func foo(obj: protocol<P1, P2>), but how do you require that the object is of a particular class as well?

Body:
In Swift 4 you can achieve this with the new & sign:

let vc: UIViewController & UITableViewDataSource


问:
Updating database without grabbing all the rows
Currently I do a property to property comparison with reflection to determine which values I should update in the database. The problem is that before I can do the comparison of the existing and new value, I need to grab all the rows from the database. These rows are already filtered but can contain thousands of records. As a result, my program is extremely slow and is bottlenecked by all the SELECT LINQ to SQL queries. These select queries take minutes at a time for each to complete.

Example LINQ:

```<code>    List<Customer> customersFromDatabase= _customerRepository
        .List()
        .Where(c=> c.country.Equals(country))
        .ToList();
</code>```

This is the LINQ I use to determine whether they are a new customer or if they exist in which case they would be updated.

```<code>var customerInDb = customersFromDatabase
        .Where(c=> c.id.ToLower() == customer.id.ToLower())
        .FirstOrDefault();
</code>```

Is there a way to filter and grab only specific rows without having to pull the entire dataset down first?

The source data is a CSV file and the target is a database table\

Thanks.

答:
If you already have the Id, could you not just grab the row in the initial step of your process:

Something like:

```<code>List<Customer> customersFromDatabase= _customerRepository
.List()
.Where(c=> c.id == customer.id)
.ToList();
</code>```

This would give you the list of clients found with the Id you provided, speeding the entire process up substantially?

Also, I'm assuming your Id column is indexed?

Body:
Currently I do a property to property comparison with reflection to determine which values I should update in the database. The problem is that before I can do the comparison of the existing and new value, I need to grab all the rows from the database. These rows are already filtered but can contain thousands of records. As a result, my program is extremely slow and is bottlenecked by all the SELECT LINQ to SQL queries. These select queries take minutes at a time for each to complete.

Example LINQ:

    List<Customer> customersFromDatabase= _customerRepository
        .List()
        .Where(c=> c.country.Equals(country))
        .ToList();

This is the LINQ I use to determine whether they are a new customer or if they exist in which case they would be updated.

var customerInDb = customersFromDatabase
        .Where(c=> c.id.ToLower() == customer.id.ToLower())
        .FirstOrDefault();

Is there a way to filter and grab only specific rows without having to pull the entire dataset down first?

The source data is a CSV file and the target is a database table\

Thanks.

Body:
If you already have the Id, could you not just grab the row in the initial step of your process:

Something like:

List<Customer> customersFromDatabase= _customerRepository
.List()
.Where(c=> c.id == customer.id)
.ToList();

This would give you the list of clients found with the Id you provided, speeding the entire process up substantially?

Also, I'm assuming your Id column is indexed?


问:
Correctly bundled image could not be loaded
I have a very simple React component, that is supposed to display an image.
I am also using Webpack for bundling.

It's probably worth noting that I am using ReactJS.NET.

Although the webpack bundle builds properly, and the .jpg generated by webpack is viewable (using Windows Photo Viewer, for example), the image does not display in my View.

When I take a peek into inspector, the html structure is built properly, but I am getting:

"Could not load the image" - when I hover over the image path.

I made sure that the image path is correct.

Below is my react component:

```<code>var React = require('react');
var BackgroundImg = require('./Images/img_fjords.jpg');

class Login extends React.Component {
    render() {
        return (
            <img src={BackgroundImg} />
        );
    }

    componentDidMount() {
        console.log("Mounted");
    }
}

module.exports = Login;
</code>```

Webpack config:

```<code>var path = require('path');
var WebpackNotifierPlugin = require('webpack-notifier');

module.exports = {
    context: path.join(__dirname, 'App'),
    entry: {
        server: './server',
        client: './client'
    },

    output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: path.join(__dirname, 'Built/'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new WebpackNotifierPlugin()
    ],
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&mimetype=application/font-woff"
            },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ]
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['.js', '.jsx']
    },

    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};
</code>```

答:
The problem was solved thanks to help from @Luggage.

The webpack.config was wrong, it should have been:

```<code>output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: 'Built/',
        filename: '[name].bundle.js'
    },
</code>```

Body:
I have a very simple React component, that is supposed to display an image.
I am also using Webpack for bundling.

It's probably worth noting that I am using ReactJS.NET.

Although the webpack bundle builds properly, and the .jpg generated by webpack is viewable (using Windows Photo Viewer, for example), the image does not display in my View.

When I take a peek into inspector, the html structure is built properly, but I am getting:

"Could not load the image" - when I hover over the image path.

I made sure that the image path is correct.

Below is my react component:

var React = require('react');
var BackgroundImg = require('./Images/img_fjords.jpg');

class Login extends React.Component {
    render() {
        return (

        );
    }

    componentDidMount() {
        console.log("Mounted");
    }
}

module.exports = Login;

Webpack config:

var path = require('path');
var WebpackNotifierPlugin = require('webpack-notifier');

module.exports = {
    context: path.join(__dirname, 'App'),
    entry: {
        server: './server',
        client: './client'
    },

    output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: path.join(__dirname, 'Built/'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new WebpackNotifierPlugin()
    ],
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&mimetype=application/font-woff"
            },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ]
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['.js', '.jsx']
    },

    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};

Body:
The problem was solved thanks to help from @Luggage.

The webpack.config was wrong, it should have been:

output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: 'Built/',
        filename: '[name].bundle.js'
    },