问:
Predefined squareroot function without using sqrt() from math.h in C
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

```<code>float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}
</code>```

答:
The square root algorithm you're (supposed to be?) using is called Newton's method.  Your if statement should be a while loop.

Replace

```<code>if (e*e > 0.001)
{
        nx = (cx +*s/cx)/2;
        return nx;
} else {
        return nx;
}
</code>```

with a while loop that iteratively does the same, but includes recalculating e.

I would give you the working code, but you said this is homework.  If you can't get it to work, post your new code and I'll be happy to help you troubleshoot.

OwnerDisplayName: Nefeli

LastEditorDisplayName: Nefeli

Body:
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}

Body:
The square root algorithm you're (supposed to be?) using is called Newton's method.  Your if statement should be a while loop.

Replace

if (e*e > 0.001)
{
        nx = (cx +*s/cx)/2;
        return nx;
} else {
        return nx;
}

with a while loop that iteratively does the same, but includes recalculating e.

I would give you the working code, but you said this is homework.  If you can't get it to work, post your new code and I'll be happy to help you troubleshoot.

OwnerDisplayName: Bill the Lizard


来源: stackexchange

问:
What is the best way in python to get a denormalized array from this ordered array?
I have this array:

```<code>>>> print raw_data
['LEVEL 1',
'SUBJECT A',
'GROUP X',
'COMMENT i',
'COMMENT ii',
'COMMENT iii',
'GROUP Y',
'COMMENT iv',
'COMMENT v',
'COMMENT vi',
'LEVEL 2',
'SUBJECT B',
'GROUP Z',
'COMMENT vii',
'COMMENT viii',
'COMMENT ix',
'SUBJECT C',
'GROUP X2',
'COMMENT x',
'COMMENT xi',
'COMMENT xii',
'COMMENT xiii',
'GROUP Y2',
'COMMENT xiv',
'COMMENT xv',
'COMMENT xvi']
</code>```

Where the obvious hierarchy is:

Level

Subject

Group

Comments

My objective is to get the array as a denormalized array to be store on a database:

```<code>>>> print result
[
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vi'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT x'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xi'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xii'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xiii],'
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xi']
]
</code>```

I was trying to solve this, but I am quite lost, I think this problem has to be usual, so I would like to know if someone has a efficient approach, this seems to be something like nested sets, but I don't know a lot of this on python, getting the level is easy, but I am getting " headaches" getting this further.

```<code>>>> def addlevel(a):
    if a.startswith('LEVEL'):
        return [1, a]
    elif a.startswith('SUBJECT'):
        return [2, a]
    elif a.startswith('GROUP'):
        return [3, a]
    elif a.startswith('COMMENT'):
        return [4, a]
>>> map(addlevel, raw_data)
[[1, 'LEVEL 1'],
 [2, 'SUBJECT A'],
 [3, 'GROUP X'],
 [4, 'COMMENT i'],
 [4, 'COMMENT ii'],
 [4, 'COMMENT iii'],
 [3, 'GROUP Y'],
 [4, 'COMMENT iv'],
 [4, 'COMMENT v'],
 [4, 'COMMENT vi'],
 [1, 'LEVEL 2'],
 [2, 'SUBJECT B'],
 [3, 'GROUP Z'],
 [4, 'COMMENT vii'],
 [4, 'COMMENT viii'],
 [4, 'COMMENT ix'],
 [2, 'SUBJECT C'],
 [3, 'GROUP X2'],
 [4, 'COMMENT x'],
 [4, 'COMMENT xi'],
 [4, 'COMMENT xii'],
 [4, 'COMMENT xiii'],
 [3, 'GROUP Y2'],
 [4, 'COMMENT xiv'],
 [4, 'COMMENT xv'],
 [4, 'COMMENT xvi']]
</code>```

I would appreciate any clues !

答:
You could try something like this:

```<code>raw_data = [ 'LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i', 'COMMENT ii',
'COMMENT iii', 'GROUP Y', 'COMMENT iv', 'COMMENT v', 'COMMENT vi', 'LEVEL 2',
'SUBJECT B', 'GROUP Z', 'COMMENT vii', 'COMMENT viii', 'COMMENT ix',
'SUBJECT C', 'GROUP X2', 'COMMENT x', 'COMMENT xi', 'COMMENT xii',
'COMMENT xiii', 'GROUP Y2', 'COMMENT xiv', 'COMMENT xv', 'COMMENT xvi' ]

level, subject, group, comment = '', '', '', ''

result = []

for item in raw_data:

    if item.startswith('COMMENT'):
        comment = item
    elif item.startswith('GROUP'):
        group = item
        comment = ''
    elif item.startswith('SUBJECT'):
        subject = item
        group = ''
    elif item.startswith('LEVEL'):
        level = item
        subject = ''

    if level and subject and group and comment:
        result.append([level, subject, group, comment])

import pprint
pprint.pprint(result)
</code>```

Which would yield:

```<code>[['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT x'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xi'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xiii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xvi']]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this array:

>>> print raw_data
['LEVEL 1',
'SUBJECT A',
'GROUP X',
'COMMENT i',
'COMMENT ii',
'COMMENT iii',
'GROUP Y',
'COMMENT iv',
'COMMENT v',
'COMMENT vi',
'LEVEL 2',
'SUBJECT B',
'GROUP Z',
'COMMENT vii',
'COMMENT viii',
'COMMENT ix',
'SUBJECT C',
'GROUP X2',
'COMMENT x',
'COMMENT xi',
'COMMENT xii',
'COMMENT xiii',
'GROUP Y2',
'COMMENT xiv',
'COMMENT xv',
'COMMENT xvi']

Where the obvious hierarchy is:

Level

Subject

Group

Comments

My objective is to get the array as a denormalized array to be store on a database:

>>> print result
[
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
    ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vi'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
    ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT x'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xi'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xii'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xiii],'
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
    ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xi']
]

I was trying to solve this, but I am quite lost, I think this problem has to be usual, so I would like to know if someone has a efficient approach, this seems to be something like nested sets, but I don't know a lot of this on python, getting the level is easy, but I am getting " headaches" getting this further.

>>> def addlevel(a):
    if a.startswith('LEVEL'):
        return [1, a]
    elif a.startswith('SUBJECT'):
        return [2, a]
    elif a.startswith('GROUP'):
        return [3, a]
    elif a.startswith('COMMENT'):
        return [4, a]
>>> map(addlevel, raw_data)
[[1, 'LEVEL 1'],
 [2, 'SUBJECT A'],
 [3, 'GROUP X'],
 [4, 'COMMENT i'],
 [4, 'COMMENT ii'],
 [4, 'COMMENT iii'],
 [3, 'GROUP Y'],
 [4, 'COMMENT iv'],
 [4, 'COMMENT v'],
 [4, 'COMMENT vi'],
 [1, 'LEVEL 2'],
 [2, 'SUBJECT B'],
 [3, 'GROUP Z'],
 [4, 'COMMENT vii'],
 [4, 'COMMENT viii'],
 [4, 'COMMENT ix'],
 [2, 'SUBJECT C'],
 [3, 'GROUP X2'],
 [4, 'COMMENT x'],
 [4, 'COMMENT xi'],
 [4, 'COMMENT xii'],
 [4, 'COMMENT xiii'],
 [3, 'GROUP Y2'],
 [4, 'COMMENT xiv'],
 [4, 'COMMENT xv'],
 [4, 'COMMENT xvi']]

I would appreciate any clues !

Body:
You could try something like this:

raw_data = [ 'LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i', 'COMMENT ii',
'COMMENT iii', 'GROUP Y', 'COMMENT iv', 'COMMENT v', 'COMMENT vi', 'LEVEL 2',
'SUBJECT B', 'GROUP Z', 'COMMENT vii', 'COMMENT viii', 'COMMENT ix',
'SUBJECT C', 'GROUP X2', 'COMMENT x', 'COMMENT xi', 'COMMENT xii',
'COMMENT xiii', 'GROUP Y2', 'COMMENT xiv', 'COMMENT xv', 'COMMENT xvi' ]

level, subject, group, comment = '', '', '', ''

result = []

for item in raw_data:

    if item.startswith('COMMENT'):
        comment = item
    elif item.startswith('GROUP'):
        group = item
        comment = ''
    elif item.startswith('SUBJECT'):
        subject = item
        group = ''
    elif item.startswith('LEVEL'):
        level = item
        subject = ''

    if level and subject and group and comment:
        result.append([level, subject, group, comment])

import pprint
pprint.pprint(result)

Which would yield:

[['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT x'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xi'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xiii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xvi']]


问:
List element pattern matching in Mathematica
The following pattern matches only the first element

```<code>{a, b, c, d, e} /. {start : ___, x_, stop : ___} :> {start, 1, stop}
</code>```

How do I make it match all of the list elements?

UPDATE:

The slightly more extended version of my goal is to have a set of three transformation rules for different elements of the list. One rule should apply to the first element, one for the last element, and another rule for every element in the middle. Here's an example:

```<code>{a, b, c, d, e} /. {most : Repeated[_], x_} ->
   {most, "Last"} /. {x_, rest : Repeated[_]} -> {"First", rest}
