问:
Update SQL query is not working in Java Swing
Here i made table called sub_master with column sub_id and name,  insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name =''  WHERE sub_id = ;</p>

```<code>private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
  executeSQlQuery(query, "Inserted");
}

private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
  executeSQlQuery(query, "Updated");
}

private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
    String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
    executeSQlQuery(query, "Deleted");
}
</code>```

答:
You are missing a space in the sql WHERE clause, so add it as shown below:

```<code>String query = "UPDATE school_submaster SET 'name' ='"+
                 SnameInput.getText()+"'  WHERE sub_id = "+SidInput.getText();
</code>```

Body:
Here i made table called sub_master with column sub_id and name,  insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name =''  WHERE sub_id = ;

private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
  executeSQlQuery(query, "Inserted");
}

private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
  executeSQlQuery(query, "Updated");
}

private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
    String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
    executeSQlQuery(query, "Deleted");
}

Body:
You are missing a space in the sql WHERE clause, so add it as shown below:

String query = "UPDATE school_submaster SET 'name' ='"+
                 SnameInput.getText()+"'  WHERE sub_id = "+SidInput.getText();


来源: stackexchange

问:
How to return distinct rows in rails?
I have a model Program containing fields program_title, department_id and date. I have inserted two rows having same program title and date but different department_id.

```<code>Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","1");
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","2");
</code>```

Now I want to return rows which will be distinct by program_title whatever be the department_id. I have tried,

```<code>@event_contents=Program.select(:id,:date,:program_title).distinct(:program_title)
</code>```

But still it returns both the rows. Any help is appreciated.

答:
Try this

```<code>Program.all.distinct(:program_title).pluck( :id,:program_title,:date)
</code>```

It will return data as array of elements though

Hope it helps

ContentLicense: CC BY-SA 3.0

Title: How to return distinct rows in rails?

Body:
I have a model Program containing fields program_title, department_id and date. I have inserted two rows having same program title and date but different department_id.

Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","1");
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","2");

Now I want to return rows which will be distinct by program_title whatever be the department_id. I have tried,

@event_contents=Program.select(:id,:date,:program_title).distinct(:program_title)

But still it returns both the rows. Any help is appreciated.

Body:
Try this

Program.all.distinct(:program_title).pluck( :id,:program_title,:date)

It will return data as array of elements though

Hope it helps


问:
JAVA: error: unexpected type
```<code>public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}
/*public boolean isDefeated(){

}*/
</code>```

}

```<code>import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){
    enemy.getHitPoints() -= playerATK;

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);
    int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;

    if (enemy.getName() == "Goblin" && getName()=="Rogue"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

          while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
          {
            playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
            playerATK = getStrength() + playerDamage;
            enemy.getHitPoints() -= playerATK;
            System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
            System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());

            if (enemy.getHitPoints() <= 0)
              break;

            enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
            enemyATK = enemy.getStrength() + enemyDamage;
            getHitPoints() -= enemyATK;
            System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
            System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
          } // end of while loop

          if (getHitPoints() > 0){
            System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
            coins = randomNums.nextInt((50 - 30) + 1) + 30;
            System.out.println(getName() + " gains " + coins + " gold coins!\n");
            //player[4] += coins;
          }
          else
          {
            System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
            System.exit(0);
          }

          if(i <= goblin.getNumGoblins() - 1){
            System.out.println("Press enter to continue...");
            keyboard.nextLine();
          }
        }
    }
</code>```

Error is as follows

./Player.java:59: error: unexpected type
                      enemy.getHitPoints() -= playerATK;
                                        ^
        required: variable
        found:    value
      ./Player.java:68: error: unexpected type
                      getHitPoints() -= enemyATK;

I know this is wrong, but what is the reason behind this? Also I have

```<code>public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}
</code>```

these two class in my character class, I don't how to code to make this work.

答:
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.

Instead of

```<code>getHitPoints() -= playerATK;
</code>```

write

```<code>setHitPoints (getHitPoints() - playerATK);
</code>```

or

```<code>decreaseHitPointsBy (playerATK); // this approach would require a corresponding
                                 // increaseHitPointsBy (value) method
</code>```

Title: JAVA: error: unexpected type

Body:
public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}
/*public boolean isDefeated(){

}*/

}

import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){
    enemy.getHitPoints() -= playerATK;

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);
    int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;

    if (enemy.getName() == "Goblin" && getName()=="Rogue"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

          while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
          {
            playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
            playerATK = getStrength() + playerDamage;
            enemy.getHitPoints() -= playerATK;
            System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
            System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());

            if (enemy.getHitPoints() <= 0)
              break;

            enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
            enemyATK = enemy.getStrength() + enemyDamage;
            getHitPoints() -= enemyATK;
            System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
            System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
          } // end of while loop

          if (getHitPoints() > 0){
            System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
            coins = randomNums.nextInt((50 - 30) + 1) + 30;
            System.out.println(getName() + " gains " + coins + " gold coins!\n");
            //player[4] += coins;
          }
          else
          {
            System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
            System.exit(0);
          }

          if(i <= goblin.getNumGoblins() - 1){
            System.out.println("Press enter to continue...");
            keyboard.nextLine();
          }
        }
    }

Error is as follows

./Player.java:59: error: unexpected type
                      enemy.getHitPoints() -= playerATK;
                                        ^
        required: variable
        found:    value
      ./Player.java:68: error: unexpected type
                      getHitPoints() -= enemyATK;

I know this is wrong, but what is the reason behind this? Also I have

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}

these two class in my character class, I don't how to code to make this work.

Body:
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.

Instead of

getHitPoints() -= playerATK;

write

setHitPoints (getHitPoints() - playerATK);

or

decreaseHitPointsBy (playerATK); // this approach would require a corresponding
                                 // increaseHitPointsBy (value) method


问:
IOException file already exists C#
```<code>private void btn_Backup_Click(object sender, EventArgs e)
    {
        List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
        string TargetDir = this.tbox_Target.Text;

        foreach (DirectoryInfo directory in SourceDir)
        {
            foreach (var file in directory.GetFiles())
                if (this.checkbox_zipfiles.Checked == true)
                {
                    System.IO.Compression.ZipFile.CreateFromDirectory(directory.FullName, TargetDir + @"\test.zip");
                }
                else
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(directory.FullName, TargetDir, true);
                }
        }
    }
</code>```

I'm creating a backup application and when I try to zip the files I need to backup it says: "The file 'C:\Users\Lada1208\Desktop\test\test.zip' already exists."
even thought the folder is empty before so it's trying to create the test.zip file two times for some reason. Any idea why?

答:
As pointed out by s.m. in the comment above, the call to ZipFile.CreateFromDirectory() will attempt to create a zip file with the same location and file name for all the source directories.

If the intention is to create a single archive containing files from all the source directories, then the Zipfile.CreateFromDirectory() "shortcut" method cannot be used. Instead, you need to call ZipFile.Open(), get a ZipArchive object and use its CreateEntry() method to add every file individually.

Title: IOException file already exists C#

Body:
private void btn_Backup_Click(object sender, EventArgs e)
    {
        List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
        string TargetDir = this.tbox_Target.Text;

        foreach (DirectoryInfo directory in SourceDir)
        {
            foreach (var file in directory.GetFiles())
                if (this.checkbox_zipfiles.Checked == true)
                {
                    System.IO.Compression.ZipFile.CreateFromDirectory(directory.FullName, TargetDir + @"\test.zip");
                }
                else
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(directory.FullName, TargetDir, true);
                }
        }
    }

I'm creating a backup application and when I try to zip the files I need to backup it says: "The file 'C:\Users\Lada1208\Desktop\test\test.zip' already exists."
even thought the folder is empty before so it's trying to create the test.zip file two times for some reason. Any idea why?


问:
my_script throwing an error of bash: /home/usr/bin/my_sript: bin/bash/ bad interpreter: No such file or directory. How can I correct this error?
First and foremost the script is a 'hello world' script and it's stored in ~/jared/bin. Here's the script:

```<code>#!bin/bash
echo "hello world"
</code>```

Based on this question here, I tried:

The file is executable? I used:

```<code>chmod 755 my_script
</code>```

I ran the following commands, and here is the output:

```<code>which bash
</code>```

/bin/bash

and finally,

```<code>echo $PATH
</code>```

/home/jared/bin:/home/jared/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin

The file endings are UNIX as I wrote the script in VIM. However to be safe, I wrote additional 'hello world' scripts in Sublime and Atom and received the same error when I ran them.

I even tried running dos2unix on the file.

The script will execute when ran directly from the directory and will execute in any directory if I type bash hello_world
However it throws the error if I use ./

I don't know if this will help, but it seems relevant: I can use tab autocomplete on the script if I don't preface it with bash or ./

