问:
Trying to change the position of characters of two different numbers
I was trying to do an exercise which is "Type 2 numbers and each character in a pair position swap it with the equivalent of the character in the same position of the second number, and the characters in an impair position swap them with the character in the same position of the first number"

But I haven't worked with characters before so I'm not sure what I'm doing wrong, this is the code i have so far, it throws random stuff out instead of the numbers changed.
I have this code so far:

```<code>public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] n1, n2;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();

            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }
            n1 = chars1;
            n2 = chars2;
            txvRes.setText("the first number is: "+n1+" and the second number is: "+n2);
        }
    };}
</code>```

答:
Alright, I found the way to fix it, first of all i was using char array in the setText which caused to output a weird string of characters

Second, i was basically changing the values wrong in the function because when i changed the first one i was replacing the value of the first one that i had previously, meaning that both numbers would end up with the same characters instead of being swapped at certain positions.

Here's the fixed code:

```<code>public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] chars3, chars4;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();
            chars3 = chars1;
            chars4 = chars2;
            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars3[i];
                        chars1[i] = chars4[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars4[i];
                        chars1[i] = chars3[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars3[i];
                        chars1[i] = chars4[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars4[i];
                        chars2[i] = chars3[i];
                    }
                }
            }
            String c = new String(chars1);
            String d = new String(chars2);
            txvRes.setText("El primer Numero es: "+c+" y el segundo Numero es: "+d);
        }
    };
}
</code>```

Body:
I was trying to do an exercise which is "Type 2 numbers and each character in a pair position swap it with the equivalent of the character in the same position of the second number, and the characters in an impair position swap them with the character in the same position of the first number"

But I haven't worked with characters before so I'm not sure what I'm doing wrong, this is the code i have so far, it throws random stuff out instead of the numbers changed.
I have this code so far:

public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] n1, n2;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();

            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }
            n1 = chars1;
            n2 = chars2;
            txvRes.setText("the first number is: "+n1+" and the second number is: "+n2);
        }
    };}

Body:
Alright, I found the way to fix it, first of all i was using char array in the setText which caused to output a weird string of characters

Second, i was basically changing the values wrong in the function because when i changed the first one i was replacing the value of the first one that i had previously, meaning that both numbers would end up with the same characters instead of being swapped at certain positions.

Here's the fixed code:

public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] chars3, chars4;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();
            chars3 = chars1;
            chars4 = chars2;
            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars3[i];
                        chars1[i] = chars4[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars4[i];
                        chars1[i] = chars3[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars3[i];
                        chars1[i] = chars4[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars4[i];
                        chars2[i] = chars3[i];
                    }
                }
            }
            String c = new String(chars1);
            String d = new String(chars2);
            txvRes.setText("El primer Numero es: "+c+" y el segundo Numero es: "+d);
        }
    };
}


来源: stackexchange

问:
Detect if someone injects code with "javascript:" or bookmarklet
Is it possible for me to, using JavaScript, detect if someone uses a bookmarklet or inject JavaScript code into a page using a "javascript:{command}" URL?</p>

答:
No, it isn't.  They could inject code that removes your detection method.

I'm not sure what it is you're trying to do or prevent, but expecting to enforce security client-side in this manner is not going to help you.

ContentLicense: CC BY-SA 3.0


问:
Replacing DBMS_OUPUT in a PL/SQL test LOOP to return a collection
So I have this assignment where I have to create a stored procedure to search for movies in an Oracle DataBase.

The search string follow the following logic :

It looks for the year of the movie in parenthesis

Ex. (1992)

It looks for a range of year in brackets

Ex. [1992,2000]

It looks for a word contained in the title, country, realisator, genre, actors or scenarists.

Any of the above can be combined multiple times.

Ex. : The Lord Of the Ring Ian McKellen Christopher Lee [1992,2000]

The logic used to solve this problem was to make a giant query to group all the required data then use a cursor to loop through the result set with a cursor to check if every word of the search string is valid.

I managed to make a procedure that works as expected, but the only way I found to return the results was to use DBMS_OUTPUT. Now the problem is that when I plug this is Hibernate the DBMS_OUTPUT is not sent over to the client. I've read some way to force the output by setting DBMS_OUTPUT.enable, but I feel that this is not the proper way to do it.

So here are my questions :

Is my logic flawed? Is there a simpler way to archive this with a single select or something?

Is there a way to dynamically push data inside a cursor and return it?

Am I really supposed to trick the DBMS_OUTPUT so it is sent over to hibernate?

Here's my code :

```<code>CREATE OR REPLACE PROCEDURE p_SearchFilm(searchString IN VARCHAR2) IS
    IsValid BOOLEAN;
    y1 INTEGER;
    y2 INTEGER;
    subStrArray apex_application_global.vc_arr2;
    term VARCHAR(100);

    CURSOR films IS
            Select FilmId, Titre, real.Prenom||' '||real.nom as Realisateur, anneeSortie, ListPays, ListGenres,
                   ListScenaristes, ListActeurs, langueOrigine
                from Film
                natural left join
                    (select FilmId, listagg(p.Nom, ',') within group (Order By p.nom) ListPays from Film
                        natural join Film_vs_pays
                        natural join Pays p
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(g.Nom, ',') within group (Order By g.nom) ListGenres from Film
                        natural join Film_vs_Genre
                        natural join Genre g
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListScenaristes from Film
                        natural join Scenariste s
                        join Personne p on s.personneId = p.personneId
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListActeurs from Film
                        natural join Personnage perso
                        join Personne p on perso.personneId = p.personneId
                        Group by FilmId)
                left join Personne real on real.personneId = realisateurId;
BEGIN
    <<FILM_LOOP>>
    FOR film IN films LOOP
        subStrArray := apex_util.string_to_table(searchString, ' ');
        FOR i in 1..subStrArray.count LOOP
            IsValid:= FALSE;
            term:= subStrArray(i);
            IF REGEXP_LIKE(term, '\(\d{4}\)') THEN
                IF film.anneeSortie = TO_NUMBER(regexp_substr(term, '\d{4}')) THEN
                    IsValid:= TRUE;
                END IF;
            ELSIF REGEXP_LIKE(term, '\[\d{4},\d{4}\]') THEN
                y1:= regexp_substr(term, '\d{4}', 1, 1);
                y2:= regexp_substr(term, '\d{4}', 1, 2);

                IF film.anneeSortie BETWEEN y1 AND y2 THEN
                    IsValid:= TRUE;
                END IF;
            ELSE
                IF UPPER(film.Titre||film.Realisateur||film.ListActeurs||film.ListScenaristes||film.ListGenres||film.ListPays||film.langueOrigine)
                     LIKE '%'||UPPER(term)||'%' THEN
                    IsValid:= TRUE;
                END IF;
            END IF;

            IF NOT IsValid THEN
                CONTINUE FILM_LOOP;
            END IF;

        END LOOP;

        DBMS_OUTPUT.put_line(film.FilmId||'|'||film.Titre);
    END LOOP;
END;
</code>```

A small disclaimer here :

I saw some similar questions that addressed this issue, but the ones that used cursors were returning a complete select, not hand picked rows.

The question about DBMS_OUTPUT and Hibernate stated that it should be avoided.