</code>```

These are the rules for the first and the last element. Now I need the rule for all the elements in the middle. Hence my original question.

I've probably chosen a wrong approach, because I cannot find a straightforward way to do this. Is it possible to do this with rules?

ContentLicense: CC BY-SA 3.0

Body:
The following pattern matches only the first element

{a, b, c, d, e} /. {start : ___, x_, stop : ___} :> {start, 1, stop}

How do I make it match all of the list elements?

UPDATE:

The slightly more extended version of my goal is to have a set of three transformation rules for different elements of the list. One rule should apply to the first element, one for the last element, and another rule for every element in the middle. Here's an example:

{a, b, c, d, e} /. {most : Repeated[_], x_} ->
   {most, "Last"} /. {x_, rest : Repeated[_]} -> {"First", rest}

These are the rules for the first and the last element. Now I need the rule for all the elements in the middle. Hence my original question.

I've probably chosen a wrong approach, because I cannot find a straightforward way to do this. Is it possible to do this with rules?

Body:
You may do:

list = Range[10]
list /. {first_, middle__, last_} -> {f[first], g[middle], h[last]}

Out

{f[1], g[2, 3, 4, 5, 6, 7, 8, 9], h[10]}

Or if you define:

g[x_, y__] = {g[x], g[y]} /. List -> Sequence

Then the result is

{f[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8], g[9], h[10]}


问:
ArrayIndexOufOfBoundsException
Hello I wanted to create a multiple quiz app, but when the app is at the last question, it stops suddenly. I want it to show a dialog where it counts the final score, then go back to main.

This is the error

```<code>12-07 22:38:17.997 29516-29516/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 29516
                                                                                java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
                                                                                at com.example.ancaalexandra.proiectandroidd.QuestionsBD.getQuestion(QuestionsBD.java:27)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.updateQuestion(BazeDeDate1Activity.java:150)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.access$400(BazeDeDate1Activity.java:19)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity$1.onClick(BazeDeDate1Activity.java:78)
                                                                                at android.view.View.performClick(View.java:6261)
                                                                                at android.widget.TextView.performClick(TextView.java:11185)
                                                                                at android.view.View$PerformClick.run(View.java:23752)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

This is QuestionsBD class, where i create the questions and their answers:

```<code>class QuestionsBD {

private String bdquestions[]= {
        "Componenta de date dintr-un SBD poate contine: ",
        "In arhitectura unui SBD pe niveluri, viziunea programatorului corespunde: ",
        "Arhitectura pe componente a unui sistem de  baze de date contine:"};

private String bdChoices[][]={
        {"Sistemul de operare","Sistemul de coduri","Dictionarul distribuit","Fisierele anexe"},
        {"Nivelul fizic","Nivelul SO","Nivelul logic","Nivelul SGBD"},
        {"Datele","Fisierele","Software-ul de comunicatie","Programe de comunicatie"}
};

private String bdCorrectAns[]={"Fisierele anexe", "Nivelul logic","Datele"};

public String getQuestion(int a)
{
    String question= bdquestions[a];
    return question;
}

public String getChoice0(int a)
{
    String choice0=bdChoices[a][0];
    return choice0;
}

public String getChoice1(int a)
{
    String choice1=bdChoices[a][1];
    return choice1;
}

public String getChoice2(int a)
{
    String choice2=bdChoices[a][2];
    return choice2;
}

public String getChoice3(int a)
{
    String choice3=bdChoices[a][3];
    return choice3;
}

public String getCorrectAnswer(int a)
{
    String answer=bdCorrectAns[a];
    return answer;
}

public int getNrQuestions()
{
    int nrquestions=bdquestions.length;
    return nrquestions;
    }
}
</code>```

And this is the activity where are shown the questions:

```<code>public class BazeDeDate1Activity  extends AppCompatActivity implements View.OnClickListener {

    private QuestionsBD questBd = new QuestionsBD();

    private TextView scoreTW;
    private TextView questionsTW;
    private Button choice0;
    private Button choice1;
    private Button choice2;
    private Button choice3;
    private Button choiceQuit;
    private ImageView numberPhoto;

    private String answer;
    private int scoreInit = 0;
    private int questionNumber = 0;
    private String quit = "quit";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baze_de_date1);

        View v = findViewById(R.id.buttonBD1quit);
        v.setOnClickListener(this);

        /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Scor final: " + scoreInit);
        builder.setTitle("Felicitari!!");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int idok) {

            }
        });

        AlertDialog dialog = builder.create();
*/
        scoreTW = (TextView) findViewById(R.id.textViewScorObtinut);
        questionsTW = (TextView) findViewById(R.id.textViewIntrebare1BD);
        choice0 = (Button) findViewById(R.id.buttonBD1r1);
        choice1 = (Button) findViewById(R.id.buttonBD1r2);
        choice2 = (Button) findViewById(R.id.buttonBD1r3);
        choice3 = (Button) findViewById(R.id.buttonBD1r4);
        choiceQuit = (Button) findViewById(R.id.buttonBD1quit);
        numberPhoto = (ImageView) findViewById(R.id.imageViewONE);

        //updateQuestion();

        choice0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice0.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                    updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                        updateQuestion();

                }
            }
        });

        choice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice1.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();
                        updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();
                    updateQuestion();
                }

            }
        });

        choice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice2.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

        choice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice3.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

    }

    private void updateQuestion()
    {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }

    private void updateScore(int point)
    {
        scoreTW.setText(""+scoreInit);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.buttonBD1quit)
        {
            Intent intent=new Intent(this,BeginActivity.class);
            this.startActivity(intent);
        }
    }
}
</code>```

答:
When you finish the last question, the code still runs trying to update to a 4th question, or index 3 in the bdquestions[] array.  You need to add a check to make sure it stops after the last question, something like this:</p>

```<code>private void updateQuestion()
{
    if (questionNumber < questBd.getNrQuestions()) {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }
}
</code>```

Title: ArrayIndexOufOfBoundsException

Body:
Hello I wanted to create a multiple quiz app, but when the app is at the last question, it stops suddenly. I want it to show a dialog where it counts the final score, then go back to main.

This is the error

12-07 22:38:17.997 29516-29516/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 29516
                                                                                java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
                                                                                at com.example.ancaalexandra.proiectandroidd.QuestionsBD.getQuestion(QuestionsBD.java:27)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.updateQuestion(BazeDeDate1Activity.java:150)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.access$400(BazeDeDate1Activity.java:19)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity$1.onClick(BazeDeDate1Activity.java:78)
                                                                                at android.view.View.performClick(View.java:6261)
                                                                                at android.widget.TextView.performClick(TextView.java:11185)
                                                                                at android.view.View$PerformClick.run(View.java:23752)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

This is QuestionsBD class, where i create the questions and their answers:

class QuestionsBD {

private String bdquestions[]= {
        "Componenta de date dintr-un SBD poate contine: ",
        "In arhitectura unui SBD pe niveluri, viziunea programatorului corespunde: ",
        "Arhitectura pe componente a unui sistem de  baze de date contine:"};

private String bdChoices[][]={
        {"Sistemul de operare","Sistemul de coduri","Dictionarul distribuit","Fisierele anexe"},
        {"Nivelul fizic","Nivelul SO","Nivelul logic","Nivelul SGBD"},
        {"Datele","Fisierele","Software-ul de comunicatie","Programe de comunicatie"}
};

private String bdCorrectAns[]={"Fisierele anexe", "Nivelul logic","Datele"};

public String getQuestion(int a)
{
    String question= bdquestions[a];
    return question;
}

public String getChoice0(int a)
{
    String choice0=bdChoices[a][0];
    return choice0;
}

public String getChoice1(int a)
{
    String choice1=bdChoices[a][1];
    return choice1;
}

public String getChoice2(int a)
{
    String choice2=bdChoices[a][2];
    return choice2;
}

public String getChoice3(int a)
{
    String choice3=bdChoices[a][3];
    return choice3;
}

public String getCorrectAnswer(int a)
{
    String answer=bdCorrectAns[a];
    return answer;
}

public int getNrQuestions()
{
    int nrquestions=bdquestions.length;
    return nrquestions;
    }
}

And this is the activity where are shown the questions:

public class BazeDeDate1Activity  extends AppCompatActivity implements View.OnClickListener {

    private QuestionsBD questBd = new QuestionsBD();

    private TextView scoreTW;
    private TextView questionsTW;
    private Button choice0;
    private Button choice1;
    private Button choice2;
    private Button choice3;
    private Button choiceQuit;
    private ImageView numberPhoto;

    private String answer;
    private int scoreInit = 0;
    private int questionNumber = 0;
    private String quit = "quit";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baze_de_date1);

        View v = findViewById(R.id.buttonBD1quit);
        v.setOnClickListener(this);

        /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Scor final: " + scoreInit);
        builder.setTitle("Felicitari!!");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int idok) {

            }
        });

        AlertDialog dialog = builder.create();