I fear, I'm making a really stupid mistake here, hopefully someone is prepared to make me feel incredibly silly today. Thanks!

答:
The first line of your script should be

```<code>#!/bin/bash
  ^
</code>```

It needs to be #! followed by an absolute path to bash. Note the slash before /bin.

Body:
First and foremost the script is a 'hello world' script and it's stored in ~/jared/bin. Here's the script:

#!bin/bash
echo "hello world"

Based on this question here, I tried:

The file is executable? I used:

chmod 755 my_script

I ran the following commands, and here is the output:

which bash

/bin/bash

and finally,

echo $PATH

/home/jared/bin:/home/jared/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin

The file endings are UNIX as I wrote the script in VIM. However to be safe, I wrote additional 'hello world' scripts in Sublime and Atom and received the same error when I ran them.

I even tried running dos2unix on the file.

The script will execute when ran directly from the directory and will execute in any directory if I type bash hello_world
However it throws the error if I use ./

I don't know if this will help, but it seems relevant: I can use tab autocomplete on the script if I don't preface it with bash or ./

I fear, I'm making a really stupid mistake here, hopefully someone is prepared to make me feel incredibly silly today. Thanks!

Body:
The first line of your script should be

#!/bin/bash
  ^

It needs to be #! followed by an absolute path to bash. Note the slash before /bin.


问:
Reading files with nested while loops
This function is part of a larger class, this functions purpose is to make a dictionary using the first lines last element as key and s_d as value. The c is supposed to be used for something else. When i print new_dict i get the desired result but the loop keeps running

```<code>def extract(filename):
f = open(filename)
new_dict={}
c = ''
l = f.readline().strip()
while l :
    first = f.readline().strip()[-1]
    s_d = f.readline().strip()
    l = f.readline().strip()
    new_line= f.readline().strip()
    while new_line != 'FIN' :
        c = c + new_line
        new_line = f.readline().strip()
    new_dict[first]= s_d
    print(new_dict)
</code>```

This function has to be done this way, with two while loops.How can i make the function stop running after it runs out of lines

BTW
the text file looks like:

```<code>IDS
ID 0
text(small description of item)
text(long description)
text(long desc second line)
FIN
ID 1
same as before
</code>```

答:
Check if the value returned from readline() function is an empty string. If it is, you have reached the last line and you can break.
https://docs.python.org/2/tutorial/inputoutput.html</p>

Title: Reading files with nested while loops

Body:
This function is part of a larger class, this functions purpose is to make a dictionary using the first lines last element as key and s_d as value. The c is supposed to be used for something else. When i print new_dict i get the desired result but the loop keeps running

def extract(filename):
f = open(filename)
new_dict={}
c = ''
l = f.readline().strip()
while l :
    first = f.readline().strip()[-1]
    s_d = f.readline().strip()
    l = f.readline().strip()
    new_line= f.readline().strip()
    while new_line != 'FIN' :
        c = c + new_line
        new_line = f.readline().strip()
    new_dict[first]= s_d
    print(new_dict)

This function has to be done this way, with two while loops.How can i make the function stop running after it runs out of lines

BTW
the text file looks like:

IDS
ID 0
text(small description of item)
text(long description)
text(long desc second line)
FIN
ID 1
same as before


问:
Jasper report exports empty data in PDF format when there is more data
I have a report to be exported in excel, pdf and word using jasper reports. I use xml file as the DataSource for the report, but when the data increases jasper report exports empty file in only for PDF format, when i reduce the data content it export the data available correctly. is there any limitation to pdf size? , how can we manage the size in jasper reports from java?

My jrxml is really big, so i cannot add it here, i have added my java code which i use to export the content:

```<code>JRAbstractExporter exporter = null;
if (format.equals("pdf")) {
    exporter = new JRPdfExporter();
    jasperPrint.setPageWidth(Integer.parseInt(pWidth));
} else if (format.equals("xls")) {
    exporter = new JRXlsExporter();

} else if (format.equals("doc")) {
    jasperPrint.setPageWidth(Integer.parseInt(pWidth));
}
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
        jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
        outputStream_);
exporter.exportReport();
contents = outputStream_.toByteArray();
response.setContentType("application/" + format);
response.addHeader("Content-disposition",
        "attachment;filename=" + name.toString() + "." + format);
</code>```

答:
A method that worked for me when dealing with big data and jasper reports is to first insert the data you need into a database table and then create a SQL statement on the jasper report that will join the table you created with the data you need. This puts more work on the database and less on the jasper library. Here is an example of a table that can be created to store report data. </p>

```<code>CREATE TABLE RE_EMPLOYEE(
EMPLOYEE_ID INT UNIQUE NOT NULL
COMPANY_ID INT UNIQUE NOT NULL
REPORT_NAME VARCHAR(20)
UNIQUE_USER_ID INT UNIQUE NOT NULL
PRIMARY KEY (EMPLOYEE_ID, COMPANY_ID)
);
</code>```

Body:
I have a report to be exported in excel, pdf and word using jasper reports. I use xml file as the DataSource for the report, but when the data increases jasper report exports empty file in only for PDF format, when i reduce the data content it export the data available correctly. is there any limitation to pdf size? , how can we manage the size in jasper reports from java?

My jrxml is really big, so i cannot add it here, i have added my java code which i use to export the content:

JRAbstractExporter exporter = null;
if (format.equals("pdf")) {
    exporter = new JRPdfExporter();
    jasperPrint.setPageWidth(Integer.parseInt(pWidth));
} else if (format.equals("xls")) {
    exporter = new JRXlsExporter();

} else if (format.equals("doc")) {
    jasperPrint.setPageWidth(Integer.parseInt(pWidth));
}
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
        jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
        outputStream_);
exporter.exportReport();
contents = outputStream_.toByteArray();
response.setContentType("application/" + format);
response.addHeader("Content-disposition",
        "attachment;filename=" + name.toString() + "." + format);

Body:
A method that worked for me when dealing with big data and jasper reports is to first insert the data you need into a database table and then create a SQL statement on the jasper report that will join the table you created with the data you need. This puts more work on the database and less on the jasper library. Here is an example of a table that can be created to store report data.

CREATE TABLE RE_EMPLOYEE(
EMPLOYEE_ID INT UNIQUE NOT NULL
COMPANY_ID INT UNIQUE NOT NULL
REPORT_NAME VARCHAR(20)
UNIQUE_USER_ID INT UNIQUE NOT NULL
PRIMARY KEY (EMPLOYEE_ID, COMPANY_ID)
);


问:
ASP.NET Stress Testing
Is there a way to test an application where you simulate a hundred different clients connecting to a IIS server and asking the same data? At the customer where our project is running they have 400 computers and they often do stress tests with all computers. I on the other hand have only got my laptop... (and a development server).

(In my case the data is asked through a WebORB Gateway).

答: Trty this tool , i've tested my website seems to work well >  x0Bench</p>

OwnerDisplayName: Lieven Cardoen

Title: ASP.NET Stress Testing


问:
Javascript createElement function
I have some code which is replicated throughout the main.js file

Javascript duplicates examples:

```<code>Example 1
for (i = userVote; i < 5; i++) {
var newVotesInput = document.createElement("input");
newVotesInput.id = "vote" + i;
newVotesInput.classList.add("vote", "displayn");
newVotesInput.type = "radio";
newVotesInput.name = "vote";
newVotesInput.value = i;
someElement.appendChild(newVotesInput);
}

Example 2
for (i = 1; i <= userVote; i++) {
var newVotesLabel = document.createElement("label");
newVotesLabel.id = "voteLabel" + i;
newVotesLabel.classList.add("voteHover");
newVotesLabel.htmlFor = "vote" + i;
someElement.appendChild(newVotesLabel);
}

Example 3
var newImg = document.createElement("img");
newImg.classList.add("babeImg", "boxsb", "leftIn");
newImg.id = "imgSrc";
newImg.src = jsonData.imgSrc;
someElement.appendChild(newImg);

Example 4
var newShuffle = document.createElement("img");
newShuffle.classList.add("shuffleImg");
newShuffle.id = "shuffleImg";
newShuffle.src = "assets/img/refresh.png";
someElement.appendChild(newShuffle);

Example 5
newImg.classList.add("babeImg", "boxsb", "leftIn");
newImg.id = "imgSrc";
newImg.src = jsonData.imgSrc;
imgInner.appendChild(newImg);
</code>```

As you can see the examples do the same which is creating an element but there are several parameters which differs from example to example.
How do i make a function that i can use for all of them?
right now i only know how to build one for exactly one specific example like so ->

```<code>function createElement(element, id, cls, src){
var newElement = document.createElement(element);
element.id = id;
element.classList.add(cls);
element.src = src;
someElement.appendChild(element);
}
</code>```