The questions using piped rows seamed to work only with functions (Changing the procedure for a function called by the procedure could be a valid work around, I'd like to know if something else is possible before tho).

答:
The use of the DBMS_OUTPUT package is pretty much bounded to developer executions of anonymous blocks, and hence not suited for your intended communication with the Hibernate framework.

If you already have a stored procedure to apply your filter and determine your positive results, a solution could be populate a temporary table with those positives, and then return an open cursor which will only have the data from that temporary table, something like:

```<code>create global temporary table movie_results( movie varchar2(200) ) on commit preserve rows;
</code>```

Of course your temp table can have more columns, but let me leave it like this, just to illustrate my solution.

```<code>   CREATE OR REPLACE PROCEDURE p_SearchFilm(searchString IN VARCHAR2, movies out SYS_REFCURSOR) IS
        IsValid BOOLEAN;
        y1 INTEGER;
        y2 INTEGER;
        subStrArray apex_application_global.vc_arr2;
        term VARCHAR(100);

        CURSOR films IS
                Select FilmId, Titre, real.Prenom||' '||real.nom as Realisateur, anneeSortie, ListPays, ListGenres,
                       ListScenaristes, ListActeurs, langueOrigine
                    from Film
                    natural left join
                        (select FilmId, listagg(p.Nom, ',') within group (Order By p.nom) ListPays from Film
                            natural join Film_vs_pays
                            natural join Pays p
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(g.Nom, ',') within group (Order By g.nom) ListGenres from Film
                            natural join Film_vs_Genre
                            natural join Genre g
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListScenaristes from Film
                            natural join Scenariste s
                            join Personne p on s.personneId = p.personneId
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListActeurs from Film
                            natural join Personnage perso
                            join Personne p on perso.personneId = p.personneId
                            Group by FilmId)
                    left join Personne real on real.personneId = realisateurId;
    BEGIN
        <<FILM_LOOP>>
        FOR film IN films LOOP
            subStrArray := apex_util.string_to_table(searchString, ' ');
            FOR i in 1..subStrArray.count LOOP
                IsValid:= FALSE;
                term:= subStrArray(i);
                IF REGEXP_LIKE(term, '\(\d{4}\)') THEN
                    IF film.anneeSortie = TO_NUMBER(regexp_substr(term, '\d{4}')) THEN
                        IsValid:= TRUE;
                    END IF;
                ELSIF REGEXP_LIKE(term, '\[\d{4},\d{4}\]') THEN
                    y1:= regexp_substr(term, '\d{4}', 1, 1);
                    y2:= regexp_substr(term, '\d{4}', 1, 2);

                    IF film.anneeSortie BETWEEN y1 AND y2 THEN
                        IsValid:= TRUE;
                    END IF;
                ELSE
                    IF UPPER(film.Titre||film.Realisateur||film.ListActeurs||film.ListScenaristes||film.ListGenres||film.ListPays||film.langueOrigine)
                         LIKE '%'||UPPER(term)||'%' THEN
                        IsValid:= TRUE;
                    END IF;
                END IF;

                IF NOT IsValid THEN
                    CONTINUE FILM_LOOP;
                END IF;

            END LOOP;

            --DBMS_OUTPUT.put_line(film.FilmId||'|'||film.Titre);
            insert into movie_results( movie )
            values film.FilmId||'|'||film.Titre;

            commit;
        END LOOP;

        open movies for
           select *
           from movie_results;
    END;
</code>```

Now your parameter 'movies' has all the positive results derived from your procedure, and all you'll have to do is read the cursor in Hibernate.

Note that, once you close your connection, the temporary table looses all the data and will be ready to use again when another session begins (always remember to close your Cursors/Connections).

Body:
So I have this assignment where I have to create a stored procedure to search for movies in an Oracle DataBase.

The search string follow the following logic :

It looks for the year of the movie in parenthesis

Ex. (1992)

It looks for a range of year in brackets

Ex. [1992,2000]

It looks for a word contained in the title, country, realisator, genre, actors or scenarists.

Any of the above can be combined multiple times.

Ex. : The Lord Of the Ring Ian McKellen Christopher Lee [1992,2000]

The logic used to solve this problem was to make a giant query to group all the required data then use a cursor to loop through the result set with a cursor to check if every word of the search string is valid.

I managed to make a procedure that works as expected, but the only way I found to return the results was to use DBMS_OUTPUT. Now the problem is that when I plug this is Hibernate the DBMS_OUTPUT is not sent over to the client. I've read some way to force the output by setting DBMS_OUTPUT.enable, but I feel that this is not the proper way to do it.

So here are my questions :

Is my logic flawed? Is there a simpler way to archive this with a single select or something?

Is there a way to dynamically push data inside a cursor and return it?

Am I really supposed to trick the DBMS_OUTPUT so it is sent over to hibernate?

Here's my code :

CREATE OR REPLACE PROCEDURE p_SearchFilm(searchString IN VARCHAR2) IS
    IsValid BOOLEAN;
    y1 INTEGER;
    y2 INTEGER;
    subStrArray apex_application_global.vc_arr2;
    term VARCHAR(100);

    CURSOR films IS
            Select FilmId, Titre, real.Prenom||' '||real.nom as Realisateur, anneeSortie, ListPays, ListGenres,
                   ListScenaristes, ListActeurs, langueOrigine
                from Film
                natural left join
                    (select FilmId, listagg(p.Nom, ',') within group (Order By p.nom) ListPays from Film
                        natural join Film_vs_pays
                        natural join Pays p
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(g.Nom, ',') within group (Order By g.nom) ListGenres from Film
                        natural join Film_vs_Genre
                        natural join Genre g
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListScenaristes from Film
                        natural join Scenariste s
                        join Personne p on s.personneId = p.personneId
                        Group by FilmId)
                natural left join
                    (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListActeurs from Film
                        natural join Personnage perso
                        join Personne p on perso.personneId = p.personneId
                        Group by FilmId)
                left join Personne real on real.personneId = realisateurId;
BEGIN
    <<FILM_LOOP>>
    FOR film IN films LOOP
        subStrArray := apex_util.string_to_table(searchString, ' ');
        FOR i in 1..subStrArray.count LOOP
            IsValid:= FALSE;
            term:= subStrArray(i);
            IF REGEXP_LIKE(term, '\(\d{4}\)') THEN
                IF film.anneeSortie = TO_NUMBER(regexp_substr(term, '\d{4}')) THEN
                    IsValid:= TRUE;
                END IF;
            ELSIF REGEXP_LIKE(term, '\[\d{4},\d{4}\]') THEN
                y1:= regexp_substr(term, '\d{4}', 1, 1);
                y2:= regexp_substr(term, '\d{4}', 1, 2);

                IF film.anneeSortie BETWEEN y1 AND y2 THEN
                    IsValid:= TRUE;
                END IF;
            ELSE
                IF UPPER(film.Titre||film.Realisateur||film.ListActeurs||film.ListScenaristes||film.ListGenres||film.ListPays||film.langueOrigine)
                     LIKE '%'||UPPER(term)||'%' THEN
                    IsValid:= TRUE;
                END IF;
            END IF;

            IF NOT IsValid THEN
                CONTINUE FILM_LOOP;
            END IF;

        END LOOP;

        DBMS_OUTPUT.put_line(film.FilmId||'|'||film.Titre);
    END LOOP;
END;

A small disclaimer here :

I saw some similar questions that addressed this issue, but the ones that used cursors were returning a complete select, not hand picked rows.

The question about DBMS_OUTPUT and Hibernate stated that it should be avoided.

The questions using piped rows seamed to work only with functions (Changing the procedure for a function called by the procedure could be a valid work around, I'd like to know if something else is possible before tho).

Body:
The use of the DBMS_OUTPUT package is pretty much bounded to developer executions of anonymous blocks, and hence not suited for your intended communication with the Hibernate framework.

If you already have a stored procedure to apply your filter and determine your positive results, a solution could be populate a temporary table with those positives, and then return an open cursor which will only have the data from that temporary table, something like:

create global temporary table movie_results( movie varchar2(200) ) on commit preserve rows;

Of course your temp table can have more columns, but let me leave it like this, just to illustrate my solution.

   CREATE OR REPLACE PROCEDURE p_SearchFilm(searchString IN VARCHAR2, movies out SYS_REFCURSOR) IS
        IsValid BOOLEAN;
        y1 INTEGER;
        y2 INTEGER;
        subStrArray apex_application_global.vc_arr2;
        term VARCHAR(100);

        CURSOR films IS
                Select FilmId, Titre, real.Prenom||' '||real.nom as Realisateur, anneeSortie, ListPays, ListGenres,
                       ListScenaristes, ListActeurs, langueOrigine
                    from Film
                    natural left join
                        (select FilmId, listagg(p.Nom, ',') within group (Order By p.nom) ListPays from Film
                            natural join Film_vs_pays
                            natural join Pays p
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(g.Nom, ',') within group (Order By g.nom) ListGenres from Film
                            natural join Film_vs_Genre
                            natural join Genre g
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListScenaristes from Film
                            natural join Scenariste s
                            join Personne p on s.personneId = p.personneId
                            Group by FilmId)
                    natural left join
                        (select FilmId, listagg(p.Prenom||' '||p.Nom, ',') within group (Order By p.nom) ListActeurs from Film
                            natural join Personnage perso
                            join Personne p on perso.personneId = p.personneId
                            Group by FilmId)
                    left join Personne real on real.personneId = realisateurId;
    BEGIN
        <<FILM_LOOP>>
        FOR film IN films LOOP
            subStrArray := apex_util.string_to_table(searchString, ' ');
            FOR i in 1..subStrArray.count LOOP
                IsValid:= FALSE;
                term:= subStrArray(i);
                IF REGEXP_LIKE(term, '\(\d{4}\)') THEN
                    IF film.anneeSortie = TO_NUMBER(regexp_substr(term, '\d{4}')) THEN
                        IsValid:= TRUE;
                    END IF;
                ELSIF REGEXP_LIKE(term, '\[\d{4},\d{4}\]') THEN
                    y1:= regexp_substr(term, '\d{4}', 1, 1);
                    y2:= regexp_substr(term, '\d{4}', 1, 2);

                    IF film.anneeSortie BETWEEN y1 AND y2 THEN
                        IsValid:= TRUE;
                    END IF;
                ELSE
                    IF UPPER(film.Titre||film.Realisateur||film.ListActeurs||film.ListScenaristes||film.ListGenres||film.ListPays||film.langueOrigine)
                         LIKE '%'||UPPER(term)||'%' THEN
                        IsValid:= TRUE;
                    END IF;
                END IF;

                IF NOT IsValid THEN
                    CONTINUE FILM_LOOP;
                END IF;

            END LOOP;

            --DBMS_OUTPUT.put_line(film.FilmId||'|'||film.Titre);
            insert into movie_results( movie )
            values film.FilmId||'|'||film.Titre;

            commit;
        END LOOP;

        open movies for
           select *
           from movie_results;
    END;

Now your parameter 'movies' has all the positive results derived from your procedure, and all you'll have to do is read the cursor in Hibernate.

Note that, once you close your connection, the temporary table looses all the data and will be ready to use again when another session begins (always remember to close your Cursors/Connections).


问:
How to change Firebase Crash Reporting Email Language
I set up Crash Reporting in my app and receiving the report email in English a week ago. However, for the last 4 days, the email changed to Japanese. Howe to change the language back to English?

Email:

In Firebase Console -> Alert subscriptions, there are option to receive or not receive email. But not the language.

Alert subscriptions:

And my Default Language in Google account is English - United States

Google Account:

答:
According @DougStevenson, it's a known bug and Firebase team is working on it.

Doug Stevenson's comment


问:
Where does realm React-Native store data on mobile apps?
I'm new to mobile development and I need to build a local storage for an app, this is where I've heard of Realm.
Could you give me more information about how exactly Realm stores data in the application?

Is it a file or ...? And how do you manage app updates in order to not lose the data already in the user's phone?

Thank you

答:
Realm stores data in a proprietary binary format in a .realm file on the devices filesystem. If you are running the iOS simulator its visible and can be opened with the Realm Browser application. </p>

<p>Realm handles updates in two ways. You can use the Realm Object Server. You would make all changes to a central server and realm handles all the syncing for you. If you want to destructively change the db model you would have to clone your server realm an then serve a new one to the new version of your app. Or if you have local database instances on your devices you handle changes to the DB model with migrations. </p>

Body:
Realm stores data in a proprietary binary format in a .realm file on the devices filesystem. If you are running the iOS simulator its visible and can be opened with the Realm Browser application.

Realm handles updates in two ways. You can use the Realm Object Server. You would make all changes to a central server and realm handles all the syncing for you. If you want to destructively change the db model you would have to clone your server realm an then serve a new one to the new version of your app. Or if you have local database instances on your devices you handle changes to the DB model with migrations.


问:
Removing multiple columns with the same name except the first one?
If you have multiple columns with the same name in a dataframe, how do you remove all of the columns except the first one?</p>

答:
Let df be a dataframe with two duplicated columns:

```<code>df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=("a","a","b"))
#   a  a  b
#0  1  2  3
#1  4  5  6
#2  7  8  9
</code>```

Find out which column names are not duplicated, and keep them:

```<code>df1 = df.loc[:, ~df.columns.duplicated()]
#   a  b
#0  1  3
#1  4  6
#2  7  9
</code>```

Body:
Let df be a dataframe with two duplicated columns:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=("a","a","b"))
#   a  a  b
#0  1  2  3
#1  4  5  6
#2  7  8  9

Find out which column names are not duplicated, and keep them:

df1 = df.loc[:, ~df.columns.duplicated()]
#   a  b
#0  1  3
#1  4  6
#2  7  9


问:
Angular - Data Binding with ngFor directive
I am new to angular and I'm not sure of how to render data as HTML markup. How can I show the component data inside of the component template?

There is a small reproduction in this plnkr.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `

`
})
export class AppComponent {
  name = 'Angular';
  liArraycontent = ["testing 1", "testing 2", "testing3"]

}
```

答:
So inside of your code for the list just do this:

```<code><li *ngFor ="let student of liArraycontent">{{student}}</li>
</code>```

And similarly if you had an array of objects you could just do {{student.name}} or any other attributes for the object

Body:
So inside of your code for the list just do this:

<li *ngFor ="let student of liArraycontent">{{student}}</li>

And similarly if you had an array of objects you could just do {{student.name}} or any other attributes for the object


问:
Amazon MWS: Accessing Array of Matching Products
I am Working with MWS for the first time and hoping to create a program that uses the ListMatchingProducts request to average out the prices of every product that matches a query.

It should be a very simple program, but I am having trouble retrieving data.

First I make the call and get amazon's xml sheet, Then I convert the xml to an array.

Print_R shows that the array looks something like this:

```<code>Array ( [ListMatchingProductsResult] => Array ( [Products] => Array ( [Product] => Array ( [0] => Array ( [Identifiers] => Array ( [MarketplaceASIN] => Array ( [MarketplaceId] => ATVPDKIKX0DER [ASIN] => 0786866020 ) ) [AttributeSets] => Array ( [ItemAttributes] => Array ( [Author] => Array ( [0] => Stephen C. Lundin [1] => Harry Paul [2] => John Christensen ) [Binding] => Hardcover [Brand] => Hyperion [Color] => White [Creator] => Ken Blanchard [Edition] => 1 [Feature] => Great product! [ItemDimensions] => Array ( [Height] => 8.25 [Length] => 5.50 [Width] => 0.00 [Weight] => 0.54 ) [IsAdultProduct] => false [Label] => Hyperion [Languages] => Array ( [Language] => Array ( [0] => Array ( [Name] => english [Type] => Published ) [1] => Array ( [Name] => english [Type] => Original Language ) [2] => Array ( [Name] => english [Type] => Unknown ) ) ) [ListPrice] => Array ( **[Amount] => 21.00** [CurrencyCode] => USD ) [Manufacturer] => Hyperion [ManufacturerMaximumAge] => 1188.0 [ManufacturerMinimumAge] => 156.0 [NumberOfItems] => 1 [NumberOfPages] => 110 [PackageDimensions] => Array ( [Height] => 0.65 [Length] => 8.60 [Width] => 5.65 [Weight] => 0.58 ) [PackageQuantity] => 1 [PartNumber] => 9780786866021 [ProductGroup] => Book [ProductTypeName] => ABIS_BOOK [PublicationDate] => 2000-03-08 [Publisher] => Hyperion [ReleaseDate] => 2000-03-08 [SmallImage] => Array ( [URL] => http://ecx.images-amazon.com/images/I/51cHo55tbOL._SL75_.jpg [Height] => 75 [Width] => 47 ) [Studio] => Hyperion [Title] => Fish: A Proven Way to Boost Morale and Improve Results ) ) [Relationships] => Array ( ) [SalesRankings] => Array ( [SalesRank] => Array ( [0] => Array ( [ProductCategoryId] => book_display_on_website [Rank] => 4629 ) [1] => Array ( [ProductCategoryId] => 1043856 [Rank] => 2 ) [2] => Array ( [ProductCategoryId] => 2635 [Rank] => 7 ) [3] => Array ( [ProductCategoryId] => 2637 [Rank] => 18 ) ) ) ) [1] ...
</code>```

I am trying to access the amount part of the array, as this is the price of the object. Eventually, I will need to access the amount of each product and so a loop will likely come into play, but right now i cannot even access one products sales amount.

Here is the code I have been trying

```<code>$value = $array->ListMatchingProductsResult->Products->Product[0]->ListPrice->Amount;
print_r($value);
</code>```

And it is not working. Even calling print_r on $array->ListMatchingProductsResult is not printing an array.

Any help is greatly appreciated!

Thanks,

Matt

答:
You are almost there. Whatever method you are using to convert the XML to a PHP array however, does just that: It creates an associative array of things, not an object. That is why you cannot access it through the ->element operator, but need to use array indexes ['element']

```<code>$value = $array['ListMatchingProductsResult']['Products']['Product'][0]['ListPrice']['Amount'];
</code>```

If you're ever wondering why you're not getting something back, you can successily shorten above expresion until you do. So if a print_r(...) on above expression returns nothing, just remove one square bracket at a time from that print_r until you do get something back. You then know that the last bracket you removed was the culprit.

```<code>Array (
[ListMatchingProductsResult] => Array (
    [Products] => Array (
        [Product] => Array (
            [0] => Array (
                 [Identifiers] => Array (
                     [MarketplaceASIN] => Array (
                          [MarketplaceId] => ATVPDKIKX0DER
                          [ASIN] => 0786866020
                      )
                  )
                 [AttributeSets] => Array (
                     [ItemAttributes] => Array (
                          [Author] => Array (
                               [0] => Stephen C. Lundin
                               [1] => Harry Paul
                               [2] => John Christensen
                          )
                          [Binding] => Hardcover
                          [Brand] => Hyperion
                          [Color] => White
                          [Creator] => Ken Blanchard
                          [Edition] => 1
                          [Feature] => Great product!
                          [ItemDimensions] => Array (
                              [Height] => 8.25
                              [Length] => 5.50
                              [Width] => 0.00
                              [Weight] => 0.54
                          )
                          [IsAdultProduct] => false
                          [Label] => Hyperion
                          [Languages] => Array (
                              [Language] => Array (
                                  [0] => Array (
                                       [Name] => english
                                       [Type] => Published
                                  )
                                  [1] => Array (
                                       [Name] => english
                                       [Type] => Original Language
                                  )
                                  [2] => Array (
                                       [Name] => english
                                       [Type] => Unknown
                                  )
                              )
                          )
                          [ListPrice] => Array (
                              [Amount] => 21.00
                              [CurrencyCode] => USD
                          )
                          [Manufacturer] => Hyperion
                 ...
</code>```

BTW, using ```...``` is helpful when trying to make sense of print_r() or var_dump().

P.S. You owe me a new space key.

Body:
I am Working with MWS for the first time and hoping to create a program that uses the ListMatchingProducts request to average out the prices of every product that matches a query.

It should be a very simple program, but I am having trouble retrieving data.

First I make the call and get amazon's xml sheet, Then I convert the xml to an array.

Print_R shows that the array looks something like this:

Array ( [ListMatchingProductsResult] => Array ( [Products] => Array ( [Product] => Array ( [0] => Array ( [Identifiers] => Array ( [MarketplaceASIN] => Array ( [MarketplaceId] => ATVPDKIKX0DER [ASIN] => 0786866020 ) ) [AttributeSets] => Array ( [ItemAttributes] => Array ( [Author] => Array ( [0] => Stephen C. Lundin [1] => Harry Paul [2] => John Christensen ) [Binding] => Hardcover [Brand] => Hyperion [Color] => White [Creator] => Ken Blanchard [Edition] => 1 [Feature] => Great product! [ItemDimensions] => Array ( [Height] => 8.25 [Length] => 5.50 [Width] => 0.00 [Weight] => 0.54 ) [IsAdultProduct] => false [Label] => Hyperion [Languages] => Array ( [Language] => Array ( [0] => Array ( [Name] => english [Type] => Published ) [1] => Array ( [Name] => english [Type] => Original Language ) [2] => Array ( [Name] => english [Type] => Unknown ) ) ) [ListPrice] => Array ( **[Amount] => 21.00** [CurrencyCode] => USD ) [Manufacturer] => Hyperion [ManufacturerMaximumAge] => 1188.0 [ManufacturerMinimumAge] => 156.0 [NumberOfItems] => 1 [NumberOfPages] => 110 [PackageDimensions] => Array ( [Height] => 0.65 [Length] => 8.60 [Width] => 5.65 [Weight] => 0.58 ) [PackageQuantity] => 1 [PartNumber] => 9780786866021 [ProductGroup] => Book [ProductTypeName] => ABIS_BOOK [PublicationDate] => 2000-03-08 [Publisher] => Hyperion [ReleaseDate] => 2000-03-08 [SmallImage] => Array ( [URL] => http://ecx.images-amazon.com/images/I/51cHo55tbOL._SL75_.jpg [Height] => 75 [Width] => 47 ) [Studio] => Hyperion [Title] => Fish: A Proven Way to Boost Morale and Improve Results ) ) [Relationships] => Array ( ) [SalesRankings] => Array ( [SalesRank] => Array ( [0] => Array ( [ProductCategoryId] => book_display_on_website [Rank] => 4629 ) [1] => Array ( [ProductCategoryId] => 1043856 [Rank] => 2 ) [2] => Array ( [ProductCategoryId] => 2635 [Rank] => 7 ) [3] => Array ( [ProductCategoryId] => 2637 [Rank] => 18 ) ) ) ) [1] ...

I am trying to access the amount part of the array, as this is the price of the object. Eventually, I will need to access the amount of each product and so a loop will likely come into play, but right now i cannot even access one products sales amount.

Here is the code I have been trying

$value = $array->ListMatchingProductsResult->Products->Product[0]->ListPrice->Amount;
print_r($value);

And it is not working. Even calling print_r on $array->ListMatchingProductsResult is not printing an array.

Any help is greatly appreciated!

Thanks,

Matt

Body:
You are almost there. Whatever method you are using to convert the XML to a PHP array however, does just that: It creates an associative array of things, not an object. That is why you cannot access it through the ->element operator, but need to use array indexes ['element']

$value = $array['ListMatchingProductsResult']['Products']['Product'][0]['ListPrice']['Amount'];

If you're ever wondering why you're not getting something back, you can successily shorten above expresion until you do. So if a print_r(...) on above expression returns nothing, just remove one square bracket at a time from that print_r until you do get something back. You then know that the last bracket you removed was the culprit.

Array (
[ListMatchingProductsResult] => Array (
    [Products] => Array (
        [Product] => Array (
            [0] => Array (
                 [Identifiers] => Array (
                     [MarketplaceASIN] => Array (
                          [MarketplaceId] => ATVPDKIKX0DER
                          [ASIN] => 0786866020
                      )
                  )
                 [AttributeSets] => Array (
                     [ItemAttributes] => Array (
                          [Author] => Array (
                               [0] => Stephen C. Lundin
                               [1] => Harry Paul
                               [2] => John Christensen
                          )
                          [Binding] => Hardcover
                          [Brand] => Hyperion
                          [Color] => White
                          [Creator] => Ken Blanchard
                          [Edition] => 1
                          [Feature] => Great product!
                          [ItemDimensions] => Array (
                              [Height] => 8.25
                              [Length] => 5.50
                              [Width] => 0.00
                              [Weight] => 0.54
                          )
                          [IsAdultProduct] => false
                          [Label] => Hyperion
                          [Languages] => Array (
                              [Language] => Array (
                                  [0] => Array (
                                       [Name] => english
                                       [Type] => Published
                                  )
                                  [1] => Array (
                                       [Name] => english
                                       [Type] => Original Language
                                  )
                                  [2] => Array (
                                       [Name] => english
                                       [Type] => Unknown
                                  )
                              )
                          )
                          [ListPrice] => Array (
                              [Amount] => 21.00
                              [CurrencyCode] => USD
                          )
                          [Manufacturer] => Hyperion
                 ...

BTW, using <pre>...</pre> is helpful when trying to make sense of print_r() or var_dump().

P.S. You owe me a new space key.


问:
3D Biplot in plotly - R
I want to build a 3D PCA bi-plot using plotly package because the graph is nice and interactive in html format (something that I need).

My difficulty is to add the loading. I want the loading to be presented as straight lines from the point (0,0,0) (i.e. the equivalent to 2D biplots)

So all in all I don't know how to add straight lines starting from the centre of the 3D graph.

I have calculated the scores and loading using the PCA function;

```<code>pca1 <- PCA (dat1, graph = F)
</code>```

for scores:

```<code>ind1 <- pca1$ind$coord[,1:3]
x <- ind1[,1] ; y <- ind1[,2] ; z <- ind1[,3]
</code>```

for loadings:

```<code>var1 <- pca1$var$coord[,1:3]
xl <- var1[,1] ; yl <- var1[,2] ; zl <- var1[,3]
</code>```

and using the code bellow the 3D score plot is generated;

```<code>p <- plot_ly( x=x, y=y, z=z,
 marker = list(opacity = 0.7, color=y  , colorscale = c('#FFE1A1', '#683531'), showscale = F)) %>%
  layout(title = "3D Prefmap",
         scene = list(
           xaxis = list(title = "PC 1"),
           yaxis = list(title = "PC 2"),
           zaxis = list(title = "PC 3")))
</code>```

答:
Here are some ideas that could be useful for the development of a 3D biplot.

```<code># Data generating process
library(MASS)
set.seed(6543)
n <- 500
mu <- c(1,-2,3,-1,3,4)
Sigma <- diag(rep(1,length(mu)))
Sigma[3,1] <- Sigma[1,3] <- 0.1
Sigma[4,6] <- Sigma[6,4] <- 0.1
X <- as.data.frame(mvrnorm(n, mu=mu, Sigma=Sigma))

# PCA
pca <- princomp(X, scores=T, cor=T)

# Scores
scores <- pca$scores
x <- scores[,1]
y <- scores[,2]
z <- scores[,3]

# Loadings
loads <- pca$loadings

# Scale factor for loadings
scale.loads <- 5

# 3D plot
library(plotly)
p <- plot_ly() %>%
  add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="markers",
            marker = list(color=y,
               colorscale = c("#FFE1A1", "#683531"),
               opacity = 0.7))

for (k in 1:nrow(loads)) {
   x <- c(0, loads[k,1])*scale.loads
   y <- c(0, loads[k,2])*scale.loads
   z <- c(0, loads[k,3])*scale.loads
   p <- p %>% add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="lines",
            line = list(width=8),
            opacity = 1)
}
print(p)
</code>```

Title: 3D Biplot in plotly - R

Body:
I want to build a 3D PCA bi-plot using plotly package because the graph is nice and interactive in html format (something that I need).

My difficulty is to add the loading. I want the loading to be presented as straight lines from the point (0,0,0) (i.e. the equivalent to 2D biplots)

So all in all I don't know how to add straight lines starting from the centre of the 3D graph.

I have calculated the scores and loading using the PCA function;

pca1 <- PCA (dat1, graph = F)

for scores:

ind1 <- pca1$ind$coord[,1:3]
x <- ind1[,1] ; y <- ind1[,2] ; z <- ind1[,3]

for loadings:

var1 <- pca1$var$coord[,1:3]
xl <- var1[,1] ; yl <- var1[,2] ; zl <- var1[,3]

and using the code bellow the 3D score plot is generated;

p <- plot_ly( x=x, y=y, z=z,
 marker = list(opacity = 0.7, color=y  , colorscale = c('#FFE1A1', '#683531'), showscale = F)) %>%
  layout(title = "3D Prefmap",
         scene = list(
           xaxis = list(title = "PC 1"),
           yaxis = list(title = "PC 2"),
           zaxis = list(title = "PC 3")))

Body:
Here are some ideas that could be useful for the development of a 3D biplot.

# Data generating process
library(MASS)
set.seed(6543)
n <- 500
mu <- c(1,-2,3,-1,3,4)
Sigma <- diag(rep(1,length(mu)))
Sigma[3,1] <- Sigma[1,3] <- 0.1
Sigma[4,6] <- Sigma[6,4] <- 0.1
X <- as.data.frame(mvrnorm(n, mu=mu, Sigma=Sigma))

# PCA
pca <- princomp(X, scores=T, cor=T)

# Scores
scores <- pca$scores
x <- scores[,1]
y <- scores[,2]
z <- scores[,3]

# Loadings
loads <- pca$loadings

# Scale factor for loadings
scale.loads <- 5

# 3D plot
library(plotly)
p <- plot_ly() %>%
  add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="markers",
            marker = list(color=y,
               colorscale = c("#FFE1A1", "#683531"),
               opacity = 0.7))

for (k in 1:nrow(loads)) {
   x <- c(0, loads[k,1])*scale.loads
   y <- c(0, loads[k,2])*scale.loads
   z <- c(0, loads[k,3])*scale.loads
   p <- p %>% add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="lines",
            line = list(width=8),
            opacity = 1)
}
print(p)


问:
Phonegap app stuck on splash screen for Apple reviewers
I've published around a couple dozen apps to the Apple App Store over the last couple of years with no problems whatsoever. Recently, an app just got rejected due to

"We discovered one or more bugs in your app when reviewed on iPhone and iPad running iOS 10.3.2 on Wi-Fi connected to an IPv6 network.
We were not able to fully load your app content after launch.
Please see attached screenshots for details.".

The attached screenshots were just the splash screen of the app. So it seems the app is getting stuck on the splash screen for the reviewers.

I tested the same binary (using TestFlight) on my iPhone running the same version of iOS they were using and it worked successfully. However, I was testing on an ipv4 network. I find it hard to believe that them testing on an ipv6 network would cause the PhoneGap app to hang on the splash screen. Especially considering this has never happened before.

Is it possible this was just some anomaly when Apple happened to test this app? Or has anyone else even encountered something like this where they were unable to reproduce what the reviewers were seeing?

答: Apple approved the app after we responded to them stating we followed https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html to no avail and that the bug was likely due to something in their testing environment. </p>


问:
Finding memory violations/leaks
I have an application developed in VC 2008 (C++) which uses axis dlls, which use openssl dlls. And someone in the chain corrupts heap - a situation which ends up giving me "memory access violation" in my application in places where violation shouldn't/couldn't happen. So, someone in the chain axis-ssl corrupts something, but I cannot find who or what.

I tried using DevPartner's tool for memory leaks, but it finds no leaks - no anything.

How should I approach this problem? I looked over axis and ssl documentation a number of times, and implemented and checked all possible memory management issues and fixes, but to no avail.

Thank you very much!
Marin

答:
May be this MSDN article might have the answers you are looking for:
Finding a Memory Leak

Also you could try this LeakDiag tool. Not sure as to why there is no reference to it in MSDN?!?!? But there is a neat article in Codeproject.com

ContentLicense: CC BY-SA 2.5

Title: Finding memory violations/leaks


问:
React & Jest, how to test changing state and checking for another component
React - Test Utilities Docs

I have a Login component which will display a Notification component if this.state.error is true.

I'm now writing a Jest test to test this.

```<code>import React from 'react'
import ReactTestUtils from 'react-dom/test-utils';
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Login from './Login'
import Notification from '../common/Notification'

describe('<Login /> component', () => {
    it('should render', () => {
        const loginComponent = shallow(<Login />);
        const tree = toJson(loginComponent);
        expect(tree).toMatchSnapshot();
    });

    it('should contains the words "Forgot Password"', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.contains('Forgot Password')).toBe(true);
    });

    // This test fails
    it('should render the Notification component if state.error is true', () => {
        const loginComponent = ReactTestUtils.renderIntoDocument(
            <Login />
        );

        const notificationComponent = ReactTestUtils.renderIntoDocument(
            <Notification />
        );

        loginComponent.setState({
            error: true
        }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));
    });
});
</code>```

However currently the test is failing, and I'm not sure why

In the last part of my code I've also tried this to no avail

```<code>loginComponent.setState({
        error: true
    }, expect(ReactTestUtils. isElement(notificationComponent)).toBe(true));
</code>```

https://facebook.github.io/react/docs/test-utils.html

The render() of my Login component

```<code>render() {
    const usernameError = this.state.username.error;
    const error = this.state.error;
    const errorMsg = this.state.errorMsg;

    return (
        <div className="app-bg">
            { error &&
                <Notification message={ errorMsg } closeMsg={ this.closeMessage }/>
            }
            <section id="auth-section">
                <header>
                    <img src="static/imgs/logo.png"/>
                    <h1>tagline</h1>
                </header>
</code>```

Also tried this method for testing for the Notification component after setting state.error to true

```<code>it('should render the Notification component if state.error is true', () => {
    const loginComponent = ReactTestUtils.renderIntoDocument(
        <Login />
    );

    const notificationComponent = ReactTestUtils.renderIntoDocument(
        <Notification />
    );

    // loginComponent.setState({
    //  error: true
    // }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));

    const checkForNotification = () => {
        const login = shallow(<Login />);
        expect(login.find(Notification).length).toBe(1);
    };

    loginComponent.setState({
        error: true
    }, checkForNotification());
});
</code>```

But that test also failed.

Also tried const login = mount(<Login />);

Anyone else running into a problem using Jest and the React Test Utilities?

答:
Figured it out! Did not need React Test Utilities

```<code>it('should render the Notification component if state.error is true', () => {
    const loginComponent = shallow(<Login />);
    loginComponent.setState({ error: true });
    expect(loginComponent.find(Notification).length).toBe(1);
});
</code>```

This will set the state of error to true in the Login component, then check if the Login component contains the Notification component.

ContentLicense: CC BY-SA 4.0

Body:
React - Test Utilities Docs

I have a Login component which will display a Notification component if this.state.error is true.

I'm now writing a Jest test to test this.

import React from 'react'
import ReactTestUtils from 'react-dom/test-utils';
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Login from './Login'
import Notification from '../common/Notification'

describe('<Login /> component', () => {
    it('should render', () => {
        const loginComponent = shallow(<Login />);
        const tree = toJson(loginComponent);
        expect(tree).toMatchSnapshot();
    });

    it('should contains the words "Forgot Password"', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.contains('Forgot Password')).toBe(true);
    });

    // This test fails
    it('should render the Notification component if state.error is true', () => {
        const loginComponent = ReactTestUtils.renderIntoDocument(
            <Login />
        );

        const notificationComponent = ReactTestUtils.renderIntoDocument(
            <Notification />
        );

        loginComponent.setState({
            error: true
        }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));
    });
});

However currently the test is failing, and I'm not sure why

In the last part of my code I've also tried this to no avail

loginComponent.setState({
        error: true
    }, expect(ReactTestUtils. isElement(notificationComponent)).toBe(true));

https://facebook.github.io/react/docs/test-utils.html

The render() of my Login component

render() {
    const usernameError = this.state.username.error;
    const error = this.state.error;
    const errorMsg = this.state.errorMsg;

    return (

            { error &&
                <Notification message={ errorMsg } closeMsg={ this.closeMessage }/>
            }

tagline

Also tried this method for testing for the Notification component after setting state.error to true

it('should render the Notification component if state.error is true', () => {
    const loginComponent = ReactTestUtils.renderIntoDocument(
        <Login />
    );

    const notificationComponent = ReactTestUtils.renderIntoDocument(
        <Notification />
    );

    // loginComponent.setState({
    //  error: true
    // }, expect(ReactTestUtils.isDOMComponent(notificationComponent)).toBe(true));

    const checkForNotification = () => {
        const login = shallow(<Login />);
        expect(login.find(Notification).length).toBe(1);
    };

    loginComponent.setState({
        error: true
    }, checkForNotification());
});

But that test also failed.

Also tried const login = mount(<Login />);

Anyone else running into a problem using Jest and the React Test Utilities?

Body:
Figured it out! Did not need React Test Utilities

it('should render the Notification component if state.error is true', () => {
    const loginComponent = shallow(<Login />);
    loginComponent.setState({ error: true });
    expect(loginComponent.find(Notification).length).toBe(1);
});

This will set the state of error to true in the Login component, then check if the Login component contains the Notification component.


问:
dynamic dplyr column name calculation
I have the following code.

colName is passed in. I've been trying to get it to be evaluated as the value of colName but have not had much success. I've tried "eval", "setNames", etc. Using the "_", still has not provided success.

Essentially, if my colName = "MyCol", I want the dplyr chain to execute as if the last line read:

mutate(MyCol = ifelse(is.na(MyCol), "BLANK", MyCol))

```<code>makeSummaryTable <- function(colName,originalData){
  result <- originalData %>%
    group_by_(colName) %>%
    summarise(numObs = n()) %>%
    ungroup() %>%
    arrange(desc(numObs)) %>%
    rowwise() %>%
    mutate_(colName = ifelse(is.na(colName), "BLANK",colName))
  return(result)
}
</code>```

答:
Here's how to do it with dplyr 0.6.0 using the new tidyeval approach to non-standard evaluation. (I'm not sure if it's even possible to do with standard evaluation, at least in a straightforward manner):

library(dplyr)

makeSummaryTable <- function(colName, originalData){

  colName <- enquo(colName)

  originalData %>%
    count(!!colName) %>%
    arrange(desc(n)) %>%
    mutate(
      old_col = !!colName,
      !!quo_name(colName) := if_else(is.na(!!colName), "BLANK",!!colName)
      )
}

makeSummaryTable(hair_color, starwars)
#> # A tibble: 13 x 3
#>       hair_color     n       old_col
#>            <chr> <int>         <chr>
#>  1          none    37          none
#>  2         brown    18         brown
#>  3         black    13         black
#>  4         BLANK     5          <NA>
#>  5         white     4         white
#>  6         blond     3         blond
#>  7        auburn     1        auburn
#>  8  auburn, grey     1  auburn, grey
#>  9 auburn, white     1 auburn, white
#> 10        blonde     1        blonde
#> 11   brown, grey     1   brown, grey
#> 12          grey     1          grey
#> 13       unknown     1       unknown
```

enquo turns the unquoted column name into some fancy object called a quosure. !! then unquotes the quosure so that it can get evaluated as if it would be typed directly in the function. For a more in-depth and accurate explanation, see Hadley's "Programming with dplyr".

EDIT: I realized that the original question was to name the new column with the user-supplied value of colName and not just colName so I updated my answer. To accomplish that, the quosure needs to be turned into a string (or label) using quo_name. Then, it can be "unquoted" using !! just as a regular quosure would be. The only caveat is that since R can't make head or tails of the expression mutate(!!foo = bar), tidyeval introduces the new definition operator := (which might be familiar to users from data.table where it has a somewhat different use). Unlike the traditional assignment operator =, the := operator allows unquoting on both the right-hand and left-hand side.

(updated the answer to use a dataframe that has NA in one of its rows, to illustrate that the last mutate works. I also used count instead of group by + summarize, and I dropped the unnecessary rowwise.)

Title: dynamic dplyr column name calculation

Body:
I have the following code.

colName is passed in. I've been trying to get it to be evaluated as the value of colName but have not had much success. I've tried "eval", "setNames", etc. Using the "_", still has not provided success.

Essentially, if my colName = "MyCol", I want the dplyr chain to execute as if the last line read:

mutate(MyCol = ifelse(is.na(MyCol), "BLANK", MyCol))

makeSummaryTable <- function(colName,originalData){
  result <- originalData %>%
    group_by_(colName) %>%
    summarise(numObs = n()) %>%
    ungroup() %>%
    arrange(desc(numObs)) %>%
    rowwise() %>%
    mutate_(colName = ifelse(is.na(colName), "BLANK",colName))
  return(result)
}

Body:
Here's how to do it with dplyr 0.6.0 using the new tidyeval approach to non-standard evaluation. (I'm not sure if it's even possible to do with standard evaluation, at least in a straightforward manner):

library(dplyr)

makeSummaryTable <- function(colName, originalData){

  colName <- enquo(colName)

  originalData %>%
    count(!!colName) %>%
    arrange(desc(n)) %>%
    mutate(
      old_col = !!colName,
      !!quo_name(colName) := if_else(is.na(!!colName), "BLANK",!!colName)
      )
}

makeSummaryTable(hair_color, starwars)
#> # A tibble: 13 x 3
#>       hair_color     n       old_col
#>            <chr> <int>         <chr>
#>  1          none    37          none
#>  2         brown    18         brown
#>  3         black    13         black
#>  4         BLANK     5          <NA>
#>  5         white     4         white
#>  6         blond     3         blond
#>  7        auburn     1        auburn
#>  8  auburn, grey     1  auburn, grey
#>  9 auburn, white     1 auburn, white
#> 10        blonde     1        blonde
#> 11   brown, grey     1   brown, grey
#> 12          grey     1          grey
#> 13       unknown     1       unknown

enquo turns the unquoted column name into some fancy object called a quosure. !! then unquotes the quosure so that it can get evaluated as if it would be typed directly in the function. For a more in-depth and accurate explanation, see Hadley's "Programming with dplyr".

EDIT: I realized that the original question was to name the new column with the user-supplied value of colName and not just colName so I updated my answer. To accomplish that, the quosure needs to be turned into a string (or label) using quo_name. Then, it can be "unquoted" using !! just as a regular quosure would be. The only caveat is that since R can't make head or tails of the expression mutate(!!foo = bar), tidyeval introduces the new definition operator := (which might be familiar to users from data.table where it has a somewhat different use). Unlike the traditional assignment operator =, the := operator allows unquoting on both the right-hand and left-hand side.

(updated the answer to use a dataframe that has NA in one of its rows, to illustrate that the last mutate works. I also used count instead of group by + summarize, and I dropped the unnecessary rowwise.)


问:
Laravel 5.3 - TokenMismatchException in VerifyCsrfToken.php line 68:
When I log in to my app, and immediately go back when I enter it, and then try to log out, I get the error from the title, how can I fix that?</p>

答:
To solve this add those two lines in the route file (e.g web.php)

```<code>Route::get('/', 'HomeController@index');// so when you logged out it go back
Route::get('/home', 'HomeController@index');
</code>```

This solved the problem for me. Hope that help.

Body:
To solve this add those two lines in the route file (e.g web.php)

Route::get('/', 'HomeController@index');// so when you logged out it go back
Route::get('/home', 'HomeController@index');

This solved the problem for me. Hope that help.


问:
How to convert an input string to uppercase in c#
```<code>string choice = String.ToUpper(Console.ReadLine());
</code>```

I want to input a string and convert it to upper case. However, there's an error that states :

cannot convert from 'string' to System.Globalization.CultureInfo'

that appears when I hover over the Console.ReadLine(). Why doesn't this work , and what fixes are there? And is there another way to do this ?

答:
You can write :

string choice = Console.ReadLine().ToUpper();

Body:
string choice = String.ToUpper(Console.ReadLine());

I want to input a string and convert it to upper case. However, there's an error that states :

cannot convert from 'string' to System.Globalization.CultureInfo'

that appears when I hover over the Console.ReadLine(). Why doesn't this work , and what fixes are there? And is there another way to do this ?


问:
NVBLAS silently fails for semi-large matrix multiplication
I followed the instructions here to run octave with nvblas.  I have CUDA toolkit 7.5 installed and a tesla k40c GPU.  To start octave with nvblas, I used LD_PRELOAD=libnvblas.so octave.  I then ran the following simple code:

```<code>N = 256
A = rand(N,N)
B = rand(N,N)
A*B
</code>```

which produces a matrix with reasonable values.  However, if I increase N to 512, or any number over 512, I get all zeros (or very small numbers) back as a result.

If I use OpenBLAS this does not happen.  The matrices should be small enough that they fit in the card's RAM (12GB).  Any idea why this might happen?

Note:  If I make A and B identity matrices this does not happen, but it still happens with A = B = ones(N,N).

答:
Sorry the question is somewhat stale, but I tried it on an Amazon AWS EC2 p2.xlarge instance with a k80 gpu and it seems to have worked.

I was getting similar results to you (lots of zeros) when I had the default "NVBLAS_GPU_LIST 0 1" setting in nvblas.conf, which seems to refer to two GPUs, so I changed it to just one and it worked.  Complete file below:

```<code>#Put here the CPU BLAS fallback Library of your choice
NVBLAS_CPU_BLAS_LIB libopenblas.so

# Specify which output log file (default is stderr)
NVBLAS_LOGFILE nvblas.log

# List of GPU devices Id to participate to the computation
# By default if no GPU are listed, only device 0 will be used
NVBLAS_GPU_LIST 0
NVBLAS_AUTOPIN_MEM_ENABLED
</code>```

Program (t1.m) slightly modified from the NVidia link, to count the number of non-zeros in the output matrix:

```<code>N = 16384;

# from the original NVidia example:
#A = single(rand(N,N));
#B = single(rand(N,N));

# double precision seems to work fine (not checked in detail)
A = rand(N,N);
B = rand(N,N);

start = clock();
C = A * B;
elapsedTime = etime(clock(), start);
disp(elapsedTime);
gFlops = 2*N*N*N/(elapsedTime * 1e+9);
disp(gFlops);

disp("number of elements >0:")
disp(sum(sum(C > 0)));

disp("Should be:")
disp(N*N)
</code>```

FYI Here is the nvidia-smi output while it was running as above (it peaked at 172MiB usage with N=16384):

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.51                 Driver Version: 375.51                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           Off  | 0000:00:1E.0     Off |                    0 |
| N/A   44C    P0    80W / 149W |     80MiB / 11439MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0     21080    C   /usr/bin/octave-cli                             78MiB |
+-----------------------------------------------------------------------------+
</code>```

Here are the nvidia & cuda files I'd previously installed:

```<code>cuda-repo-ubuntu1604-8-0-local-ga2_8.0.61-1_amd64-deb
libcudnn5-dev_5.1.10-1+cuda8.0_amd64.deb
libcudnn5_5.1.10-1+cuda8.0_amd64.deb
nvidia-driver-local-repo-ubuntu1604_375.51-1_amd64.deb
</code>```

I seem to get a speed up of about 8.6, with about 55 gflops from plain octave, and 478 from the GPU version.

Body:
I followed the instructions here to run octave with nvblas.  I have CUDA toolkit 7.5 installed and a tesla k40c GPU.  To start octave with nvblas, I used LD_PRELOAD=libnvblas.so octave.  I then ran the following simple code:

N = 256
A = rand(N,N)
B = rand(N,N)
A*B

which produces a matrix with reasonable values.  However, if I increase N to 512, or any number over 512, I get all zeros (or very small numbers) back as a result.

If I use OpenBLAS this does not happen.  The matrices should be small enough that they fit in the card's RAM (12GB).  Any idea why this might happen?

Note:  If I make A and B identity matrices this does not happen, but it still happens with A = B = ones(N,N).

Body:
Sorry the question is somewhat stale, but I tried it on an Amazon AWS EC2 p2.xlarge instance with a k80 gpu and it seems to have worked.

I was getting similar results to you (lots of zeros) when I had the default "NVBLAS_GPU_LIST 0 1" setting in nvblas.conf, which seems to refer to two GPUs, so I changed it to just one and it worked.  Complete file below:

#Put here the CPU BLAS fallback Library of your choice
NVBLAS_CPU_BLAS_LIB libopenblas.so

# Specify which output log file (default is stderr)
NVBLAS_LOGFILE nvblas.log

# List of GPU devices Id to participate to the computation
# By default if no GPU are listed, only device 0 will be used
NVBLAS_GPU_LIST 0
NVBLAS_AUTOPIN_MEM_ENABLED

Program (t1.m) slightly modified from the NVidia link, to count the number of non-zeros in the output matrix:

N = 16384;

# from the original NVidia example:
#A = single(rand(N,N));
#B = single(rand(N,N));

# double precision seems to work fine (not checked in detail)
A = rand(N,N);
B = rand(N,N);

start = clock();
C = A * B;
elapsedTime = etime(clock(), start);
disp(elapsedTime);
gFlops = 2*N*N*N/(elapsedTime * 1e+9);
disp(gFlops);

disp("number of elements >0:")
disp(sum(sum(C > 0)));

disp("Should be:")
disp(N*N)

FYI Here is the nvidia-smi output while it was running as above (it peaked at 172MiB usage with N=16384):

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.51                 Driver Version: 375.51                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           Off  | 0000:00:1E.0     Off |                    0 |
| N/A   44C    P0    80W / 149W |     80MiB / 11439MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0     21080    C   /usr/bin/octave-cli                             78MiB |
+-----------------------------------------------------------------------------+

Here are the nvidia & cuda files I'd previously installed:

cuda-repo-ubuntu1604-8-0-local-ga2_8.0.61-1_amd64-deb
libcudnn5-dev_5.1.10-1+cuda8.0_amd64.deb
libcudnn5_5.1.10-1+cuda8.0_amd64.deb
nvidia-driver-local-repo-ubuntu1604_375.51-1_amd64.deb

I seem to get a speed up of about 8.6, with about 55 gflops from plain octave, and 478 from the GPU version.


问:
X-RequestDigest: Getting error while running recorded web test of sharepoint page
I have recorded and replayed my sharepoint webtest successfully but after a week or two, I get '403 FORBIDDEN' error when I replay it in Visual Studio.

I understand that X-RequestDigest has expired certificate/token details and needs to be updated for every run in my request.
However, I'm unable to find preceding X-RequestDigest header value in my recorded web test.

I'm able to extract from response header but I need to bind the value to request prior to response?
Can someone give me a code/method to extract X-RequestDigest header value from Sharepoint page and use it in my Visual Studio Webtest?

答:
Answer to your question may vary depends on the version of SharePoint you use. Typically the x-requestdigest value can be extracted from  _api/contextinfo that appears just before the request that you need to parameterize. This is a json response body that looks as follows:

{"d":{"GetContextWebInformation":{"__metadata":{"type":"SP.ContextWebInformation"},"FormDigestTimeoutSeconds":1800,"FormDigestValue":"0x258D3700E8E516F8E320BAF6FEFDDC271C54C8C44A1E5DBE8B9CBE6ED2A77EDCCF88CAA901790245D3E9B518FB31AA9B345B0E232C93CD39D4E12999499B7414,6
  Jun 2017 10:26:21
  -0000","LibraryVersion":"16.0.5521.1202","SiteFullUrl":"https://xxx.sharepoint.com","SupportedSchemaVersions":{"__metadata":{"type":"Collection(Edm.String)"},"results":["14.0.0.0","15.0.0.0"]},"WebFullUrl":"https://xxx.sharepoint.com/Sample_Site"}}}

From here you need to extract the “FormDigestValue” value with an Extract Text extractor. Set the Starts With: "FormDigestValue":"  Ends With: “

If you wish to use Fiddler as AdrianHHH suggested, you may also want to use our free StresStimulus add-on that will create all extractors and parameter automatically as described here http://www.stresstimulus.com/blog/post/visual-studio-load-testing-fixing-playback-errors-in-web-tests. You just need to record the test scenario, save it as a webtest and open in Visual Studio. That way, you don’t have to create any extractors and parameters manually.


问:
How to run a whole Java file added as a snippet in JShell?
I tried installing JDK 9 Early access version 172 to play around with JShell.
When I tried to open a simple java file and execute it after adding it as a snippet, it just showed modified class Test and increased the snippet number. Can you please help me realize where I went wrong?</p>

```<code>|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell> /open G:\kavitha\Test.java

jshell> /list

   1 : public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
       }

jshell> /1
public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
}
|  modified class Test

jshell> /list

   2 : public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
       }
</code>```

答:
/open only loads the file, after that you have to tell jshell what you want to execute.

Example:

```<code>jshell> /open Test.java

jshell> /list

   1 : class Test {
           public static void main(String[] args) {
               System.out.println("Hello Kavitha");
           }
           int rollDice() {
               return 1 + (int)(6 * Math.random());
           }
       }

jshell> Test.main(new String[0])
Hello Kavitha

jshell> new Test().rollDice()
$3 ==> 3
</code>```

Here I have executed main method, but I can also use the loaded class as I want, create a new instance, invoke a method, etc.

Shortcut /<id> re-runs snippet with that id. In your case, snippet 1 only loads the class and executes nothing, so by executing /1 you re-loaded the same class, again without executing it.

After running my example above, /2 would re-run the main method, and /3 would re-roll the dice:

```<code>jshell> /3
new Test().rollDice()
$4 ==> 1

jshell> /3
new Test().rollDice()
$5 ==> 6

jshell> /3
new Test().rollDice()
$6 ==> 2
</code>```

Addendum: /open & compilation, class loading, class initialization

(Trying to clarify why /open did not execute the main method of your class, and to show that it makes sense)

When you /open a file, JShell will add the content of the file as if you typed it into the shell.

It will then compile the snippet(s), but it will not initialize classes if there were any.

(I'm not sure whether or not if will load classes, which is the step before initialization, it's difficult to tell, see this post that was an attempt to explore the internals of JShell, it shows how class names in JShell are translated for the user, and failed attempts to see the list of loaded classes -- but that matters less than compilation & initialization)

If I open SnippetWithError.txt which contains the following:

```<code>System.out.println("Hey")
class Foo { int n=33; } bar
</code>```

(yes it does not need to be a java file, it's really a bunch of text you include in the shell for evaluation)

```<code>jshell> /open SnippetWithError.txt
Hey
|  Error:
|  cannot find symbol
|    symbol:   variable bar
|   bar
|   ^-^
</code>```

See it printed "Hey", and it has included class Foo:

```<code>jshell> new Foo().n
$2 ==> 33
</code>```

So, JShell compiles when you /open, it executes the statements, but if some statements are class or method declarations, it does not execute those, it does not even initialize the classes.

See below how the imports are counted as separate statements in the history, then the class declaration is in its own statement (#3):

```<code>jshell> /open HasStaticInitBlock.java

jshell> /list

1 : import java.time.Duration;
2 : import java.time.Instant;
3 : class HasStaticInitBlock {
        static Instant t0 = Instant.now();
        static {
            System.out.println("Class initialized at " + t0);
        }
        static Duration timeSinceInit() {
            return Duration.between(t0, Instant.now());
        }
    }

jshell> HasStaticInitBlock.timeSinceInit()
Class initialized at 2017-06-07T06:49:06.746185Z
$4 ==> PT0.040414S

jshell> HasStaticInitBlock.timeSinceInit()
$5 ==> PT2.343019S
</code>```

Class initialization was only performed when needed.

Body:
I tried installing JDK 9 Early access version 172 to play around with JShell.
When I tried to open a simple java file and execute it after adding it as a snippet, it just showed modified class Test and increased the snippet number. Can you please help me realize where I went wrong?

|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell> /open G:\kavitha\Test.java

jshell> /list

   1 : public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
       }

jshell> /1
public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
}
|  modified class Test

jshell> /list

   2 : public class Test{
        public static void main(String[] args){
                 int i = 1;
                 int j = 2;
             System.out.println("Sum of 1 and 2 is : " + (i+j));
        }
       }

Body:
/open only loads the file, after that you have to tell jshell what you want to execute.

Example:

jshell> /open Test.java

jshell> /list

   1 : class Test {
           public static void main(String[] args) {
               System.out.println("Hello Kavitha");
           }
           int rollDice() {
               return 1 + (int)(6 * Math.random());
           }
       }

jshell> Test.main(new String[0])
Hello Kavitha

jshell> new Test().rollDice()
$3 ==> 3

Here I have executed main method, but I can also use the loaded class as I want, create a new instance, invoke a method, etc.

Shortcut /<id> re-runs snippet with that id. In your case, snippet 1 only loads the class and executes nothing, so by executing /1 you re-loaded the same class, again without executing it.

After running my example above, /2 would re-run the main method, and /3 would re-roll the dice:

jshell> /3
new Test().rollDice()
$4 ==> 1

jshell> /3
new Test().rollDice()
$5 ==> 6

jshell> /3
new Test().rollDice()
$6 ==> 2

Addendum: /open & compilation, class loading, class initialization

(Trying to clarify why /open did not execute the main method of your class, and to show that it makes sense)

When you /open a file, JShell will add the content of the file as if you typed it into the shell.

It will then compile the snippet(s), but it will not initialize classes if there were any.

(I'm not sure whether or not if will load classes, which is the step before initialization, it's difficult to tell, see this post that was an attempt to explore the internals of JShell, it shows how class names in JShell are translated for the user, and failed attempts to see the list of loaded classes -- but that matters less than compilation & initialization)

If I open SnippetWithError.txt which contains the following:

System.out.println("Hey")
class Foo { int n=33; } bar

(yes it does not need to be a java file, it's really a bunch of text you include in the shell for evaluation)

jshell> /open SnippetWithError.txt
Hey
|  Error:
|  cannot find symbol
|    symbol:   variable bar
|   bar
|   ^-^

See it printed "Hey", and it has included class Foo:

jshell> new Foo().n
$2 ==> 33

So, JShell compiles when you /open, it executes the statements, but if some statements are class or method declarations, it does not execute those, it does not even initialize the classes.

See below how the imports are counted as separate statements in the history, then the class declaration is in its own statement (#3):

jshell> /open HasStaticInitBlock.java

jshell> /list

1 : import java.time.Duration;
2 : import java.time.Instant;
3 : class HasStaticInitBlock {
        static Instant t0 = Instant.now();
        static {
            System.out.println("Class initialized at " + t0);
        }
        static Duration timeSinceInit() {
            return Duration.between(t0, Instant.now());
        }
    }

jshell> HasStaticInitBlock.timeSinceInit()
Class initialized at 2017-06-07T06:49:06.746185Z
$4 ==> PT0.040414S

jshell> HasStaticInitBlock.timeSinceInit()
$5 ==> PT2.343019S

Class initialization was only performed when needed.


问:
how to get list of points from kml layer android
i'm trying to get the coordinates of my kml layer in my android app, and i just cant seem to find how to do it.

i have this kml layer:

```<code>KmlLayer layer = new KmlLayer(mMap, R.raw.allowedarea, getApplicationContext());
</code>```

and i'm trying to get the Latitude and Longtitude list of his boundries points.

```<code>ArrayList<LatLnt> latlitArray = layer.soemthing();
</code>```

could find anything, please guys help.

答:
This will recursively access every placemark geometry inside the container. I'm not aware if the object obtained can actually be an instance of any other class or collection besides List and LatLng.  </p>

```<code>public void accessContainers(Iterable<KmlContainer> containers) {
    for(KmlContainer c : containers) {
        if(c.hasPlacemarks()) {
            for(KmlPlacemark p : c.getPlacemarks()) {
                KmlGeometry g = p.getGeometry();
                Object object = g.getGeometryObject();

                if(object instanceof LatLng) {
                    LatLng latlng = (LatLng)object;
                    //Do more stuff with the point
                }

                if(object instanceof List<?>) {
                    List<LatLng> list = (List<LatLng>)object;
                    //Do more stuff with the list of points
                }

                Log.d(TAG, g.getGeometryType() + ":" + object.toString());
            }
        }
        if(c.hasContainers()) {
            accessContainers(c.getContainers());
        }
    }
}
</code>```

Body:
i'm trying to get the coordinates of my kml layer in my android app, and i just cant seem to find how to do it.

i have this kml layer:

KmlLayer layer = new KmlLayer(mMap, R.raw.allowedarea, getApplicationContext());

and i'm trying to get the Latitude and Longtitude list of his boundries points.

ArrayList<LatLnt> latlitArray = layer.soemthing();

could find anything, please guys help.

Body:
This will recursively access every placemark geometry inside the container. I'm not aware if the object obtained can actually be an instance of any other class or collection besides List and LatLng.

public void accessContainers(Iterable<KmlContainer> containers) {
    for(KmlContainer c : containers) {
        if(c.hasPlacemarks()) {
            for(KmlPlacemark p : c.getPlacemarks()) {
                KmlGeometry g = p.getGeometry();
                Object object = g.getGeometryObject();

                if(object instanceof LatLng) {
                    LatLng latlng = (LatLng)object;
                    //Do more stuff with the point
                }

                if(object instanceof List<?>) {
                    List<LatLng> list = (List<LatLng>)object;
                    //Do more stuff with the list of points
                }

                Log.d(TAG, g.getGeometryType() + ":" + object.toString());
            }
        }
        if(c.hasContainers()) {
            accessContainers(c.getContainers());
        }
    }
}


问:
jquery to change swf
I want to be able to change the swf file showing on a page using the code below (with the comment turned into real code)

Is this possible??

jquery:

```<code>$("div.360container > p").click( function() {
    // show different swf by changing the value of the first param and src of the embed
});
</code>```

html:

```<code><div class="mycontainer" style='padding:2px;'>

  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="650" height="350">
    <param name="movie" value="/mySwf.swf" />
    <param name="quality" value="high" />
    <param name="wmode" value="opaque" />
    <embed src="/mySwf.swf" quality="high" wmode="opaque" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="650" height="350"></embed>
  </object>

  <p>click to change...</p>
</div>
</code>```

答:
Most reliable way to do that would be to set innerHTML of the element to your HTML. So, using jquery:</p>

```<code>$("div.360container > p").click( function() {
    // show different swf by changing the value of the first param and src of the embed
    $(".mycontainer").html("<object ....><param name='movie' value='" + movieUrl + "' />....");
});
</code>```

Title: jquery to change swf

Body:
I want to be able to change the swf file showing on a page using the code below (with the comment turned into real code)

Is this possible??

jquery:

$("div.360container > p").click( function() {
    // show different swf by changing the value of the first param and src of the embed
});

html:

  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="650" height="350">
    <param name="movie" value="/mySwf.swf" />
    <param name="quality" value="high" />
    <param name="wmode" value="opaque" />
    <embed src="/mySwf.swf" quality="high" wmode="opaque" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="650" height="350"></embed>
  </object>

click to change...

Body:
Most reliable way to do that would be to set innerHTML of the element to your HTML. So, using jquery:

$("div.360container > p").click( function() {
    // show different swf by changing the value of the first param and src of the embed
    $(".mycontainer").html("<object ....><param name='movie' value='" + movieUrl + "' />....");
});


问:
Set all back buttons like leftBarButtonItem with custom image
How do I set a custom image to all back buttons of view controllers pushed in a UINavigationController?

My issues are:

must look like leftBarButtonItem, position-wise (because the backBarButtonItem itself is too glued to the left and I can't seem to change it's horizontal alignment).

has to be on all back actions (instead of manually setting on each view controller).

having a method setCustomBackButton and calling it on each view controller is also not an option, I'm looking for something like UINavigationBar.appearance(), i.e., throughout the app.

Something like this:

But with the back action working without me manually setting the selector on each view controller.

UPDATE: In response to Joe's solution, I'm getting that error:

答:
```<code>UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backArrow")
</code>```

See Here: https://www.raywenderlich.com/108766/uiappearance-tutorial

Body:
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backArrow")

See Here: https://www.raywenderlich.com/108766/uiappearance-tutorial


问:
Django Cannot resolve keyword 'Word' into field. Choices are:
I have find similar errors on the forum but I don't see any mistakes in my code, and models and views are really not complicated.

```<code>class Word(models.Model):

    word_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)

class Explanation(models.Model):

    word_foid = models.ForeignKey(Word, on_delete=models.CASCADE)
    expl_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)
</code>```

So in my opinion Foreign Relationship should be fine. I don't have problems when I'm adding new data by admin panel. I used it in a view:

views.py:

```<code>def index(request):
    if request.method == 'POST':
        form = Search(request.POST)
        if form.is_valid():
            dane = form.cleaned_data
            tlumaczenie=Explanation.objects.filter(Word__word_text=dane['Searched_word'])
            print(tlumaczenie)
            return render(request,'explanation.html', {'dane':dane})
</code>```

But I'm still getting error:

django.core.exceptions.FieldError: Cannot resolve keyword 'Word' into field. Choices are: expl_text, id, modi_date, publ_date, user_crea, word_foid, word_foid_id

I don't understand why. It should send query like:

```<code>select e.* from word w join explanation e on w.word_id = e.word_foid where w.word_text = dane['Searched_word']
</code>```

and retrieve the data.

Any ideas why it's not working properly?

答:
Your foreign key field is called word_foid, not Word. The query should use that name like this

```<code>tlumaczenie = Explanation.objects.filter(word_foid__word_text=dane['Searched_word'])
</code>```

Body:
I have find similar errors on the forum but I don't see any mistakes in my code, and models and views are really not complicated.

class Word(models.Model):

    word_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)

class Explanation(models.Model):

    word_foid = models.ForeignKey(Word, on_delete=models.CASCADE)
    expl_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)

So in my opinion Foreign Relationship should be fine. I don't have problems when I'm adding new data by admin panel. I used it in a view:

views.py:

def index(request):
    if request.method == 'POST':
        form = Search(request.POST)
        if form.is_valid():
            dane = form.cleaned_data
            tlumaczenie=Explanation.objects.filter(Word__word_text=dane['Searched_word'])
            print(tlumaczenie)
            return render(request,'explanation.html', {'dane':dane})

But I'm still getting error:

django.core.exceptions.FieldError: Cannot resolve keyword 'Word' into field. Choices are: expl_text, id, modi_date, publ_date, user_crea, word_foid, word_foid_id

I don't understand why. It should send query like:

select e.* from word w join explanation e on w.word_id = e.word_foid where w.word_text = dane['Searched_word']

and retrieve the data.

Any ideas why it's not working properly?

Body:
Your foreign key field is called word_foid, not Word. The query should use that name like this

tlumaczenie = Explanation.objects.filter(word_foid__word_text=dane['Searched_word'])


问:
XQuery Show Collection Name
What is the XQuery to search the entire database and show the collection name which has a given element-name?</p>

答:
You can find out which collections contain documents matching a query with a cts:collections() lexicon lookup.  You can use a cts:element-query() with a cts:true-query() to match an element on name regardless of content.

Putting those two ingredients together, the query would look something like:

```<code>cts:collections((), (),
    cts:element-query(QName("namespace", "name"), cts:true-query())
    )
</code>```

The collection lexicon must be enabled for the database, which is the default in MarkLogic 9.

Hoping that helps,

Title: XQuery Show Collection Name

Body:
You can find out which collections contain documents matching a query with a cts:collections() lexicon lookup.  You can use a cts:element-query() with a cts:true-query() to match an element on name regardless of content.

Putting those two ingredients together, the query would look something like:

cts:collections((), (),
    cts:element-query(QName("namespace", "name"), cts:true-query())
    )

The collection lexicon must be enabled for the database, which is the default in MarkLogic 9.

Hoping that helps,