*/
        scoreTW = (TextView) findViewById(R.id.textViewScorObtinut);
        questionsTW = (TextView) findViewById(R.id.textViewIntrebare1BD);
        choice0 = (Button) findViewById(R.id.buttonBD1r1);
        choice1 = (Button) findViewById(R.id.buttonBD1r2);
        choice2 = (Button) findViewById(R.id.buttonBD1r3);
        choice3 = (Button) findViewById(R.id.buttonBD1r4);
        choiceQuit = (Button) findViewById(R.id.buttonBD1quit);
        numberPhoto = (ImageView) findViewById(R.id.imageViewONE);

        //updateQuestion();

        choice0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice0.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                    updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                        updateQuestion();

                }
            }
        });

        choice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice1.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();
                        updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();
                    updateQuestion();
                }

            }
        });

        choice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice2.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

        choice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice3.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

    }

    private void updateQuestion()
    {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }

    private void updateScore(int point)
    {
        scoreTW.setText(""+scoreInit);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.buttonBD1quit)
        {
            Intent intent=new Intent(this,BeginActivity.class);
            this.startActivity(intent);
        }
    }
}

Body:
When you finish the last question, the code still runs trying to update to a 4th question, or index 3 in the bdquestions[] array.  You need to add a check to make sure it stops after the last question, something like this:

private void updateQuestion()
{
    if (questionNumber < questBd.getNrQuestions()) {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }
}


问:
Save and load all h2o cross-validation models in R

I am trying to find an easy way to save all the cross validation models produced by h2o using R.

Running a any kind of model with nfolds = 5 I can see each CV model listed in the web-interface (localhose:54321) looking something like this:

```<code>model_id
model_id_cv_1
model_id_cv_2
model_id_cv_3
model_id_cv_4
model_id_cv_5
</code>```

I've used this to save it:
    h2o.saveModel(model_id, path="mypath") gives a

But h2o.saveModel(model_id_cv_1, path="mypath")
But when I reload it I loose all the cross validated models.

It does seem possible to save each CV model as  POJO via the webinterface, but I'd rather be able to do this programatically in R.  It seems that there used to be a 'save_cv' option in earlier versions of h2o.saveModel(), but this seems to have been removed.

Is this possible?

答:
When you save a model by main model ID which has CV configuration,  the saved model does have all the cross validated models into it. If you save individual cross validated models on disk then they will all be considered as individual models and you will not see them all together.

Here is an example:

Lets build GBM model with 5 folds:

```<code>prostate_df  = h2o.importFile("https://raw.githubusercontent.com/Avkash/mldl/master/data/prostate.csv")
response = "CAPSULE"
features = setdiff(h2o.colnames(prostate_df), response)
prostate_gbm_cv5_model = h2o.gbm(x = features, y = response, training_frame = prostate_df, nfolds = 5)
</code>```

You can get all the models from this object:

```<code>h2o.cross_validation_models(prostate_gbm_cv5_model)
</code>```

You can access individual CV models as below:

```<code>h2o.cross_validation_models(prostate_gbm_cv5_model][[1]]
h2o.cross_validation_models(prostate_gbm_cv5_model)[[1]]@model_id
</code>```

You will get total cross fold models count here:

```<code>length(h2o.cross_validation_models(prostate_gbm_cv5_model))
</code>```

Lets save model to disk:

```<code>h2o.saveModel(object = prostate_gbm_cv5_model, path = "/Users/avkashchauhan/Downloads")
</code>```

Lets load model from the disk:

```<code>model_from_disk = h2o.loadModel("/Users/avkashchauhan/Downloads/GBM_model_R_1512067532473_2966")
</code>```

You will get all the CV models here:

```<code>h2o.cross_validation_models(model_from_disk)
</code>```

Get CV models count:

```<code>length(h2o.cross_validation_models(model_from_disk))
</code>```

Access CV model individually:

```<code>h2o.cross_validation_models(model_from_disk)[[1]]
h2o.cross_validation_models(model_from_disk)[[1]]@model_id
</code>```

Body:
I am trying to find an easy way to save all the cross validation models produced by h2o using R.

Running a any kind of model with nfolds = 5 I can see each CV model listed in the web-interface (localhose:54321) looking something like this:

model_id
model_id_cv_1
model_id_cv_2
model_id_cv_3
model_id_cv_4
model_id_cv_5

I've used this to save it:
    h2o.saveModel(model_id, path="mypath") gives a

But h2o.saveModel(model_id_cv_1, path="mypath")
But when I reload it I loose all the cross validated models.

It does seem possible to save each CV model as  POJO via the webinterface, but I'd rather be able to do this programatically in R.  It seems that there used to be a 'save_cv' option in earlier versions of h2o.saveModel(), but this seems to have been removed.

Is this possible?

Body:
When you save a model by main model ID which has CV configuration,  the saved model does have all the cross validated models into it. If you save individual cross validated models on disk then they will all be considered as individual models and you will not see them all together.

Here is an example:

Lets build GBM model with 5 folds:

prostate_df  = h2o.importFile("https://raw.githubusercontent.com/Avkash/mldl/master/data/prostate.csv")
response = "CAPSULE"
features = setdiff(h2o.colnames(prostate_df), response)
prostate_gbm_cv5_model = h2o.gbm(x = features, y = response, training_frame = prostate_df, nfolds = 5)

You can get all the models from this object:

h2o.cross_validation_models(prostate_gbm_cv5_model)

You can access individual CV models as below:

h2o.cross_validation_models(prostate_gbm_cv5_model][[1]]
h2o.cross_validation_models(prostate_gbm_cv5_model)[[1]]@model_id

You will get total cross fold models count here:

length(h2o.cross_validation_models(prostate_gbm_cv5_model))

Lets save model to disk:

h2o.saveModel(object = prostate_gbm_cv5_model, path = "/Users/avkashchauhan/Downloads")

Lets load model from the disk:

model_from_disk = h2o.loadModel("/Users/avkashchauhan/Downloads/GBM_model_R_1512067532473_2966")

You will get all the CV models here:

h2o.cross_validation_models(model_from_disk)

Get CV models count:

length(h2o.cross_validation_models(model_from_disk))

Access CV model individually:

h2o.cross_validation_models(model_from_disk)[[1]]
h2o.cross_validation_models(model_from_disk)[[1]]@model_id


问:
Creating barchart ggplot2 single dim dataframe
I'm trying to create a barchart in ggplot2, I have a dataframe that has column names and associated numeric values, but I keep running into unexpected errors creating the dataframe:

```<code>ggplot(audit_count,aes(x=colnames(audit_count),y=audit_count[1,])) +geom_bar()
</code>```

gives me error message

```<code>Error: Aesthetics must be either length 1 or the same as the data (1): x, y
</code>```

But this error message doesnt make sense to me, as colnames(audit_count) and audit_count[1,] are the same length.

Is there some kind of transform I need to do to my data to get it to plot as barchart with the column names as bar names, and the numeric values as y values?

Data below:

```<code>structure(list(page_title_missing = 56L, page_title_length = 164L,
    page_title_duplicates = 630L, meta_desc_missing = 703L, meta_desc_length = 0L,
    meta_desc_duplicate = 28L, url_dynamic = 397L, url_underscore = 26L,
    url_uppercase = 701L, pagination = 0L, image_alt_missing = 223L,
    h1_missing = 56L, h1_multiple = 427L, meta_keyword_present = 0L,
    https_missing = 0L, non_canonical = 293L, meta_no_index = 0L,
    meta_no_follow = 0L, content_duplication = 617L, content_depth = 461L,
    non_301_redirects = 55L, redirec_chains = 56L, errors_404 = 0L,
    mobile_url_inconsisten = 0L, hreflang_missing = 731L), .Names = c("page_title_missing",
"page_title_length", "page_title_duplicates", "meta_desc_missing",
"meta_desc_length", "meta_desc_duplicate", "url_dynamic", "url_underscore",
"url_uppercase", "pagination", "image_alt_missing", "h1_missing",
"h1_multiple", "meta_keyword_present", "https_missing", "non_canonical",
"meta_no_index", "meta_no_follow", "content_duplication", "content_depth",
"non_301_redirects", "redirec_chains", "errors_404", "mobile_url_inconsisten",
"hreflang_missing"), row.names = c(NA, -1L), class = "data.frame")
</code>```

答:
ggplot expects data to be in a tidy format and aes() should map columns of a data.frame to a graphic property. You aren't really meant to pass the data directly to an aes. One quick fix is

```<code>ggplot(tidyr::gather(audit_count, variable, value)) +
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip()
</code>```

or

```<code>ggplot(reshape2::melt(audit_count)) +
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip()
</code>```

Body:
I'm trying to create a barchart in ggplot2, I have a dataframe that has column names and associated numeric values, but I keep running into unexpected errors creating the dataframe:

ggplot(audit_count,aes(x=colnames(audit_count),y=audit_count[1,])) +geom_bar()

gives me error message

Error: Aesthetics must be either length 1 or the same as the data (1): x, y

But this error message doesnt make sense to me, as colnames(audit_count) and audit_count[1,] are the same length.

Is there some kind of transform I need to do to my data to get it to plot as barchart with the column names as bar names, and the numeric values as y values?

Data below:

structure(list(page_title_missing = 56L, page_title_length = 164L,
    page_title_duplicates = 630L, meta_desc_missing = 703L, meta_desc_length = 0L,
    meta_desc_duplicate = 28L, url_dynamic = 397L, url_underscore = 26L,
    url_uppercase = 701L, pagination = 0L, image_alt_missing = 223L,
    h1_missing = 56L, h1_multiple = 427L, meta_keyword_present = 0L,
    https_missing = 0L, non_canonical = 293L, meta_no_index = 0L,
    meta_no_follow = 0L, content_duplication = 617L, content_depth = 461L,
    non_301_redirects = 55L, redirec_chains = 56L, errors_404 = 0L,
    mobile_url_inconsisten = 0L, hreflang_missing = 731L), .Names = c("page_title_missing",
"page_title_length", "page_title_duplicates", "meta_desc_missing",
"meta_desc_length", "meta_desc_duplicate", "url_dynamic", "url_underscore",
"url_uppercase", "pagination", "image_alt_missing", "h1_missing",
"h1_multiple", "meta_keyword_present", "https_missing", "non_canonical",
"meta_no_index", "meta_no_follow", "content_duplication", "content_depth",
"non_301_redirects", "redirec_chains", "errors_404", "mobile_url_inconsisten",
"hreflang_missing"), row.names = c(NA, -1L), class = "data.frame")

Body:
ggplot expects data to be in a tidy format and aes() should map columns of a data.frame to a graphic property. You aren't really meant to pass the data directly to an aes. One quick fix is

ggplot(tidyr::gather(audit_count, variable, value)) +
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip()

or

ggplot(reshape2::melt(audit_count)) +
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip()


问:
Difference between dot and greater-than sign in Elasticsearch
What is the difference between key.other_key and key>other_key in Elasticsearch? I've come across it in this page in docs and can't find a further explanation of why it's needed and how it's different from a dot.

答:
These symbols are used together when a buckets_path syntax is used:

```<code>AGG_SEPARATOR       =  '>' ;
METRIC_SEPARATOR    =  '.' ;
AGG_NAME            =  <the name of the aggregation> ;
METRIC              =  <the name of the metric (in case of multi-value metrics aggregation)> ;
PATH                =  <AGG_NAME> [ <AGG_SEPARATOR>, <AGG_NAME> ]* [ <METRIC_SEPARATOR>, <METRIC> ] ;
</code>```

You need this when using pipeline aggregations or when sorting buckets of terms aggregation.

The difference in semantics is best shown with the example from the page you referenced in the question:

```<code>GET /_search
{
    "aggs" : {
        "countries" : {
            "terms" : {
                "field" : "artist.country",
                "order" : { "rock>playback_stats.avg" : "desc" }
            },
            "aggs" : {
                "rock" : {
                    "filter" : { "term" : { "genre" :  "rock" }},
                    "aggs" : {
                        "playback_stats" : { "stats" : { "field" : "play_count" }}
                    }
                }
            }
        }
    }
}
</code>```

The above will sort the artist’s countries buckets based on the average play count among the rock songs.

Here > symbol is used to separate different levels of the aggregations (playback_stats is a sub-aggregation of rock), and the dot indicates which metric of the aggregation to use for sorting, in this case avg.

Hope that helps!

Body:
These symbols are used together when a buckets_path syntax is used:

AGG_SEPARATOR       =  '>' ;
METRIC_SEPARATOR    =  '.' ;
AGG_NAME            =  <the name of the aggregation> ;
METRIC              =  <the name of the metric (in case of multi-value metrics aggregation)> ;
PATH                =  <AGG_NAME> [ <AGG_SEPARATOR>, <AGG_NAME> ]* [ <METRIC_SEPARATOR>, <METRIC> ] ;

You need this when using pipeline aggregations or when sorting buckets of terms aggregation.

The difference in semantics is best shown with the example from the page you referenced in the question:

GET /_search
{
    "aggs" : {
        "countries" : {
            "terms" : {
                "field" : "artist.country",
                "order" : { "rock>playback_stats.avg" : "desc" }
            },
            "aggs" : {
                "rock" : {
                    "filter" : { "term" : { "genre" :  "rock" }},
                    "aggs" : {
                        "playback_stats" : { "stats" : { "field" : "play_count" }}
                    }
                }
            }
        }
    }
}

The above will sort the artist’s countries buckets based on the average play count among the rock songs.

Here > symbol is used to separate different levels of the aggregations (playback_stats is a sub-aggregation of rock), and the dot indicates which metric of the aggregation to use for sorting, in this case avg.

Hope that helps!


问:
String.Format like functionality in T-SQL?
I'm looking for a built-in function/extended function in T-SQL for string manipulation similar to the String.Format method in .NET.

答: At the moment this doesn't really exist (although you can of course write your own).  There is an open connect bug for it: https://connect.microsoft.com/SQLServer/Feedback/Details/3130221, which as of this writing has just 1 vote.  </p>

OwnerDisplayName: unknown (yahoo)

LastEditorDisplayName: Joel Coehoorn


问:
How do you copy properties of an object into another without adding properties using Javascript or jQuery?
I want to copy the right object into the left object without copy properties that are in the right object into the left. In the end, I only want the properties that exist in the left object. I can use JavaScript and jQuery

```<code>var left = { "id": "123" };
var right = { "id": "456", "no": "false" };

$.each(left, function (l1_key, l1Value) {
  if (typeof l1Value === 'object') {
    const left_l2 = left[l1_key];
    const right_l1_properties = right[l1_key];
    $.each(left_l2, function (l2_key, l2Value) {
      l2Value = right_l1_properties[l2_key];
    });
  }
});
</code>```

left need to be:

```<code>{ "id": "456" };
</code>```

答:
Simply iterate over all properties in the left object, check if that key exists in the right object, and set the left keyed value to the right keyed value.

var left = { "id": "123" }; var right = { "id": "456", "no": "false" };

for (var prop in left){
  if(prop in right) {
    left[prop] = right[prop];
  }
};

console.log(left);```

No jQuery needed.

EDIT: rather than using if(right[prop]), it does make more sense to be a little more object-happy and use either hasOwnProperty or in to check for the existence of the matching property in right. I've updated the code to use in. A discussion on in vs hasOwnProperty.

Body:
I want to copy the right object into the left object without copy properties that are in the right object into the left. In the end, I only want the properties that exist in the left object. I can use JavaScript and jQuery

var left = { "id": "123" };
var right = { "id": "456", "no": "false" };

$.each(left, function (l1_key, l1Value) {
  if (typeof l1Value === 'object') {
    const left_l2 = left[l1_key];
    const right_l1_properties = right[l1_key];
    $.each(left_l2, function (l2_key, l2Value) {
      l2Value = right_l1_properties[l2_key];
    });
  }
});

left need to be:

{ "id": "456" };

Body:
Simply iterate over all properties in the left object, check if that key exists in the right object, and set the left keyed value to the right keyed value.

var left = { "id": "123" }; var right = { "id": "456", "no": "false" };

for (var prop in left){
  if(prop in right) {
    left[prop] = right[prop];
  }
};

console.log(left);

No jQuery needed.

EDIT: rather than using if(right[prop]), it does make more sense to be a little more object-happy and use either hasOwnProperty or in to check for the existence of the matching property in right. I've updated the code to use in. A discussion on in vs hasOwnProperty.


问:
Deleting elements from list depending on randomly generated number
This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list.  It should return a new list with the remaining viruses. Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining.

It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions.

```<code>def kill(viruses, mortalityProb):
    for i in viruses:
        if random.randint(0, 100) < (mortalityProb * 100):
            del i
    return viruses
</code>```

This does not quite work, but I can't get a grasp on why.

答:
Because in the for loop "i' is not actually the element in the list. You have to actually change the viruses list. Something like this may work. </p>

```<code>def kill(viruses, mortalityProb):
    for x,i in enumerate(viruses):
        if random.randint(0, 100) < (mortalityProb * 100):
            viruses.pop(x)
    return viruses
</code>```

Body:
This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list.  It should return a new list with the remaining viruses. Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining.

It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions.

def kill(viruses, mortalityProb):
    for i in viruses:
        if random.randint(0, 100) < (mortalityProb * 100):
            del i
    return viruses

This does not quite work, but I can't get a grasp on why.

Body:
Because in the for loop "i' is not actually the element in the list. You have to actually change the viruses list. Something like this may work.

def kill(viruses, mortalityProb):
    for x,i in enumerate(viruses):
        if random.randint(0, 100) < (mortalityProb * 100):
            viruses.pop(x)
    return viruses


问:
Need to remove the delItem from the toDos array not sure how
I can't figure out how to complete this function. I have filtered through to find the variable that matches the id but now I need to match that item to the delItem var and delete it.    </p>

```<code>function deleteToDo(tot) {
        let delItem = toDos.filter((remove) => remove.id === tot);
     /// i need to remove item from toDos array that matches delItem.
        renderTheUI(toDos);
    }