This is bascially Example 4.. but how do i make this more efficient and useable on all of the examples?

答:
I would suggest the following function:

```<code>function createElement(type, attributes) {
  var element = document.createElement(type);
  for (var key in attributes) {
    if (key == "class") {
        element.classList.add.apply(element.classList, attributes[key]); // add all classes at once
    } else {
      element[key] = attributes[key];
    }
  }
  someElement.appendChild(element);
}
</code>```

The function takes a type (input, img, etc) and a list of attributes (i.e. an object/dictionary). We loop through the attributes and add them to the new element. The only special case is with classes, with use a different syntax (and we can have multiple classes). Here is how you can use it:

```<code>var input = createElement("input", {
  "id": "myId",
  "class": ["one-class", "another-class"],
  "name": "someName"
});
</code>```

Note that the class has an array as a value.

The result will be:

```<code><input id="myId" class="one-class another-class" name="someName">
</code>```

Here is the jsfiddle.

EDIT

To better understand: in JS, objects are like dictionaries, i.e. a bunch of key-value pairs (and prototypes, but this is not important for this discussion).

If you have an object with an id attribute, you can access it using one of the following syntax:

```<code>myObject.id   // object style
myObject["id"] // dictionary style
</code>```

The second syntax is very useful, since you can use variables to access object attributes:

```<code>var attr = "id";
myObject[attr];
</code>```

Now, we can also iterate over an object, as we do with arrays. The only difference is that with arrays, the for in syntax returns the index, while with objects it returns the key or property name.

```<code>var myObject = { "id": 1, "name": "a name" }; // a basic object

for(var key in myObject) console.log(key, myObject[key]);
// will print
// id 1
// name a name
</code>```

If you understand these two mecanics, the code I gave you will get much clearer.

Title: Javascript createElement function

Body:
I have some code which is replicated throughout the main.js file

Javascript duplicates examples:

Example 1
for (i = userVote; i < 5; i++) {
var newVotesInput = document.createElement("input");
newVotesInput.id = "vote" + i;
newVotesInput.classList.add("vote", "displayn");
newVotesInput.type = "radio";
newVotesInput.name = "vote";
newVotesInput.value = i;
someElement.appendChild(newVotesInput);
}

Example 2
for (i = 1; i <= userVote; i++) {
var newVotesLabel = document.createElement("label");
newVotesLabel.id = "voteLabel" + i;
newVotesLabel.classList.add("voteHover");
newVotesLabel.htmlFor = "vote" + i;
someElement.appendChild(newVotesLabel);
}

Example 3
var newImg = document.createElement("img");
newImg.classList.add("babeImg", "boxsb", "leftIn");
newImg.id = "imgSrc";
newImg.src = jsonData.imgSrc;
someElement.appendChild(newImg);

Example 4
var newShuffle = document.createElement("img");
newShuffle.classList.add("shuffleImg");
newShuffle.id = "shuffleImg";
newShuffle.src = "assets/img/refresh.png";
someElement.appendChild(newShuffle);

Example 5
newImg.classList.add("babeImg", "boxsb", "leftIn");
newImg.id = "imgSrc";
newImg.src = jsonData.imgSrc;
imgInner.appendChild(newImg);

As you can see the examples do the same which is creating an element but there are several parameters which differs from example to example.
How do i make a function that i can use for all of them?
right now i only know how to build one for exactly one specific example like so ->

function createElement(element, id, cls, src){
var newElement = document.createElement(element);
element.id = id;
element.classList.add(cls);
element.src = src;
someElement.appendChild(element);
}

This is bascially Example 4.. but how do i make this more efficient and useable on all of the examples?

Body:
I would suggest the following function:

function createElement(type, attributes) {
  var element = document.createElement(type);
  for (var key in attributes) {
    if (key == "class") {
        element.classList.add.apply(element.classList, attributes[key]); // add all classes at once
    } else {
      element[key] = attributes[key];
    }
  }
  someElement.appendChild(element);
}

The function takes a type (input, img, etc) and a list of attributes (i.e. an object/dictionary). We loop through the attributes and add them to the new element. The only special case is with classes, with use a different syntax (and we can have multiple classes). Here is how you can use it:

var input = createElement("input", {
  "id": "myId",
  "class": ["one-class", "another-class"],
  "name": "someName"
});

Note that the class has an array as a value.

The result will be:

<input id="myId" class="one-class another-class" name="someName">

Here is the jsfiddle.

EDIT

To better understand: in JS, objects are like dictionaries, i.e. a bunch of key-value pairs (and prototypes, but this is not important for this discussion).

If you have an object with an id attribute, you can access it using one of the following syntax:

myObject.id   // object style
myObject["id"] // dictionary style

The second syntax is very useful, since you can use variables to access object attributes:

var attr = "id";
myObject[attr];

Now, we can also iterate over an object, as we do with arrays. The only difference is that with arrays, the for in syntax returns the index, while with objects it returns the key or property name.

var myObject = { "id": 1, "name": "a name" }; // a basic object

for(var key in myObject) console.log(key, myObject[key]);
// will print
// id 1
// name a name

If you understand these two mecanics, the code I gave you will get much clearer.


答:
first line should look like:

```<code>#!/bin/bash
</code>```

you forgot the '/' after '!' so the system cannot find correct (absolute) path to bash

Title: my_script throwing an error of bash: /home/usr/bin/my_sript: bin/bash/ bad interpreter: No such file or directory. How can I correct this error?

Body:
first line should look like:

#!/bin/bash

you forgot the '/' after '!' so the system cannot find correct (absolute) path to bash


问:
Adding a ReadOnly property to MaterialSingleLineTextField
How to add a ReadOnly property to this control?

The control doesn't have a ReadOnly property.
I'm a beginner in C# and all I can think for now is this:

```<code>public class MaterialSingleLineTextFieldRO : MaterialSingleLineTextField
{
    public bool ReadOnly { ... };
}
</code>```

答:
Reza's solution solved my problem.

I have another solution by adding the code in the main source code (MaterialSkin.dll)

Body:
How to add a ReadOnly property to this control?

The control doesn't have a ReadOnly property.
I'm a beginner in C# and all I can think for now is this:

public class MaterialSingleLineTextFieldRO : MaterialSingleLineTextField
{
    public bool ReadOnly { ... };
}


问:
Loop for this particular summation
Given a pattern... (1 / 2)^2 + (2 / 3)^2 + (3 / 4)^2 + ...

Input is n; which becomes the highest denominator used in the summation of these fractions.

When a user enters n = 2; the sum is simply (1 / 2)^2.

When a user enters n = 3; the sum is (1 / 2)^2 + (2 / 3)^2

I believe I've solved this problem (we assume the user enters an integer greater than or equal to 2)...

```<code>int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow(--counter/++counter, 2);
counter++;
}

System.out.println("Sum is " + sum);
</code>```

Is there any "obvious" way to simplify my solution to this problem (whilst remaining as a while-loop)? This is one of the first loops I've ever written. I'm not sure if less variables can be used to solve this problem.

答:
Why dont simplify it and write this:

```<code>int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow((counter - 1)/counter, 2);
counter++;
}

System.out.println("Sum is " + sum);
</code>```

i dont know who is computed first (++counter) or (--counter), if (--counter) your response is correct, but dont pollute your code with ++ or --, use them only if you need it.

Title: Loop for this particular summation

Body:
Given a pattern... (1 / 2)^2 + (2 / 3)^2 + (3 / 4)^2 + ...

Input is n; which becomes the highest denominator used in the summation of these fractions.

When a user enters n = 2; the sum is simply (1 / 2)^2.

When a user enters n = 3; the sum is (1 / 2)^2 + (2 / 3)^2

I believe I've solved this problem (we assume the user enters an integer greater than or equal to 2)...

int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow(--counter/++counter, 2);
counter++;
}

System.out.println("Sum is " + sum);

Is there any "obvious" way to simplify my solution to this problem (whilst remaining as a while-loop)? This is one of the first loops I've ever written. I'm not sure if less variables can be used to solve this problem.

Body:
Why dont simplify it and write this:

int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow((counter - 1)/counter, 2);
counter++;
}

System.out.println("Sum is " + sum);

i dont know who is computed first (++counter) or (--counter), if (--counter) your response is correct, but dont pollute your code with ++ or --, use them only if you need it.


问:
How do I access individual words after splitting a string?
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
</code>```

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

```<code>if (word[0] == "something")
   do_this();
else
   do_that();
</code>```

答: Your token variable is a String, not an array of strings.  By using the [0], you're asking for the first character of token, not the String itself.</p>

ContentLicense: CC BY-SA 2.5

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();


问:
How to prevent a crash when the uiviewcontroller is deinited and there is an active urlsessiontask
I have a crash in my Swift 3 iOS app when I have an active URLSessionTask and the user presses the back button and the view controller is deinited.  I call the cancel method on the urlsessiontask in the back button and no crash occurs at that time but when the user goes back to the view controller the app crashes.  If the user allows the url session task to complete there is no crash.  Does anyone know what I can do to prevent the crash?  I am using iOS 10, Swift 3, Xcode 8.  Thanks in advance.</p>

答:
Don't make the view controller the delegate of the URL session if it might not be around when the download completes.

Here's one solution:

Create a DownloadManager singleton that is the delegate of the URL session, saves the files to disk once the download is complete, records info about the file having been downloaded, and then notifies its delegate, using a weak delegate property.

(Some people believe that singletons are the root of all evil and should never be used. I'm not one of those people. To my mind an app-wide download manager is an excellent use-case for a singleton.)


问:
How to loop through polygons in a shapefile in r?
I have created a map where i have plotted population density with a shapefile using the Leaflet package. I'am trying to loop through each polygon on the map, is this possible and how could do it?</p>

<p>**Map: Leaflet map </p>

```<code>#Create Leaflet map
map <- leaflet()  %>% addTiles() %>%
  setView(lng = -7.1050, lat=53.2000,zoom=8) %>%

  addPolygons(data=m,weight=1, popup = map_popup2, fillOpacity = .5) %>%

  addCircleMarkers(data = m, lng = ~long_xcord,
                   lat = ~lat_ycord, radius=.5, color="green") %>%

  addCircles(data = m, lng = ~long_xcord,
             lat = ~lat_ycord, popup = map_popup,
             radius = 4828.03, fillOpacity = 0.1, #3218.69 = 2 miles
             color = 'black', fillColor = 'blue',weight = 2, label=m$` name`) %>%

  addLegend("bottomright", pal = heat, values = m$pop,
            title = "Population",
            opacity = 1)
</code>```

答:
Just use [. Here's a modified example from ?"SpatialPolygonsDataFrame-class"

```<code>library(sp)

Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)

Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

plot(0,0, xlim = c(0, 10), ylim = c(0, 5), type = "n")