</code>```

答:
Array#filter returns an array, with all items that match the predicate. Instead of getting the item that you want to remove, get an array without the item by checking that the id is not equal to tot. Then use the filtered array in renderTheUI:

```<code>function deleteToDo(tot) {
  const filteredToDos = toDos.filter((item) => item.id !== tot);
  renderTheUI(filteredToDos);
}
</code>```

I would suggest moving the call to renderTheUI out of the deleteToDo method, since it might be very confusing. The deleteToDo will return an updated array, and then you can render the new array:

```<code>function deleteToDo(tot) {
  return toDos.filter((item) => item.id !== tot);
}

const filteredToDos = deleteToDo(2);

renderTheUI(filteredToDos);
</code>```

Body:
I can't figure out how to complete this function. I have filtered through to find the variable that matches the id but now I need to match that item to the delItem var and delete it.

function deleteToDo(tot) {
        let delItem = toDos.filter((remove) => remove.id === tot);
     /// i need to remove item from toDos array that matches delItem.
        renderTheUI(toDos);
    }

Body:
Array#filter returns an array, with all items that match the predicate. Instead of getting the item that you want to remove, get an array without the item by checking that the id is not equal to tot. Then use the filtered array in renderTheUI:

function deleteToDo(tot) {
  const filteredToDos = toDos.filter((item) => item.id !== tot);
  renderTheUI(filteredToDos);
}

I would suggest moving the call to renderTheUI out of the deleteToDo method, since it might be very confusing. The deleteToDo will return an updated array, and then you can render the new array:

function deleteToDo(tot) {
  return toDos.filter((item) => item.id !== tot);
}

const filteredToDos = deleteToDo(2);

renderTheUI(filteredToDos);


问:
hide lines of text not fully visible with javascript & css
I think this might be impossible, but is there some way using JQuery to prevent lines of text not fully visible from showing up on the screen when a user scrolls until the entire line is visible? That is, we want to prevent something like this from showing up:

Thanks!

答:
I agree with @rahmanisback, don´t mess with the user's browsing experience.

However, what would perhaps be a nice "inbetween" solution, is using a transparency gradient so that the bottom pixels fade out. But that would apply also to "whole" lines, so perhaps that´s not a good solution for your problem.


问:
Kubernetes pod arguments are not displayed in Service under Args: without error

I created a singlePod.yaml file to properly describe the kubernetes pod service that passes arguments, and can run like this:
kubectl create -f ./singlePod.yaml

I want the arguments called to match Docker:

```<code>docker run -it -p 8080:8080 joethecoder2/spring-boot-web cassandra_ip=127.0.0.1 cassandra_port=9042

apiVersion: v1
kind: Pod
metadata:
  name: spring-boot-web-demo
  labels:
    purpose: demonstrate-spring-boot-web
spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    env:
    - name: "cassandra_ip"
      value: "127.0.0.1"
    - name: "cassandra_port"
      value: "9042"
    command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar", "cassandra_ip=127.0.0.1", "cassandra_port=9042"]
    args: ["$(cassandra_ip)", "$(cassandra_port)"]
  restartPolicy: OnFailure
<!-- Paste the part of the code that shows the problem. (Please indent 4 spaces.) -->
</code>```

The problem is that although the arguments have been added to the below service, the arguments do not take effect to the calling program (spring-boot-web-0.0.1-SNAPSHOT.jar)

```<code>Name:       spring-boot-web-demo
Namespace:  default
Node:       minikube/192.168.64.3
Start Time: Thu, 07 Dec 2017 12:08:10 -0500
Labels:     purpose=demonstrate-spring-boot-web
Annotations:    <none>
Status:     Running
IP:     172.17.0.2
Controllers:    <none>
Containers:
  spring-boot-web:
    Container ID:   docker://1c9543e412b50b36182528d690121014dfe7c9dd6409ce689d1a08fbad7c2436
    Image:      docker.io/joethecoder2/spring-boot-web
    Image ID:       docker-pullable://joethecoder2/spring-boot-web@sha256:ebf94365075e0ee16a50cab41d8e1307785a93c60be600f94bb82a4dbefb6bc0
    Port:
    Command:
      java
      -jar
      spring-boot-web-0.0.1-SNAPSHOT.jar
      cassandra_ip=127.0.0.1
      cassandra_port=9042
    Args:
      $(cassandra_ip)
      $(cassandra_port)
    State:      Running
      Started:      Thu, 07 Dec 2017 12:08:11 -0500
    Ready:      True
    Restart Count:  0
    Environment:
      cassandra_ip: 127.0.0.1
      cassandra_port:   9042
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-wgdn6 (ro)
Conditions:
  Type      Status
  Initialized   True
  Ready     True
  PodScheduled  True
Volumes:
  default-token-wgdn6:
    Type:   Secret (a volume populated by a Secret)
    SecretName: default-token-wgdn6
    Optional:   false
QoS Class:  BestEffort
Node-Selectors: <none>
Tolerations:    <none>
Events:
  FirstSeen LastSeen    Count   From            SubObjectPath               Type        Reason          Message
  --------- --------    -----   ----            -------------               --------    ------          -------
  8m        8m      1   default-scheduler                       Normal      Scheduled       Successfully assigned spring-boot-web-demo to minikube
  8m        8m      1   kubelet, minikube                       Normal      SuccessfulMountVolume   MountVolume.SetUp succeeded for volume "default-token-wgdn6"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Pulling         pulling image "docker.io/joethecoder2/spring-boot-web"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Pulled          Successfully pulled image "docker.io/joethecoder2/spring-boot-web"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Created         Created container
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Started         Started container
</code>```

I am expecting the results from the calling java program:
to use the cassandra_ip and cassandra_port

The service, does not properly show the arguments being displayed by the service, and also the running java program inside docker, does not show that the arguments are called.

```<code>Command:
      java
      -jar
      spring-boot-web-0.0.1-SNAPSHOT.jar
      cassandra_ip=127.0.0.1
      cassandra_port=9042
    Args:
      $(cassandra_ip)
      $(cassandra_port)
</code>```

答:
change it like this. it will work.</p>

```<code>spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    env:
    - name: "cassandra_ip"
      value: "127.0.0.1"
    - name: "cassandra_port"
      value: "9042"
    command: ["/bin/sh","-c", "java -jar spring-boot-web-0.0.1-SNAPSHOT.jar cassandra_ip=$cassandra_ip", "cassandra_port=$cassandra_port]
  restartPolicy: OnFailure
</code>```

Body:
I created a singlePod.yaml file to properly describe the kubernetes pod service that passes arguments, and can run like this:
kubectl create -f ./singlePod.yaml

I want the arguments called to match Docker:

docker run -it -p 8080:8080 joethecoder2/spring-boot-web cassandra_ip=127.0.0.1 cassandra_port=9042

apiVersion: v1
kind: Pod
metadata:
  name: spring-boot-web-demo
  labels:
    purpose: demonstrate-spring-boot-web
spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    env:
    - name: "cassandra_ip"
      value: "127.0.0.1"
    - name: "cassandra_port"
      value: "9042"
    command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar", "cassandra_ip=127.0.0.1", "cassandra_port=9042"]
    args: ["$(cassandra_ip)", "$(cassandra_port)"]
  restartPolicy: OnFailure

The problem is that although the arguments have been added to the below service, the arguments do not take effect to the calling program (spring-boot-web-0.0.1-SNAPSHOT.jar)

Name:       spring-boot-web-demo
Namespace:  default
Node:       minikube/192.168.64.3
Start Time: Thu, 07 Dec 2017 12:08:10 -0500
Labels:     purpose=demonstrate-spring-boot-web
Annotations:    <none>
Status:     Running
IP:     172.17.0.2
Controllers:    <none>
Containers:
  spring-boot-web:
    Container ID:   docker://1c9543e412b50b36182528d690121014dfe7c9dd6409ce689d1a08fbad7c2436
    Image:      docker.io/joethecoder2/spring-boot-web
    Image ID:       docker-pullable://joethecoder2/spring-boot-web@sha256:ebf94365075e0ee16a50cab41d8e1307785a93c60be600f94bb82a4dbefb6bc0
    Port:
    Command:
      java
      -jar
      spring-boot-web-0.0.1-SNAPSHOT.jar
      cassandra_ip=127.0.0.1
      cassandra_port=9042
    Args:
      $(cassandra_ip)
      $(cassandra_port)
    State:      Running
      Started:      Thu, 07 Dec 2017 12:08:11 -0500
    Ready:      True
    Restart Count:  0
    Environment:
      cassandra_ip: 127.0.0.1
      cassandra_port:   9042
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-wgdn6 (ro)
Conditions:
  Type      Status
  Initialized   True
  Ready     True
  PodScheduled  True
Volumes:
  default-token-wgdn6:
    Type:   Secret (a volume populated by a Secret)
    SecretName: default-token-wgdn6
    Optional:   false
QoS Class:  BestEffort
Node-Selectors: <none>
Tolerations:    <none>
Events:
  FirstSeen LastSeen    Count   From            SubObjectPath               Type        Reason          Message
  --------- --------    -----   ----            -------------               --------    ------          -------
  8m        8m      1   default-scheduler                       Normal      Scheduled       Successfully assigned spring-boot-web-demo to minikube
  8m        8m      1   kubelet, minikube                       Normal      SuccessfulMountVolume   MountVolume.SetUp succeeded for volume "default-token-wgdn6"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Pulling         pulling image "docker.io/joethecoder2/spring-boot-web"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Pulled          Successfully pulled image "docker.io/joethecoder2/spring-boot-web"
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Created         Created container
  8m        8m      1   kubelet, minikube   spec.containers{spring-boot-web}    Normal      Started         Started container

I am expecting the results from the calling java program:
to use the cassandra_ip and cassandra_port

The service, does not properly show the arguments being displayed by the service, and also the running java program inside docker, does not show that the arguments are called.

Command:
      java
      -jar
      spring-boot-web-0.0.1-SNAPSHOT.jar
      cassandra_ip=127.0.0.1
      cassandra_port=9042
    Args:
      $(cassandra_ip)
      $(cassandra_port)

Body:
change it like this. it will work.

spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    env:
    - name: "cassandra_ip"
      value: "127.0.0.1"
    - name: "cassandra_port"
      value: "9042"
    command: ["/bin/sh","-c", "java -jar spring-boot-web-0.0.1-SNAPSHOT.jar cassandra_ip=$cassandra_ip", "cassandra_port=$cassandra_port]
  restartPolicy: OnFailure


答:
You do not need to find the element with filter but its index in the array.

```<code>function deleteToDo(tot) {
    let delIndex = toDos.findIndex((remove) => remove.id === tot);

    if (delIndex !== -1){ // if element was found
        toDos.splice(delIndex,1); // remove the element from the toDos array
    }

    renderTheUI(toDos);
}
</code>```

Title: Need to remove the delItem from the toDos array not sure how

Body:
You do not need to find the element with filter but its index in the array.

function deleteToDo(tot) {
    let delIndex = toDos.findIndex((remove) => remove.id === tot);

    if (delIndex !== -1){ // if element was found
        toDos.splice(delIndex,1); // remove the element from the toDos array
    }

    renderTheUI(toDos);
}


问:
clickable div javascript programming
I have 5 divs and I want each of them to be clickable and change the background and content in the div "new"

  <button id="btn">Przeczytaj Artykułt</button>

⟩

⟨

```

答:
First, you appear to have one .card element that doesn't go with the others. I'm assuming you want to only update .new when any of the other five .card elements are clicked, so for the purposes of my example, I've removed that element. You can always use .dol > card as a selector if need be :)

Assuming you want to change the background of .new when you click on any element with the class card, what you'll want to do is first collect all of the elements with the class card, which can be done with document.getElementsByClassName('card').

You'll also need to define the target .new element, with document.getElementsByClassName('new')[0]. Note the [0] at the end of the selector, which indicates that we want the first result. This is important because document.getElementsByClassName() returns a NodeList collection of elements, and even if there is only one result, we need to explicitly state that we want to use that one.

Now that you have both the cards and the target defined, you'll want to loop over each of the card elements, attaching an onclick event handler to each one. The for loop would be for (var i = 0; i < cards.length; i++), and the handler would be added with cards[i].onclick = function() { }.

For each of the card elements, you want to modify the style.background of to change the background colour, and the .innerHTML to change the content.

The brackets and the i at the end of the function are an immediately-invoked function expression (IIFE), which gets run as soon as the page is loaded. This is needed to attach the event handlers.

This can be seen in the following:

var cards = document.getElementsByClassName('card');
var newElement = document.getElementsByClassName('new')[0];
for (var i = 0; i < cards.length; i++)(function(i) {
  cards[i].onclick = function() {
    newElement.style.background = 'red';
    newElement.innerHTML = 'modified';
  }
})(i);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="new"><b></b>
  <button id="btn">Przeczytaj Artykułt</button>
  <div id="next">⟩</div>
  <div id="prev">⟨</div>
  <div id="slider"></div>
</div>
<div class="dol">
  <div class="card" id="pierwsz"><img src="slajdy/slajd1.png"></div>
  <div class="card" id="drugi"><img src="slajdy/slajd2.png"></div>
  <div class="card" id="trzeci"><img src="slajdy/slajd3.png"></div>
  <div class="card" id="czwarty"><img src="slajdy/slajd4.png"></div>
  <div class="card" id="piaty"><img src="slajdy/slajd5.png"></div>
</div></code>```

Hope this helps! :)

Title: clickable div javascript programming

Body:
First, you appear to have one .card element that doesn't go with the others. I'm assuming you want to only update .new when any of the other five .card elements are clicked, so for the purposes of my example, I've removed that element. You can always use .dol > card as a selector if need be :)

Assuming you want to change the background of .new when you click on any element with the class card, what you'll want to do is first collect all of the elements with the class card, which can be done with document.getElementsByClassName('card').

You'll also need to define the target .new element, with document.getElementsByClassName('new')[0]. Note the [0] at the end of the selector, which indicates that we want the first result. This is important because document.getElementsByClassName() returns a NodeList collection of elements, and even if there is only one result, we need to explicitly state that we want to use that one.

Now that you have both the cards and the target defined, you'll want to loop over each of the card elements, attaching an onclick event handler to each one. The for loop would be for (var i = 0; i < cards.length; i++), and the handler would be added with cards[i].onclick = function() { }.

For each of the card elements, you want to modify the style.background of to change the background colour, and the .innerHTML to change the content.

The brackets and the i at the end of the function are an immediately-invoked function expression (IIFE), which gets run as soon as the page is loaded. This is needed to attach the event handlers.

This can be seen in the following:

var cards = document.getElementsByClassName('card');
var newElement = document.getElementsByClassName('new')[0];
for (var i = 0; i < cards.length; i++)(function(i) {
  cards[i].onclick = function() {
    newElement.style.background = 'red';
    newElement.innerHTML = 'modified';
  }
})(i);

<div class="new"><b></b>
  <button id="btn">Przeczytaj Artykułt</button>
  <div id="next">&rang;</div>
  <div id="prev">&lang;</div>
  <div id="slider"></div>
</div>
<div class="dol">
  <div class="card" id="pierwsz"><img src="slajdy/slajd1.png"></div>
  <div class="card" id="drugi"><img src="slajdy/slajd2.png"></div>
  <div class="card" id="trzeci"><img src="slajdy/slajd3.png"></div>
  <div class="card" id="czwarty"><img src="slajdy/slajd4.png"></div>
  <div class="card" id="piaty"><img src="slajdy/slajd5.png"></div>
</div>

Hope this helps! :)


问:
How to add blank lines to complete an Access report so that it matches a printed form?
I deal with a bunch of government forms, and I constantly find myself trying to get Access 2013 to output a report that matches a pre-printed form.

Most of the forms are now in .pdf form, so Access doesn't handle them well (to my knowledge) without additional software, which I cannot install on user production computers.

So I usually re-create the form as an Access report, but I have real difficulty when I have only enough records for a half a page.

How do I get a report to print the required records, and then fill the page with blank records so the "form" looks correct?

I'd be willing to try any possible solution - I've even gone so far as to create blank records to try to make this work. My goal, however, is to automate this process so any user can generate the report and it prints out correctly without a bunch of fiddling.

On this form, some or all of the lines might be used, and each person (I have ~550 people who each have an individual form) has a different number of lines, depending on the number of jumps they have completed.

答:
I hope you have found the solution to this issue. I am posting this in the hope that if someone else finds this same question they will find this one as the best possible solution, as I have been struggling for about 2 days now.

I suppose you have at least two tables and a query where you mix information from both, and your report is made out from this query. I will call this your Query1, so the trick is that when you open the Report from your Form, you will use the label number of your Form to make the filter of the Query1 from where you will get the information for your report.  Like this:

rectotal = DCount("*", "Quote-Report", "[Quote_No]=" & stQtNo)

This instruction will count how many records you have on your “Quote-Report”  Query that are of the same value of the [Quote_No]  field inside your Quote Form , as you are assigning the stQtNo variable to the Form with the name “Quote”; and put this value on your rectotal variable.

Now with rectotal you need to determine how many lines you want in your report. I used 28 so the following formula will give how many blank rows needed to fill the page.

```<code>If rectotal / 28 - Int(rectotal / 28) = 0 Then
    x = 28
    Else
    x = 28 * (rectotal / 28 - Int(rectotal / 28))
End If
blanklines = 28 - x
tLines = rectotal + blanklines
</code>```

Of course you can use 15, 20 or as many rows you want your report to print per page. The variable blanklines will give you this number.

Then I use the recordset procedure from Access to open the table where I have the information that will print in the detail section of the report and fill with as many records as I need using the blanklines variable and the Do Until Loop.

```<code>Set db = CurrentDb
Set rs = db.OpenRecordset("Item_QD", dbOpenDynaset, dbseechanges)
</code>```

Item_QD is the table
where I want to insert new records to fill the report detail section.

```<code>x = 0
rs.MoveLast

Do Until x = blanklines
    rs.AddNew
    rs![Quote_No] = stQtNo
    rs![CODE No] = "Z" & x  I use the Z and the number so I can erase the records once I don’t need them anymore.
    x = x + 1
    rs.Update
Loop
</code>```

Please note that you need to Dim db As Database and Dim rs As Recordset variables outside your private sub in module header. Also your Access needs to be running these two classes so you can use them.

Finally once you open your report you have to go to your detail section and do a requery command to refresh all the rows prior to print.  Need to format your detail cells in order to print the grid line and the rest is history.
The beauty of this procedure is that you can add and handle as many rows as you want or need inside your report and make a professional look of your quotes, packing slips, purchase orders, etc.

Hope this solves many problems.  For a fast reference on how to use and manage ACCESS record set visit:  https://www.youtube.com/watch?v=WNm17l54z1c

```<code>Private Sub Report_Open(Cancel As Integer)
Dim blanklines, tLines As Integer
    Dim rectotal, x  As Long
    Dim stQtNo As String

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Item_QD", dbOpenDynaset, dbseechanges)

stQtNo = Forms![Quote].[Quote_No]

rectotal = DCount("*", "Quote-Report", "[Quote_No]=" & stQtNo)
If rectotal / 28 - Int(rectotal / 28) = 0 Then
    x = 28
    Else
    x = 28 * (rectotal / 28 - Int(rectotal / 28))
End If
blanklines = 28 - x
tLines = rectotal + blanklines

x = 0
rs.MoveLast

Do Until x = blanklines
    rs.AddNew
    rs![Quote_No] = stQtNo
    rs![CODE No] = "Z" & x
    x = x + 1
    rs.Update
Loop
End Sub
</code>```

Body:
I hope you have found the solution to this issue. I am posting this in the hope that if someone else finds this same question they will find this one as the best possible solution, as I have been struggling for about 2 days now.

I suppose you have at least two tables and a query where you mix information from both, and your report is made out from this query. I will call this your Query1, so the trick is that when you open the Report from your Form, you will use the label number of your Form to make the filter of the Query1 from where you will get the information for your report.  Like this:

rectotal = DCount("*", "Quote-Report", "[Quote_No]=" & stQtNo)

This instruction will count how many records you have on your “Quote-Report”  Query that are of the same value of the [Quote_No]  field inside your Quote Form , as you are assigning the stQtNo variable to the Form with the name “Quote”; and put this value on your rectotal variable.

Now with rectotal you need to determine how many lines you want in your report. I used 28 so the following formula will give how many blank rows needed to fill the page.

If rectotal / 28 - Int(rectotal / 28) = 0 Then
    x = 28
    Else
    x = 28 * (rectotal / 28 - Int(rectotal / 28))
End If
blanklines = 28 - x
tLines = rectotal + blanklines

Of course you can use 15, 20 or as many rows you want your report to print per page. The variable blanklines will give you this number.

Then I use the recordset procedure from Access to open the table where I have the information that will print in the detail section of the report and fill with as many records as I need using the blanklines variable and the Do Until Loop.

Set db = CurrentDb
Set rs = db.OpenRecordset("Item_QD", dbOpenDynaset, dbseechanges)

Item_QD is the table
where I want to insert new records to fill the report detail section.

x = 0
rs.MoveLast

Do Until x = blanklines
    rs.AddNew
    rs![Quote_No] = stQtNo
    rs![CODE No] = "Z" & x  I use the Z and the number so I can erase the records once I don’t need them anymore.
    x = x + 1
    rs.Update
Loop

Please note that you need to Dim db As Database and Dim rs As Recordset variables outside your private sub in module header. Also your Access needs to be running these two classes so you can use them.

Finally once you open your report you have to go to your detail section and do a requery command to refresh all the rows prior to print.  Need to format your detail cells in order to print the grid line and the rest is history.
The beauty of this procedure is that you can add and handle as many rows as you want or need inside your report and make a professional look of your quotes, packing slips, purchase orders, etc.

Hope this solves many problems.  For a fast reference on how to use and manage ACCESS record set visit:  https://www.youtube.com/watch?v=WNm17l54z1c

Private Sub Report_Open(Cancel As Integer)
Dim blanklines, tLines As Integer
    Dim rectotal, x  As Long
    Dim stQtNo As String

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Item_QD", dbOpenDynaset, dbseechanges)

stQtNo = Forms![Quote].[Quote_No]

rectotal = DCount("*", "Quote-Report", "[Quote_No]=" & stQtNo)
If rectotal / 28 - Int(rectotal / 28) = 0 Then
    x = 28
    Else
    x = 28 * (rectotal / 28 - Int(rectotal / 28))
End If
blanklines = 28 - x
tLines = rectotal + blanklines

x = 0
rs.MoveLast

Do Until x = blanklines
    rs.AddNew
    rs![Quote_No] = stQtNo
    rs![CODE No] = "Z" & x
    x = x + 1
    rs.Update
Loop
End Sub

ContentLicense: CC BY-SA 4.0


问:
groovy how create array with name?
IM trying to use this command in groovy but I cant print the array

appears and error

```<code>       Caught: java.lang.IllegalArgumentException: argument type mismatch
</code>```

java.lang.IllegalArgumentException: argument type mismatch
    at Test.main(Test.groovy:7)

how I could solve this

I use this same command without this line  and this works

```<code>          testArray["fff"] = "B"
</code>```

this is my code

I dont know because I cant create this 2d array

```<code> def testArray =  []
  testArray[0] = "A"
      testArray["fff"] = "B"
      testArray[2] = "C"

   println testArray
</code>```

please give me a help

答: Use testArray = [:] instead. And this is not an array but a map (a LinkedHashMap to be specific and [:] is the literal Groovy uses to create it).  Maps in Java/Groovy are associative data structures to store key-value-relations.  Access via map[key] is an enhancement, that Groovy brings to the table.

Title: groovy how create array with name?

Body:
IM trying to use this command in groovy but I cant print the array

appears and error

       Caught: java.lang.IllegalArgumentException: argument type mismatch

java.lang.IllegalArgumentException: argument type mismatch
    at Test.main(Test.groovy:7)

how I could solve this

I use this same command without this line  and this works

          testArray["fff"] = "B"

this is my code

I dont know because I cant create this 2d array

 def testArray =  []
  testArray[0] = "A"
      testArray["fff"] = "B"
      testArray[2] = "C"

   println testArray

please give me a help


问:
remove collection with delete-orphan not work with null assignment? :(
I am having problems removing another entity through cascade delete-orphan.
It works when I clear the associated set collection, but not when I make the set collection null.
Let me explain in detail.
The config snippet:

```<code><class name="com.sample.CategoriesDefault" table="cats">
  <id name="id" column="id" type="string" length="40" access="property">
     <generator class="assigned" />
  </id>
  <version name="version" column="objVrs"  unsaved-value="negative"/>

 <set name="bla" lazy="false" cascade="all-delete-orphan" inverse="true">
      <key column="idCats" not-null="true"/>
       <one-to-many class="com.sample.BLA"/>
 </set>

<class name="com.sample.BLA" table="blaTEST">
   <id name="id" column="id" type="string" length="40" access="property">
     <generator class="assigned" />
   </id>
   <version name="version" column="objVrs"  unsaved-value="negative"/>
   <property name="bla" type="string" column="bla"/>
   <many-to-one name="parent" class="com.sample.CategoriesDefault" column="idCats" not-null="true"/>
</class>
</code>```

My sample code:

```<code>Categories cats = new CategoriesDefault();
final Set<BLA> col = new HashSet<BLA>();
col.add(new BLA(cats));
cats.setBla(col);
cats.saveOrupdate(); // will update/insert it in the db.
</code>```

The following works correctly, that is: all the collection items are all moved from the db.

```<code>cats.getBla().clear();
cats.saveOrUpdate();
</code>```

I think this works as the PersistSet of Hibernate is marked as dirty when calling this method.

The following however doesn't work the same as above like I would want/expect.

```<code>cats.setBla(null);
cats.saveOrUpdate();
</code>```

If I reload the cats item from the db, it still contains the BLA items and no delete statement is generated by Hibernate :(..
Why not??... or is this a bug ? I am using 3.6.0.Final.

答:
I think its because hibernate uses its own collection implementations (which is why the docs say you MUST declare collections as interfaces, not implementations), and the collection implementations obey the semantics of you transitive persistence settings.  So, when you do

```<code>cats.getBla().clear()
</code>```

the getBla() part is the hibernate collection implementation, which knows to remove the children from the session when clear() is called.

When you do

```<code>cats.setBla(null);
</code>```

you haven't removed the collection, you have changed the parent's reference to the collection to null.  The collection probably still exists in the session.

Body:
I am having problems removing another entity through cascade delete-orphan.
It works when I clear the associated set collection, but not when I make the set collection null.
Let me explain in detail.
The config snippet:

<class name="com.sample.CategoriesDefault" table="cats">
  <id name="id" column="id" type="string" length="40" access="property">
     <generator class="assigned" />
  </id>
  <version name="version" column="objVrs"  unsaved-value="negative"/>

 <set name="bla" lazy="false" cascade="all-delete-orphan" inverse="true">
      <key column="idCats" not-null="true"/>
       <one-to-many class="com.sample.BLA"/>
 </set>

<class name="com.sample.BLA" table="blaTEST">
   <id name="id" column="id" type="string" length="40" access="property">
     <generator class="assigned" />
   </id>
   <version name="version" column="objVrs"  unsaved-value="negative"/>
   <property name="bla" type="string" column="bla"/>
   <many-to-one name="parent" class="com.sample.CategoriesDefault" column="idCats" not-null="true"/>
</class>

My sample code:

Categories cats = new CategoriesDefault();
final Set<BLA> col = new HashSet<BLA>();
col.add(new BLA(cats));
cats.setBla(col);
cats.saveOrupdate(); // will update/insert it in the db.

The following works correctly, that is: all the collection items are all moved from the db.

cats.getBla().clear();
cats.saveOrUpdate();

I think this works as the PersistSet of Hibernate is marked as dirty when calling this method.

The following however doesn't work the same as above like I would want/expect.

cats.setBla(null);
cats.saveOrUpdate();

If I reload the cats item from the db, it still contains the BLA items and no delete statement is generated by Hibernate :(..
Why not??... or is this a bug ? I am using 3.6.0.Final.

Body:
I think its because hibernate uses its own collection implementations (which is why the docs say you MUST declare collections as interfaces, not implementations), and the collection implementations obey the semantics of you transitive persistence settings.  So, when you do

cats.getBla().clear()

the getBla() part is the hibernate collection implementation, which knows to remove the children from the session when clear() is called.

When you do

cats.setBla(null);

you haven't removed the collection, you have changed the parent's reference to the collection to null.  The collection probably still exists in the session.


问:
How to Modify value of optionset by code C#?
Do you know if there is a solution to modify the value (not a label) of an option in optionset by code C#.

for example, I have this Option:
(Label: OldLabel, Value: OldValue)

and I want this:
(Label: OldLabel, Value: NewValue)

I tried by the following code, but is not working:

```<code>UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = newValue,
        Label = new Label("oldLabel", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);
</code>```

答:
UpdateOptionValueRequest is the message to update the Label (Display text) using Key (Integer). You are expecting to update the Integer key using Label, no way.

This will create data inconsistency across the system for existing data vs new data. Even if you manually update like this or delete the option & recreate a new option using SDK, data loss is unavoidable.

If you see the code sample in MSDN, the comments clearly calls out.

```<code>#region How to update an option item in a picklist
// In order to change *labels* on option set values (or delete) option set
// values, you must use UpdateOptionValueRequest
// (or DeleteOptionValueRequest).
UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = optionList[1].Value.Value,
        Label = new Label("Updated Option 1", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);

Console.WriteLine("Option Set option *label* changed.");
#endregion How to update an option item in a picklist
</code>```

Body:
Do you know if there is a solution to modify the value (not a label) of an option in optionset by code C#.

for example, I have this Option:
(Label: OldLabel, Value: OldValue)

and I want this:
(Label: OldLabel, Value: NewValue)

I tried by the following code, but is not working:

UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = newValue,
        Label = new Label("oldLabel", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);

Body:
UpdateOptionValueRequest is the message to update the Label (Display text) using Key (Integer). You are expecting to update the Integer key using Label, no way.

This will create data inconsistency across the system for existing data vs new data. Even if you manually update like this or delete the option & recreate a new option using SDK, data loss is unavoidable.

If you see the code sample in MSDN, the comments clearly calls out.

#region How to update an option item in a picklist
// In order to change *labels* on option set values (or delete) option set
// values, you must use UpdateOptionValueRequest
// (or DeleteOptionValueRequest).
UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = optionList[1].Value.Value,
        Label = new Label("Updated Option 1", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);

Console.WriteLine("Option Set option *label* changed.");
#endregion How to update an option item in a picklist


问:
Perl: Parentheses vs Brackets for array definition, why is one considered a scalar?
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

```<code><!--template2.tmpl-->
<html>
<body>
<table>
  <tr>
    <th>Language</th>
    <th>Description</th>
  </tr>
  <tmpl_loop name="language">
  <tr>
    <td><tmpl_var name="language_name"></td>
    <td><tmpl_var name="description"></td>
  </tr>
  </tmpl_loop>
</table>
</body>
</html>
</code>```

And here's the CGI test program:

```<code>#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();
</code>```

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

答:
```<code>language => @rows
</code>```

means

```<code>'language', $rows[0], $rows[1], $rows[2], ...
</code>```

or

```<code>language => $rows[0],
$rows[1] => $rows[2],
...
</code>```

You want

```<code>language => \@rows
</code>```

Body:
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

    Language
    Description

  <tmpl_loop name="language">

    <tmpl_var name="language_name">
    <tmpl_var name="description">

  </tmpl_loop>

And here's the CGI test program:

#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

Body:
language => @rows

means

'language', $rows[0], $rows[1], $rows[2], ...

or

language => $rows[0],
$rows[1] => $rows[2],
...

You want

language => \@rows


问:
select all available combination by specific field in one query
I have table "teams" with fields: id, team_name

```<code>  id, team_name
</code>```

1, Real Madrid

2, FC Barcelona

3, juventus

4, Milan

i want to select in one query all available VS combinations ...

like that:

Real Madrid - FC Barcelona

Real Madrid - juventus

Real Madrid - Milan

FC Barcelona - juventus

FC Barcelona - Milan

juventus - Milan

the purpose is to find solution for dynamic with different amount of rows if will be more teams in the tables...

this is possible? how... ?

Thanks :)

答:
Use a self join.

```<code>select t1.team_name,t2.team_name
from tbl t1
join tbl t2 on t1.team_name>t2.team_name --or if the id's are unique use
                                          /* on t1.id < t2.id */
</code>```

Body:
I have table "teams" with fields: id, team_name

  id, team_name

1, Real Madrid

2, FC Barcelona

3, juventus

4, Milan

i want to select in one query all available VS combinations ...

like that:

Real Madrid - FC Barcelona

Real Madrid - juventus

Real Madrid - Milan

FC Barcelona - juventus

FC Barcelona - Milan

juventus - Milan

the purpose is to find solution for dynamic with different amount of rows if will be more teams in the tables...

this is possible? how... ?

Thanks :)

Body:
Use a self join.

select t1.team_name,t2.team_name
from tbl t1
join tbl t2 on t1.team_name>t2.team_name --or if the id's are unique use
                                          /* on t1.id < t2.id */


问:
Add Blank Space between SVGs
I want to display 3 SVGs in a horizontal row in a div, with say 5px blank space between without changing the SVG at all.

Padding and Margin do not work, at least not reliably for svgs, so please what else could I do to achieve this?

答:
Can you make use of  letter-spacing:? This is one example of what you may be looking for.

 div{
 text-align:center;
 letter-spacing:-10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="RED" />
   Sorry, your browser does not support inline SVG.
</svg>

<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="GREEN" />
   Sorry, your browser does not support inline SVG.
</svg>

<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="BLUE" />
   Sorry, your browser does not support inline SVG.
</svg>
 </div></code>```

Title: Add Blank Space between SVGs

Body:
Can you make use of  letter-spacing:? This is one example of what you may be looking for.

 div{
 text-align:center;
 letter-spacing:-10px;
 }

<div>
<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="RED" />
   Sorry, your browser does not support inline SVG.
</svg>

<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="GREEN" />
   Sorry, your browser does not support inline SVG.
</svg>

<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="BLUE" />
   Sorry, your browser does not support inline SVG.
</svg>
 </div>


问:
Can Intellij Idea create javadoc comments for all the methods of a class at one time?
I know if I type /** at the top of a method, it will create the bare bones comment for that method, is there a way to do it for a whole class at one time?  I tried the code menu, but did not see it.</p>

答:
A slightly quicker way is to set the action Fix doc comment to something like  Alt+Shift+J (by default there is no keyboard shortcut). Now if the cursor is anywhere in the method you can use this and it will generate the comments instead of having to be at the exact line.

There may not be a default keystroke setup for this, so you can add it.  Go to IntelliJ preferences and type 'fix doc comment' into the search bar.