for (i in 1:nrow(coordinates(SpP))) {
  plot(SpP[i, ], add = TRUE)
}
</code>```

Body:
I have created a map where i have plotted population density with a shapefile using the Leaflet package. I'am trying to loop through each polygon on the map, is this possible and how could do it?

**Map: Leaflet map

#Create Leaflet map
map <- leaflet()  %>% addTiles() %>%
  setView(lng = -7.1050, lat=53.2000,zoom=8) %>%

  addPolygons(data=m,weight=1, popup = map_popup2, fillOpacity = .5) %>%

  addCircleMarkers(data = m, lng = ~long_xcord,
                   lat = ~lat_ycord, radius=.5, color="green") %>%

  addCircles(data = m, lng = ~long_xcord,
             lat = ~lat_ycord, popup = map_popup,
             radius = 4828.03, fillOpacity = 0.1, #3218.69 = 2 miles
             color = 'black', fillColor = 'blue',weight = 2, label=m$` name`) %>%

  addLegend("bottomright", pal = heat, values = m$pop,
            title = "Population",
            opacity = 1)

Body:
Just use [. Here's a modified example from ?"SpatialPolygonsDataFrame-class"

library(sp)

Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)

Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

plot(0,0, xlim = c(0, 10), ylim = c(0, 5), type = "n")

for (i in 1:nrow(coordinates(SpP))) {
  plot(SpP[i, ], add = TRUE)
}


问:
How to append unicode string to list of strings in Julia?
For integers, list comprehension can be done with:

```<code>julia> nums = [1,2,3,4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> nums = [i+1 for i in nums]
4-element Array{Int64,1}:
 2
 3
 4
 5
</code>```

But when I tried to add a character to a string, it throws an error:

```<code>julia> s = split("the lazy fox jumps over the brown dog")
8-element Array{SubString{String},1}:
 "the"
 "lazy"
 "fox"
 "jumps"
 "over"
 "the"
 "brown"
 "dog"

julia> s2 = [word +'X' for word in s]
ERROR: syntax: invalid comprehension syntax
</code>```

And when the character is a private unicode char (http://www.fileformat.info/info/unicode/char/e000/index.htm), it throws another error:

```<code>julia> s2 = [word + u'\uE000' for word in s]
</code>```

ERROR: UndefVarError: u not defined
 in collect(::Base.Generator{Array{SubString{String},1},##3#4}) at ./array.jl:307

How to append unicode char/string to list of strings in Julia?

答:
As the other answer said, if you need to append a string you can use the string concatenation operator:

```<code>[word * "X" for word in s]
</code>```

If you really need to concatenate a Char, say, because you have it in some variable c, it can be done using string interpolation, like so:

```<code>["$word$c" for word in s]
</code>```

(Of course, you could also just convert it to a String with string(c) and use the first form.)

Body:
For integers, list comprehension can be done with:

julia> nums = [1,2,3,4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> nums = [i+1 for i in nums]
4-element Array{Int64,1}:
 2
 3
 4
 5

But when I tried to add a character to a string, it throws an error:

julia> s = split("the lazy fox jumps over the brown dog")
8-element Array{SubString{String},1}:
 "the"
 "lazy"
 "fox"
 "jumps"
 "over"
 "the"
 "brown"
 "dog"

julia> s2 = [word +'X' for word in s]
ERROR: syntax: invalid comprehension syntax

And when the character is a private unicode char (http://www.fileformat.info/info/unicode/char/e000/index.htm), it throws another error:

julia> s2 = [word + u'\uE000' for word in s]

ERROR: UndefVarError: u not defined
 in collect(::Base.Generator{Array{SubString{String},1},##3#4}) at ./array.jl:307

How to append unicode char/string to list of strings in Julia?

Body:
As the other answer said, if you need to append a string you can use the string concatenation operator:

[word * "X" for word in s]

If you really need to concatenate a Char, say, because you have it in some variable c, it can be done using string interpolation, like so:

["$word$c" for word in s]

(Of course, you could also just convert it to a String with string(c) and use the first form.)


问:
How to convert PowerPoint (.ppt, .pptx) to several images of each slide?
Do you guys have some .Net libraries which has ability to convert a PowerPoint Presentation file into images?</p>

答:
do check
 PPT slides to images

https://stackoverflow.com/questions/733347/is-it-possible-to-convert-powerpoint-to-images-programatically


问:
Editable table / grid in asp.net with VB
I'm a front-end dev, working with a VB developer to create a web application for entering fields of data: names, objectives and due dates.

Our client wants the data to be entered like an Excel spreadsheet: tabbing through multiple fields and entering the data. And then that inputted data gets outputted as a grid or table elsewhere to view / approve.

I work mostly in CSS/JS/PHP, and I'm pretty new to .ASPX. We are working in a .NET 4.0 framework with VB running on the back end to connect to SQL Server. On the front end we have .ASPX web forms along with CSS/JS.

Please Note: this is NOT an MVC or Core framework, but an older 4.0 .NET framework.

We've tried multiple options, but none of these work the way our client wants. I've tried this both as <asp:Table> with rows of <input> fields, and also as a
 of <asp:TextBox> input fields. But we've run into problems both ways. We also tried a <asp:GridView> but that didn't work either. It was only Read-only, not editable. And it would only let you edit one row at a time. Client wanted entire table/grid to be editable. Sample of code for one below. The problem with this is that each ID is a different name: TextBox1, TextBox2, etc. And that doesn't work for the VB to save records to the database.

Has anyone built a similar web application? What has worked for you?

```<code><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="obj-table">
        <table>
            <tr>
                <td>
                    <asp:Label ID="Label1" CssClass="label name" runat="server" Text="Name"></asp:Label></td>
                <td>
                    <asp:Label ID="Label2" CssClass="label" runat="server" Text="Objective"></asp:Label></td>
                <td>
                    <asp:Label ID="Label3" CssClass="label" runat="server" Text="Due Date"></asp:Label></td>
                <td>
                    <asp:Label ID="Label4" CssClass="checkbox" runat="server" Text="Approved"></asp:Label></td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="Name" CssClas="textbox" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="Descrp" CssClas="textbox" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="DueDate" CssClas="textbox" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:CheckBox ID="CheckBox" runat="server"/>
                </td>

                <%-- use this for when we need a drop down menu
                <td>
                    <asp:DropDownList ID="DropDown" runat="server"></asp:DropDownList>
                </td>--%>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:CheckBox ID="CheckBox1" runat="server"/>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                </td>

                <td>
                    <asp:CheckBox ID="CheckBox2" runat="server"/>
                </td>
            </tr>
        </table>
</div>
</code>```

答: You can use the grid view element that will automate your desired operations in sync with asp sql data source object</p>

Body:
I'm a front-end dev, working with a VB developer to create a web application for entering fields of data: names, objectives and due dates.

Our client wants the data to be entered like an Excel spreadsheet: tabbing through multiple fields and entering the data. And then that inputted data gets outputted as a grid or table elsewhere to view / approve.

I work mostly in CSS/JS/PHP, and I'm pretty new to .ASPX. We are working in a .NET 4.0 framework with VB running on the back end to connect to SQL Server. On the front end we have .ASPX web forms along with CSS/JS.

Please Note: this is NOT an MVC or Core framework, but an older 4.0 .NET framework.

We've tried multiple options, but none of these work the way our client wants. I've tried this both as <asp:Table> with rows of <input> fields, and also as a
 of <asp:TextBox> input fields. But we've run into problems both ways. We also tried a <asp:GridView> but that didn't work either. It was only Read-only, not editable. And it would only let you edit one row at a time. Client wanted entire table/grid to be editable. Sample of code for one below. The problem with this is that each ID is a different name: TextBox1, TextBox2, etc. And that doesn't work for the VB to save records to the database.

Has anyone built a similar web application? What has worked for you?

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

                    <asp:Label ID="Label1" CssClass="label name" runat="server" Text="Name"></asp:Label>

                    <asp:Label ID="Label2" CssClass="label" runat="server" Text="Objective"></asp:Label>

                    <asp:Label ID="Label3" CssClass="label" runat="server" Text="Due Date"></asp:Label>

                    <asp:Label ID="Label4" CssClass="checkbox" runat="server" Text="Approved"></asp:Label>

                    <asp:TextBox ID="Name" CssClas="textbox" runat="server"></asp:TextBox>

                    <asp:TextBox ID="Descrp" CssClas="textbox" runat="server"></asp:TextBox>

                    <asp:TextBox ID="DueDate" CssClas="textbox" runat="server"></asp:TextBox>

                    <asp:CheckBox ID="CheckBox" runat="server"/>

                <%-- use this for when we need a drop down menu

                    <asp:DropDownList ID="DropDown" runat="server"></asp:DropDownList>
                	--%>

                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

                    <asp:CheckBox ID="CheckBox1" runat="server"/>

                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>

                    <asp:CheckBox ID="CheckBox2" runat="server"/>


问:
maven dependancy lookup fails even if I have specified repo
I am trying to run a project. Its not able to find a dependency. So I have added repository inside pom.xml

But its not able to lookup for the same.

from pom.xml

```<code><repositories>
    <repository>

        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>fail</checksumPolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>fail</checksumPolicy>
        </snapshots>
        <id>spring</id>
        <name>Spring Framework Maven Release Repository</name>
        <url>http://oss.sonatype.org/content/groups/public</url>
        <layout>default</layout>
    </repository>

</repositories>
</code>```

81749 [WARNING] Unable to create Maven project for
  com.gemstone.gemfire:gemfire:pom:8.1.0 from repository.
  org.apache.maven.project.ProjectBuildingException: Error resolving
  project artifact: Failure to find
  com.gemstone.gemfire:gemfire:pom:8.1.0 in
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced for project
  com.gemstone.gemfire:gemfire:pom:8.1.0

when i applied -X i see following

```<code>103850 [DEBUG] === PROJECT BUILD PLAN ================================================
103850 [DEBUG] Project:       xxxxx:xxxxxx:0.0.1-SNAPSHOT
103850 [DEBUG] Dependencies (collect): [compile+runtime]
103850 [DEBUG] Dependencies (resolve): [compile, compile+runtime, runtime, test]
103850 [DEBUG] Repositories (dependencies): [central (https://repo.maven.apache.org/maven2, default, releases)]
103850 [DEBUG] Repositories (plugins)     : [central (https://repo.maven.apache.org/maven2, default, releases)]
</code>```

What am I missing here ? I have parent pom.xml with repository mention

parent is not included in child

答:
Given this pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.gemstone.gemfire</groupId>
            <artifactId>gemfire</artifactId>
            <version>8.1.0</version>
        </dependency>
    </dependencies>
</project>
</code>```

When I tried to run:

```<code>$mvn clean compile
</code>```

The result was:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building test 0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/com/gemstone/gemfire/gemfire/8.1.0/gemfire-8.1.0.pom
[WARNING] The POM for com.gemstone.gemfire:gemfire:jar:8.1.0 is missing, no dependency information available
Downloading: https://repo.maven.apache.org/maven2/com/gemstone/gemfire/gemfire/8.1.0/gemfire-8.1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.642 s
[INFO] Finished at: 2017-04-02T13:31:34+01:00
[INFO] Final Memory: 11M/131M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project test: Could not resolve dependencies for project test:test:jar:0.1-SNAPSHOT: Could not find artifact com.gemstone.gemfire:gemfire:jar:8.1.0 in central (https://repo.maven.apache.org/maven2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
</code>```

So I researched for the dependency and repository in mvnrepository.com and I found the repositories that contains this dependency are Spring Plugins and Spring Libs:

Then I just added the Spring Plugins repository in my pom and it worked!

The final POM is:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.gemstone.gemfire</groupId>
            <artifactId>gemfire</artifactId>
            <version>8.1.0</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring</id>
            <url>http://repo.spring.io/plugins-release</url>
        </repository>
    </repositories>
</project>
</code>```

Body:
I am trying to run a project. Its not able to find a dependency. So I have added repository inside pom.xml

But its not able to lookup for the same.

from pom.xml

<repositories>
    <repository>

        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>fail</checksumPolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>fail</checksumPolicy>
        </snapshots>
        <id>spring</id>
        <name>Spring Framework Maven Release Repository</name>
        <url>http://oss.sonatype.org/content/groups/public</url>
        <layout>default</layout>
    </repository>

</repositories>

81749 [WARNING] Unable to create Maven project for
  com.gemstone.gemfire:gemfire:pom:8.1.0 from repository.
  org.apache.maven.project.ProjectBuildingException: Error resolving
  project artifact: Failure to find
  com.gemstone.gemfire:gemfire:pom:8.1.0 in
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced for project
  com.gemstone.gemfire:gemfire:pom:8.1.0

when i applied -X i see following

103850 [DEBUG] === PROJECT BUILD PLAN ================================================
103850 [DEBUG] Project:       xxxxx:xxxxxx:0.0.1-SNAPSHOT
103850 [DEBUG] Dependencies (collect): [compile+runtime]
103850 [DEBUG] Dependencies (resolve): [compile, compile+runtime, runtime, test]
103850 [DEBUG] Repositories (dependencies): [central (https://repo.maven.apache.org/maven2, default, releases)]
103850 [DEBUG] Repositories (plugins)     : [central (https://repo.maven.apache.org/maven2, default, releases)]

What am I missing here ? I have parent pom.xml with repository mention

parent is not included in child

Body:
Given this pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.gemstone.gemfire</groupId>
            <artifactId>gemfire</artifactId>
            <version>8.1.0</version>
        </dependency>
    </dependencies>
</project>

When I tried to run:

$mvn clean compile

The result was:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building test 0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/com/gemstone/gemfire/gemfire/8.1.0/gemfire-8.1.0.pom
[WARNING] The POM for com.gemstone.gemfire:gemfire:jar:8.1.0 is missing, no dependency information available
Downloading: https://repo.maven.apache.org/maven2/com/gemstone/gemfire/gemfire/8.1.0/gemfire-8.1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.642 s
[INFO] Finished at: 2017-04-02T13:31:34+01:00
[INFO] Final Memory: 11M/131M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project test: Could not resolve dependencies for project test:test:jar:0.1-SNAPSHOT: Could not find artifact com.gemstone.gemfire:gemfire:jar:8.1.0 in central (https://repo.maven.apache.org/maven2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

So I researched for the dependency and repository in mvnrepository.com and I found the repositories that contains this dependency are Spring Plugins and Spring Libs:

Then I just added the Spring Plugins repository in my pom and it worked!

The final POM is:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.gemstone.gemfire</groupId>
            <artifactId>gemfire</artifactId>
            <version>8.1.0</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring</id>
            <url>http://repo.spring.io/plugins-release</url>
        </repository>
    </repositories>
</project>


问:
minimum instantiate class object, when query getInstance<T>(), based on inheritance
User of my library will ask for an instance of any class via getInstance<T>().

Among all classes {T1,T2,T3,...,Tn} that user asks (appearance of calling getInstance<T>()) in a certain program, if there is a pair of (i,j) and Ti derived from Tj, I will create only the bigger one, e.g. Ti.

Here is an example.

Assume that user's code code ask me to create these classes:-

Physic

Rigid

Constraint

Graphic

and their inheritance is as followed:-

(The above four classes are marked with yellow in the diagram.)

My code will create minimum amount of class instances that cover the whole tree.

In this case, the best solution are 3 : Rigid, Constraint, Graphic.

Roughly speaking, the three arrows pass all classes in the tree.

In this case, there will be 2 instances of Physic, but I don't care.  (Thank Christian Hackl)

More specifically, getInstance<Physic>() can return any of them.

The underlying type can be Rigid* or Constraint* - both are OK.

If there are many minimum solutions, any one of them are OK.

Here is what I dream :-

```<code>//..... some list to cache std::function .... ?
template<class T> T* getInstance(){
    //return new T()  ?
}
class B{};
class C{};
class D : public B{};
int main(){
    //..... allow to insert some code here ...... (a little less preferable)
    B* b=getInstance<B>();   //return B*  (implicitly cast D*->B*)
    C* c=getInstance<C>();   //return C*
    D* d=getInstance<D>();   //return D*
    assert( static_cast<D*>(b) == d );
    delete d;    delete c;
    //no memory leak
}
</code>```

How to do it?

This is closest question : Create "custom typeid" for many types AND cache their sizeof()

I feel that it is possible : I have to cache the type by using :-

lambda without capture / std::function -> keep it in a list

The cache function call std::is_base_of.

Then, I have to recognize all leaf-nodes in some ways.

Amount of classes that have to be instantiated = amount of leaf-nodes.

However, it is far from a concrete idea.

I want to create a very-sophisticated singleton manager for my libraries + educational purpose.

I know it is quite not a good practice,  but I believe the solution will enlighten me in C++ area.

 Just in case it is not so obvious - this is not a homework / interview.

答:
You mainly need a type traits that, given a type and a list of type, return a sort of top derived type from the list.

Not really elegant (I'll try to semplify it) but the following code should give you an example

```<code>#include <cassert>
#include <iostream>
#include <type_traits>

struct core {};
struct physic     : public core {};
struct rigid      : public physic {};
struct constraint : public physic {};
struct graphic    : public core {};

template <typename ... Ts>
struct contTypes
 { };

template <typename T0, typename T1>
struct isStrictBase
 { static constexpr bool value =
         (false == std::is_same<T0, T1>::value)
      && (true == std::is_base_of<T0, T1>::value); };

template <bool, typename...>
struct chooseT;

template <typename, typename, typename>
struct getTopTypeH;

template <typename C0, typename T, typename T0, typename C1>
struct chooseT<true, C0, T, T0, C1>
 { using type = typename getTopTypeH<C0, T0, C0>::type; };

template <typename C0, typename T, typename T0, typename C1>
struct chooseT<false, C0, T, T0, C1>
 { using type = typename getTopTypeH<C0, T, C1>::type; };

template <typename, typename, typename>
struct getTopTypeH;

template <template <typename ...> class Ct, typename ... Ts0, typename T>
struct getTopTypeH<Ct<Ts0...>, T, Ct<>>
 { using type = T; };

template <template <typename ...> class Ct, typename ... Ts0,
          typename T, typename T0, typename ... Ts>
struct getTopTypeH<Ct<Ts0...>, T, Ct<T0, Ts...>>
 {
   using type = typename chooseT<isStrictBase<T, T0>::value,
                                 Ct<Ts0...>, T, T0, Ct<Ts...>>::type;
 };

template <typename T, typename CT>
struct getTopType
 { using type = typename getTopTypeH<CT, T, CT>::type; };

template <typename T>
struct staticWrapper
 {
   static T * getPnt ()
    {
      static T st{};

      return & st;
    }
 };

using cT = contTypes<core, physic, rigid, constraint, graphic>;

template <typename T>
T * getInstance ()
 { return staticWrapper<typename getTopType<T, cT>::type>::getPnt(); }

int main ()
 {
   auto p0 = getInstance<core>();
   auto p1 = getInstance<physic>();
   auto p2 = getInstance<rigid>();
   auto p3 = getInstance<constraint>();
   auto p4 = getInstance<graphic>();

   assert( p0 == p1 );
   assert( p0 == p2 );

   std::cout << "assert passed" << std::endl;
 }
</code>```

Body:
User of my library will ask for an instance of any class via getInstance<T>().

Among all classes {T1,T2,T3,...,Tn} that user asks (appearance of calling getInstance<T>()) in a certain program, if there is a pair of (i,j) and Ti derived from Tj, I will create only the bigger one, e.g. Ti.

Here is an example.

Assume that user's code code ask me to create these classes:-

Physic

Rigid

Constraint

Graphic

and their inheritance is as followed:-

(The above four classes are marked with yellow in the diagram.)

My code will create minimum amount of class instances that cover the whole tree.

In this case, the best solution are 3 : Rigid, Constraint, Graphic.

Roughly speaking, the three arrows pass all classes in the tree.

In this case, there will be 2 instances of Physic, but I don't care.  (Thank Christian Hackl)

More specifically, getInstance<Physic>() can return any of them.

The underlying type can be Rigid* or Constraint* - both are OK.

If there are many minimum solutions, any one of them are OK.

Here is what I dream :-

//..... some list to cache std::function .... ?
template<class T> T* getInstance(){
    //return new T()  ?
}
class B{};
class C{};
class D : public B{};
int main(){
    //..... allow to insert some code here ...... (a little less preferable)
    B* b=getInstance();   //return B*  (implicitly cast D*->B*)
    C* c=getInstance<C>();   //return C*
    D* d=getInstance<D>();   //return D*
    assert( static_cast<D*>(b) == d );
    delete d;    delete c;
    //no memory leak
}

How to do it?

This is closest question : Create "custom typeid" for many types AND cache their sizeof()

I feel that it is possible : I have to cache the type by using :-

lambda without capture / std::function -> keep it in a list

The cache function call std::is_base_of.

Then, I have to recognize all leaf-nodes in some ways.

Amount of classes that have to be instantiated = amount of leaf-nodes.

However, it is far from a concrete idea.

I want to create a very-sophisticated singleton manager for my libraries + educational purpose.

I know it is quite not a good practice,  but I believe the solution will enlighten me in C++ area.

 Just in case it is not so obvious - this is not a homework / interview.

Body:
You mainly need a type traits that, given a type and a list of type, return a sort of top derived type from the list.

Not really elegant (I'll try to semplify it) but the following code should give you an example

#include <cassert>
#include <iostream>
#include <type_traits>

struct core {};
struct physic     : public core {};
struct rigid      : public physic {};
struct constraint : public physic {};
struct graphic    : public core {};

template <typename ... Ts>
struct contTypes
 { };

template <typename T0, typename T1>
struct isStrictBase
 { static constexpr bool value =
         (false == std::is_same<T0, T1>::value)
      && (true == std::is_base_of<T0, T1>::value); };

template <bool, typename...>
struct chooseT;

template <typename, typename, typename>
struct getTopTypeH;

template <typename C0, typename T, typename T0, typename C1>
struct chooseT<true, C0, T, T0, C1>
 { using type = typename getTopTypeH<C0, T0, C0>::type; };

template <typename C0, typename T, typename T0, typename C1>
struct chooseT<false, C0, T, T0, C1>
 { using type = typename getTopTypeH<C0, T, C1>::type; };

template <typename, typename, typename>
struct getTopTypeH;

template <template <typename ...> class Ct, typename ... Ts0, typename T>
struct getTopTypeH<Ct<Ts0...>, T, Ct<>>
 { using type = T; };

template <template <typename ...> class Ct, typename ... Ts0,
          typename T, typename T0, typename ... Ts>
struct getTopTypeH<Ct<Ts0...>, T, Ct<T0, Ts...>>
 {
   using type = typename chooseT<isStrictBase<T, T0>::value,
                                 Ct<Ts0...>, T, T0, Ct<Ts...>>::type;
 };

template <typename T, typename CT>
struct getTopType
 { using type = typename getTopTypeH<CT, T, CT>::type; };

template <typename T>
struct staticWrapper
 {
   static T * getPnt ()
    {
      static T st{};

      return & st;
    }
 };

using cT = contTypes<core, physic, rigid, constraint, graphic>;

template <typename T>
T * getInstance ()
 { return staticWrapper<typename getTopType<T, cT>::type>::getPnt(); }

int main ()
 {
   auto p0 = getInstance<core>();
   auto p1 = getInstance<physic>();
   auto p2 = getInstance<rigid>();
   auto p3 = getInstance<constraint>();
   auto p4 = getInstance<graphic>();

   assert( p0 == p1 );
   assert( p0 == p2 );

   std::cout << "assert passed" << std::endl;
 }


问:
Lucene multi word tokens with delimiter
I am just starting with Lucene so it's probably a beginners question. We are trying to implement a semantic search on digital books and already have a concept generator, so for example the contexts I generate for a new article could be:
|Green Beans | Spring Onions | Cooking |
I am using Lucene to create an index on the books/articles using only the extracted concepts (stored in a temporary document for that purpose). Now the standard analyzer is creating single word tokens: Green, Beans, Spring, Onions, Cooking, which of course is not the same.

My question: is there an analyzer that is able to detect delimiters around tokens (|| in our example), or an analyzer that is able to detect multi-word constructs?

I'm afraid we'll have to create our own analyzer, but I don't quite know where to start for that one.

答:
I came across this question because I am doing something with my Lucene mechanisms which creates data structures to do with sequencing, in effect "hijacking" the Lucene classes.  Otherwise I can't imagine why people would want knowledge of the separators ("delimiters") between tokens, but as it was quite tricky I thought I'd put it here for the benefit of anyone who might need to.

You have to rewrite your own versions of StandardTokenizer and StandardTokenizerImpl.  These are both final classes so you can't extend them.

SeparatorDeliveringTokeniserImpl (tweaked from source of StandardTokenizerImpl):

3 new fields:

```<code>private int startSepPos = 0;
private int endSepPos = 0;
private String originalBufferAsString;
</code>```

Tweak these methods:

```<code>public final void getText(CharTermAttribute t) {
    t.copyBuffer(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead);
    if( originalBufferAsString == null ){
        originalBufferAsString = new String( zzBuffer, 0, zzBuffer.length );
    }
    // startSepPos == -1 is a "flag condition": it means that this token is the last one and it won't be followed by a sep
    if( startSepPos != -1 ){
        // if the flag is NOT set, record the start pos of the next sep...
        startSepPos = zzMarkedPos;
    }
}

public final void yyreset(java.io.Reader reader) {
    zzReader = reader;
    zzAtBOL = true;
    zzAtEOF = false;
    zzEOFDone = false;
    zzEndRead = zzStartRead = 0;
    zzCurrentPos = zzMarkedPos = 0;
    zzFinalHighSurrogate = 0;
    yyline = yychar = yycolumn = 0;
    zzLexicalState = YYINITIAL;
    if (zzBuffer.length > ZZ_BUFFERSIZE)
        zzBuffer = new char[ZZ_BUFFERSIZE];
    // reset fields responsible for delivering separator...
    originalBufferAsString = null;
    startSepPos = 0;
    endSepPos = 0;
}
</code>```

(inside getNextToken:)

```<code>if ((zzAttributes & 1) == 1) {
    zzAction = zzState;
    zzMarkedPosL = zzCurrentPosL;
    if ((zzAttributes & 8) == 8) {
        // every occurrence of a separator char leads here...
        endSepPos = zzCurrentPosL;
        break zzForAction;
    }
}
</code>```

And make a new method:

```<code>String getPrecedingSeparator() {
    String sep = null;
    if( originalBufferAsString == null ){
        sep = new String( zzBuffer, 0, endSepPos );
    }
    else if( startSepPos == -1 || endSepPos <= startSepPos ){
        sep = "";
    }
    else {
        sep = originalBufferAsString.substring( startSepPos, endSepPos );
    }
    if( zzMarkedPos < startSepPos ){
        // ... then this is a sign that the next token will be the last one... and will NOT have a trailing separator
        // so set a "flag condition" for next time this method is called
        startSepPos = -1;
    }
    return sep;
}
</code>```

SeparatorDeliveringTokeniser (tweaked from source of StandardTokenizer):

Add this:

```<code>private String separator;
String getSeparator(){
    // normally this delivers a preceding separator... but after incrementToken returns false, if there is a trailing
    // separator, it then delivers that...
    return separator;
}
</code>```

(inside incrementToken:)

```<code>while(true) {
  int tokenType = scanner.getNextToken();

  // added NB this gives you the separator which PRECEDES the token
  // which you are about to get from scanner.getText( ... )
  separator = scanner.getPrecedingSeparator();

  if (tokenType == SeparatorDeliveringTokeniserImpl.YYEOF) {
      // NB at this point sep is equal to the trailing separator...
    return false;
  }
  ...
</code>```

Usage:

In my FilteringTokenFilter subclass, called TokenAndSeparatorExamineFilter, the methods accept and end look like this:

```<code>@Override
public boolean accept() throws IOException {
    String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
    // a preceding separator can only be an empty String if we are currently
    // dealing with the first token and if the sequence starts with a token
    if (!sep.isEmpty()) {
       // ... do something with the preceding separator
    }
    // then get the token...
    String token = getTerm();
    // ... do something with the token

    // my filter does no filtering! Every token is accepted...:
    return true;
}

@Override
public void end() throws IOException {
    // deals with trailing separator at the end of a sequence of tokens and separators (if there is one, i.e. if it doesn't end with a token)
    String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
    // NB will be an empty String if there is no trailing separator
    if (!sep.isEmpty()) {
        // ... do something with this trailing separator
    }
}
</code>```

Title: Lucene multi word tokens with delimiter

Body:
I came across this question because I am doing something with my Lucene mechanisms which creates data structures to do with sequencing, in effect "hijacking" the Lucene classes.  Otherwise I can't imagine why people would want knowledge of the separators ("delimiters") between tokens, but as it was quite tricky I thought I'd put it here for the benefit of anyone who might need to.

You have to rewrite your own versions of StandardTokenizer and StandardTokenizerImpl.  These are both final classes so you can't extend them.

SeparatorDeliveringTokeniserImpl (tweaked from source of StandardTokenizerImpl):

3 new fields:

private int startSepPos = 0;
private int endSepPos = 0;
private String originalBufferAsString;

Tweak these methods:

public final void getText(CharTermAttribute t) {
    t.copyBuffer(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead);
    if( originalBufferAsString == null ){
        originalBufferAsString = new String( zzBuffer, 0, zzBuffer.length );
    }
    // startSepPos == -1 is a "flag condition": it means that this token is the last one and it won't be followed by a sep
    if( startSepPos != -1 ){
        // if the flag is NOT set, record the start pos of the next sep...
        startSepPos = zzMarkedPos;
    }
}

public final void yyreset(java.io.Reader reader) {
    zzReader = reader;
    zzAtBOL = true;
    zzAtEOF = false;
    zzEOFDone = false;
    zzEndRead = zzStartRead = 0;
    zzCurrentPos = zzMarkedPos = 0;
    zzFinalHighSurrogate = 0;
    yyline = yychar = yycolumn = 0;
    zzLexicalState = YYINITIAL;
    if (zzBuffer.length > ZZ_BUFFERSIZE)
        zzBuffer = new char[ZZ_BUFFERSIZE];
    // reset fields responsible for delivering separator...
    originalBufferAsString = null;
    startSepPos = 0;
    endSepPos = 0;
}

(inside getNextToken:)

if ((zzAttributes & 1) == 1) {
    zzAction = zzState;
    zzMarkedPosL = zzCurrentPosL;
    if ((zzAttributes & 8) == 8) {
        // every occurrence of a separator char leads here...
        endSepPos = zzCurrentPosL;
        break zzForAction;
    }
}

And make a new method:

String getPrecedingSeparator() {
    String sep = null;
    if( originalBufferAsString == null ){
        sep = new String( zzBuffer, 0, endSepPos );
    }
    else if( startSepPos == -1 || endSepPos <= startSepPos ){
        sep = "";
    }
    else {
        sep = originalBufferAsString.substring( startSepPos, endSepPos );
    }
    if( zzMarkedPos < startSepPos ){
        // ... then this is a sign that the next token will be the last one... and will NOT have a trailing separator
        // so set a "flag condition" for next time this method is called
        startSepPos = -1;
    }
    return sep;
}

SeparatorDeliveringTokeniser (tweaked from source of StandardTokenizer):

Add this:

private String separator;
String getSeparator(){
    // normally this delivers a preceding separator... but after incrementToken returns false, if there is a trailing
    // separator, it then delivers that...
    return separator;
}

(inside incrementToken:)

while(true) {
  int tokenType = scanner.getNextToken();

  // added NB this gives you the separator which PRECEDES the token
  // which you are about to get from scanner.getText( ... )
  separator = scanner.getPrecedingSeparator();

  if (tokenType == SeparatorDeliveringTokeniserImpl.YYEOF) {
      // NB at this point sep is equal to the trailing separator...
    return false;
  }
  ...

Usage:

In my FilteringTokenFilter subclass, called TokenAndSeparatorExamineFilter, the methods accept and end look like this:

@Override
public boolean accept() throws IOException {
    String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
    // a preceding separator can only be an empty String if we are currently
    // dealing with the first token and if the sequence starts with a token
    if (!sep.isEmpty()) {
       // ... do something with the preceding separator
    }
    // then get the token...
    String token = getTerm();
    // ... do something with the token

    // my filter does no filtering! Every token is accepted...:
    return true;
}

@Override
public void end() throws IOException {
    // deals with trailing separator at the end of a sequence of tokens and separators (if there is one, i.e. if it doesn't end with a token)
    String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
    // NB will be an empty String if there is no trailing separator
    if (!sep.isEmpty()) {
        // ... do something with this trailing separator
    }
}


问:
Very mysterious runtime error: Bad type operand on stack
I get this very mysterious error:

java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    org/bh/tools/base/strings/TestUtils.concat(Ljava/lang/Object;Ljava/lang/CharSequence;)Ljava/lang/CharSequence; @28: invokevirtual
  Reason:
    Type 'java/lang/Object' (current frame, stack[1]) is not assignable to 'java/lang/String'
  Current Frame:
    bci: @28
    flags: { }
    locals: { 'java/lang/Object', 'java/lang/CharSequence' }
    stack: { 'java/lang/StringBuilder', 'java/lang/Object' }
  Bytecode:
    0x0000000: 2a12 59b8 0012 2b12 43b8 0012 2ac1 005b
    0x0000010: 9900 1a2a bb00 1659 b700 1a5f b600 512b
    0x0000020: b600 5eb6 0052 c000 23b0 2ac1 0016 9900
    0x0000030: 152a c000 162b b600 5e59 1260 b800 63c0
    0x0000040: 0023 b0bb 0016 59b7 001a 2ab6 0047 2bb6
    0x0000050: 005e 5912 65b8 0063 c000 23b0
  Stackmap Table:
    same_frame(@42)
    same_frame(@67)

    at org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose(NumberConversionKtTest.kt:488)
    at org.bh.tools.base.math.NumberConversionKtTest.Number_float32Value(NumberConversionKtTest.kt:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:58)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
```

At this line:
https://github.com/BlueHuskyStudios/Blue-Base/blob/ea415b702b87b7a33d90bc13221f44205c38e9f1/JVM/test/org/bh/tools/base/math/NumberConversionKtTest.kt#L488

I think it involves this function:
https://github.com/BlueHuskyStudios/Blue-Base/blob/ea415b702b87b7a33d90bc13221f44205c38e9f1/JVM/src/org/bh/tools/base/strings/String%20Utils.kt#L121-L154

but I can't possibly understand what's going wrong. It seems to indicate that I'm calling a concatenate method on an Object and a CharSequence within the TestUtils class (which I don't think is touched when I run the test that triggers this), but sounds mighty close to another function I wrote which wasn't used here.

Something's going on that I cannot get my head around. Does anyone have any ideas?

Companion JetBrains bug: KT-17210

答:
Since I don't have the bytecode to study, all of the below explaination are built on one assumption: the Kotlin has smart cast wrong once again.

tl;dr  JVM verify the whole class instead of just the proportion used.

The situation happens in the below steps:

Test ran. Junit found tests and tried to invoke org.bh.tools.base.math.NumberConversionKtTest::Number_float32Value reflection. This triggered the loading, linking and initialization of class NumberConversionKtTest. Everything is good.

This method invoked org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose, which is inside a class not yet loaded (note the trialing Kt which the previous class does not has). JVM found, loaded, linked and initialized it.

The assertNumbersClose is now being executed, i.e. a new frame is created and pushed into the stack. After executing some of bytecode, the program flow moved to line 488, and found a method invocation instruction, which asks the JVM to execute a method lying in the class org.bh.tools.base.strings.TestUtils. This class hadn't yet beening loaded, so the JVM started loading a new class.

JVM loads that class, and, during verifying, it found the method concat, not the one used in assertNumbersClose, is not good. It stops verifying with a VerifyError. Because the method differingCharacters hadn't yet been executed, i.e. no new frame was created and pushed into the stack, it's not on the stacktrace, so you see org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose on the top.

Posible workaround

You need to fix the concat method's bytecode, somehow. You have these following wrokaround.

Try upgrade kotlin compiler. I recall some smartcast related issues being fixed in the kotlin 1.1.

Since this error is kotlin compiler failing to emit a CHECKCAST for smartcasts, you may trying adding a manual cast, like this:

```<code>fun concat(lhs: Any, rhs: CharSequence): CharSequence {
    if (lhs is String) {
        val s: String = lhs as String
        return s.plus(rhs)
    } else if (lhs is StringBuilder) {
        val sb: StringBuilder= lhs as StringBuilder
        return sb.append(rhs)
    } else {
        return StringBuilder().append(lhs).append(rhs)
    }
}
</code>```

This sometimes works for some people.

If all of these don't work, Switch to plain Java and place concat in another class. This fixes most, if not all, kotlin issues.

Body:
I get this very mysterious error:

java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    org/bh/tools/base/strings/TestUtils.concat(Ljava/lang/Object;Ljava/lang/CharSequence;)Ljava/lang/CharSequence; @28: invokevirtual
  Reason:
    Type 'java/lang/Object' (current frame, stack[1]) is not assignable to 'java/lang/String'
  Current Frame:
    bci: @28
    flags: { }
    locals: { 'java/lang/Object', 'java/lang/CharSequence' }
    stack: { 'java/lang/StringBuilder', 'java/lang/Object' }
  Bytecode:
    0x0000000: 2a12 59b8 0012 2b12 43b8 0012 2ac1 005b
    0x0000010: 9900 1a2a bb00 1659 b700 1a5f b600 512b
    0x0000020: b600 5eb6 0052 c000 23b0 2ac1 0016 9900
    0x0000030: 152a c000 162b b600 5e59 1260 b800 63c0
    0x0000040: 0023 b0bb 0016 59b7 001a 2ab6 0047 2bb6
    0x0000050: 005e 5912 65b8 0063 c000 23b0
  Stackmap Table:
    same_frame(@42)
    same_frame(@67)

    at org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose(NumberConversionKtTest.kt:488)
    at org.bh.tools.base.math.NumberConversionKtTest.Number_float32Value(NumberConversionKtTest.kt:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:58)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

At this line:
https://github.com/BlueHuskyStudios/Blue-Base/blob/ea415b702b87b7a33d90bc13221f44205c38e9f1/JVM/test/org/bh/tools/base/math/NumberConversionKtTest.kt#L488

I think it involves this function:
https://github.com/BlueHuskyStudios/Blue-Base/blob/ea415b702b87b7a33d90bc13221f44205c38e9f1/JVM/src/org/bh/tools/base/strings/String%20Utils.kt#L121-L154

but I can't possibly understand what's going wrong. It seems to indicate that I'm calling a concatenate method on an Object and a CharSequence within the TestUtils class (which I don't think is touched when I run the test that triggers this), but sounds mighty close to another function I wrote which wasn't used here.

Something's going on that I cannot get my head around. Does anyone have any ideas?

Companion JetBrains bug: KT-17210

Body:
Since I don't have the bytecode to study, all of the below explaination are built on one assumption: the Kotlin has smart cast wrong once again.

tl;dr  JVM verify the whole class instead of just the proportion used.

The situation happens in the below steps:

Test ran. Junit found tests and tried to invoke org.bh.tools.base.math.NumberConversionKtTest::Number_float32Value reflection. This triggered the loading, linking and initialization of class NumberConversionKtTest. Everything is good.

This method invoked org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose, which is inside a class not yet loaded (note the trialing Kt which the previous class does not has). JVM found, loaded, linked and initialized it.

The assertNumbersClose is now being executed, i.e. a new frame is created and pushed into the stack. After executing some of bytecode, the program flow moved to line 488, and found a method invocation instruction, which asks the JVM to execute a method lying in the class org.bh.tools.base.strings.TestUtils. This class hadn't yet beening loaded, so the JVM started loading a new class.

JVM loads that class, and, during verifying, it found the method concat, not the one used in assertNumbersClose, is not good. It stops verifying with a VerifyError. Because the method differingCharacters hadn't yet been executed, i.e. no new frame was created and pushed into the stack, it's not on the stacktrace, so you see org.bh.tools.base.math.NumberConversionKtTestKt.assertNumbersClose on the top.

Posible workaround

You need to fix the concat method's bytecode, somehow. You have these following wrokaround.

Try upgrade kotlin compiler. I recall some smartcast related issues being fixed in the kotlin 1.1.

Since this error is kotlin compiler failing to emit a CHECKCAST for smartcasts, you may trying adding a manual cast, like this:

fun concat(lhs: Any, rhs: CharSequence): CharSequence {
    if (lhs is String) {
        val s: String = lhs as String
        return s.plus(rhs)
    } else if (lhs is StringBuilder) {
        val sb: StringBuilder= lhs as StringBuilder
        return sb.append(rhs)
    } else {
        return StringBuilder().append(lhs).append(rhs)
    }
}

This sometimes works for some people.

If all of these don't work, Switch to plain Java and place concat in another class. This fixes most, if not all, kotlin issues.