问:
Going mad with Android Fragment Transaction
I can not comprehend this behavior of my fragment transactions. Can someone please intervent before I go crazy. In my MainActivity I set it up correctly:

```<code>    private final GuideFragment guideFragment = new GuideFragment();
    private final MapFragment mapFragment = new MapFragment();
    private final MoreFragment moreFragment = new MoreFragment();

    Fragment active;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                switch (item.getItemId()) {
                    case R.id.navigation_guide:
                        if (!guideFragment.isAdded()) {
                            transaction.add(R.id.content,guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "add Fragment1");
                            break;
                        } else {
                            transaction.hide(active).show(guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "show Fragment1");
                            break;
                        }
                    case R.id.navigation_map:
                        if (!mapFragment.isAdded()) {
                            transaction.add(R.id.content, mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"add Fragment2");
                            break;
                        } else {
                            transaction.hide(active).show(mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"show Fragment2");
                            break;
                        }
                    case R.id.navigation_more:
                        if (!moreFragment.isAdded()) {
                            transaction.add(R.id.content,moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"add Fragment3");
                            break;
                        } else {
                            transaction.hide(active).show(moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"show Fragment3");
                            break;
                        }
                }

                return true;
            }

        };

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

        //start with guide view/fragment
        switchTabView(R.id.navigation_guide);

    }

    //method to start or switch a tab
    private void switchTabView(int itemId) {
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(itemId);

    }
</code>```

My App has 3 Tabs as you can see above: Tab1 (Guide) Tab2 (Map) Tab3 (More).

When the app launches, the first Tab (Guide) is added and shown correctly.
Then I tap on Map (next Fragment), this is added and shown correctly.
Finally on the More Tab (my 3rd Tab) all works great.

But when the activity launches and I tap 1-3 (Guide to Map) so far correct -
then 3-2 (More Tab to Map Tab) all good - but then back from 2-1 (Map to Guide) there is suddenly the 3rd tab Fragment (More) shown where the Guide Fragment should be.

Someone has an idea on what is wrong?
Would appreciate some help.

Solution thanks to Mateus

```<code>transaction.hide(fragment3).hide(fragment2).show(fragment1).commit();
</code>```

I am not sure if calling two times hide fragment is that clean but I think with 3 tabs it is still okay. With more tabs I would consider to handle this in a different way like remove() or replace() fragments.

Update - Solution is more tricky as expected:

```<code>           switch (item.getItemId()) {
                case R.id.navigation_guide:
                    if (!guideFragment.isAdded()) {
                        transaction.add(R.id.content,guideFragment).commit();
                        Log.d(TAG, "add Fragment1");
                        break;
                    } else {
                        if (!moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(mapFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && !mapFragment.isAdded()) {
                            transaction.hide(moreFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(moreFragment).hide(mapFragment).show(guideFragment).commit();
                        }

                        Log.d(TAG, "show Fragment1");
                        break;
                    }
                case R.id.navigation_map:
                    if (!mapFragment.isAdded()) {
                        transaction.add(R.id.content, mapFragment).commit();
                        Log.d(TAG,"add Fragment2");
                        break;
                    } else {
                        if (!moreFragment.isAdded()) {
                            transaction.hide(guideFragment).show(mapFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(moreFragment).show(mapFragment).commit();
                        }
                        Log.d(TAG,"show Fragment2");
                        break;
                    }
                case R.id.navigation_more:
                    if (!moreFragment.isAdded()) {
                        transaction.add(R.id.content,moreFragment).commit();
                        Log.d(TAG,"add Fragment3");
                        break;
                    } else {
                        if (!mapFragment.isAdded()) {
                            transaction.hide(guideFragment).show(moreFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(mapFragment).show(moreFragment).commit();
                        }
                        Log.d(TAG,"show Fragment3");
                        break;
                    }
            }
</code>```

Finally bug free, you have to check if other fragments are added!

答:
At the point you go back from 2 to 1, this line will be called:

```<code>transaction.hide(active).show(guideFragment).commit();
</code>```

The problem is that when you hide active(Fragment 2) and show Fragment 1, Fragment 3(which was added after Fragment 1, therefore is "on top" of Fragment1) is still being shown. You'd have to call hide on Fragment 3 too to see Fragment 1.

In other words, you need to adjust your code to hide all the other fragments everytime you want to show a specific one.

Also check this discussion about choosing between show/hide and add/remove/replace to confirm that the first strategy better suits your needs.

Body:
I can not comprehend this behavior of my fragment transactions. Can someone please intervent before I go crazy. In my MainActivity I set it up correctly:

    private final GuideFragment guideFragment = new GuideFragment();
    private final MapFragment mapFragment = new MapFragment();
    private final MoreFragment moreFragment = new MoreFragment();

    Fragment active;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                switch (item.getItemId()) {
                    case R.id.navigation_guide:
                        if (!guideFragment.isAdded()) {
                            transaction.add(R.id.content,guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "add Fragment1");
                            break;
                        } else {
                            transaction.hide(active).show(guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "show Fragment1");
                            break;
                        }
                    case R.id.navigation_map:
                        if (!mapFragment.isAdded()) {
                            transaction.add(R.id.content, mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"add Fragment2");
                            break;
                        } else {
                            transaction.hide(active).show(mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"show Fragment2");
                            break;
                        }
                    case R.id.navigation_more:
                        if (!moreFragment.isAdded()) {
                            transaction.add(R.id.content,moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"add Fragment3");
                            break;
                        } else {
                            transaction.hide(active).show(moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"show Fragment3");
                            break;
                        }
                }

                return true;
            }

        };

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

        //start with guide view/fragment
        switchTabView(R.id.navigation_guide);

    }

    //method to start or switch a tab
    private void switchTabView(int itemId) {
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(itemId);

    }

My App has 3 Tabs as you can see above: Tab1 (Guide) Tab2 (Map) Tab3 (More).

When the app launches, the first Tab (Guide) is added and shown correctly.
Then I tap on Map (next Fragment), this is added and shown correctly.
Finally on the More Tab (my 3rd Tab) all works great.

But when the activity launches and I tap 1-3 (Guide to Map) so far correct -
then 3-2 (More Tab to Map Tab) all good - but then back from 2-1 (Map to Guide) there is suddenly the 3rd tab Fragment (More) shown where the Guide Fragment should be.

Someone has an idea on what is wrong?
Would appreciate some help.

Solution thanks to Mateus

transaction.hide(fragment3).hide(fragment2).show(fragment1).commit();

I am not sure if calling two times hide fragment is that clean but I think with 3 tabs it is still okay. With more tabs I would consider to handle this in a different way like remove() or replace() fragments.

Update - Solution is more tricky as expected:

           switch (item.getItemId()) {
                case R.id.navigation_guide:
                    if (!guideFragment.isAdded()) {
                        transaction.add(R.id.content,guideFragment).commit();
                        Log.d(TAG, "add Fragment1");
                        break;
                    } else {
                        if (!moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(mapFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && !mapFragment.isAdded()) {
                            transaction.hide(moreFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(moreFragment).hide(mapFragment).show(guideFragment).commit();
                        }

                        Log.d(TAG, "show Fragment1");
                        break;
                    }
                case R.id.navigation_map:
                    if (!mapFragment.isAdded()) {
                        transaction.add(R.id.content, mapFragment).commit();
                        Log.d(TAG,"add Fragment2");
                        break;
                    } else {
                        if (!moreFragment.isAdded()) {
                            transaction.hide(guideFragment).show(mapFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(moreFragment).show(mapFragment).commit();
                        }
                        Log.d(TAG,"show Fragment2");
                        break;
                    }
                case R.id.navigation_more:
                    if (!moreFragment.isAdded()) {
                        transaction.add(R.id.content,moreFragment).commit();
                        Log.d(TAG,"add Fragment3");
                        break;
                    } else {
                        if (!mapFragment.isAdded()) {
                            transaction.hide(guideFragment).show(moreFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(mapFragment).show(moreFragment).commit();
                        }
                        Log.d(TAG,"show Fragment3");
                        break;
                    }
            }

Finally bug free, you have to check if other fragments are added!

Body:
At the point you go back from 2 to 1, this line will be called:

transaction.hide(active).show(guideFragment).commit();

The problem is that when you hide active(Fragment 2) and show Fragment 1, Fragment 3(which was added after Fragment 1, therefore is "on top" of Fragment1) is still being shown. You'd have to call hide on Fragment 3 too to see Fragment 1.

In other words, you need to adjust your code to hide all the other fragments everytime you want to show a specific one.

Also check this discussion about choosing between show/hide and add/remove/replace to confirm that the first strategy better suits your needs.


来源: stackexchange

问:
WordPress theme editor is missing
I am trying to access the theme editor in WordPress.

The problem is that I cannot find the option under Admin-Appearances -  Editor and when I try to access the page using the link http://www.nameofsite.com/wp-admin/theme-editor.php I get the error:

You do not have sufficient permissions to access this page.

I am logged in as an administrator. Why can't I find the editor option?

答:
It is probably because of iThemes Security and its settings. So yeah, just go to wp-config and change DISALLOW_FILE_EDIT to false.

```<code>define( 'DISALLOW_FILE_EDIT', false );
</code>```

Or just switch it off here:
Dashboard -> Security -> WordPress Tweaks -> Configure Settings

Uncheck: Disable File Editor

ContentLicense: CC BY-SA 4.0

Title: WordPress theme editor is missing

Body:
It is probably because of iThemes Security and its settings. So yeah, just go to wp-config and change DISALLOW_FILE_EDIT to false.

define( 'DISALLOW_FILE_EDIT', false );

Or just switch it off here:
Dashboard -> Security -> WordPress Tweaks -> Configure Settings

Uncheck: Disable File Editor

ContentLicense: CC BY-SA 3.0


问:
cond fails when I add a puts function
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

```<code>   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end
</code>```

Is this the correct syntax for cond ? Why this error seems so random ?

答:
From documentation:

reduce(enumerable, acc, fun)

Invokes fun for each element in the enumerable, passing that element and the accumulator acc as arguments. fun’s return value is stored in acc

One of your cond branches does not return the new value for accumulator. (the one with IO.puts)

Title: cond fails when I add a puts function

Body:
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end

Is this the correct syntax for cond ? Why this error seems so random ?


问:
Remove string and add sequential number to file headers using awk or sed
I have following input:

```<code>>Thimo_0001|ID:40710520| hypothetical protein [Thioflavicoccus mobilis 8321]
LIAPTMILRIRLTEFCPMRTEGFEE
TGIGPLDSRMPRYDDVVHHREIIT
YPPEALSNDPFDPTSIDGSPSAFF*
>ThimoAM_0002|ID:40707134| protein of unknown function [Thioflavicoccus mobilis 8321]
VRKAERDSPCKRRGADRSFP
KSARLISSKAFRDVFAESITNSDPFFVVR
ARPNLAETARLGIAVSKKCARRSVDRSRIKRII
RESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA*
>Thimo_0002|ID:40710524| ribonuclease P protein component [Thioflavicoccus mobilis 8321]
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRAR
TTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAP
RRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL*
</code>```

And I would like to

remove the linebreaks in lines after the header starting with >

remove the asterisk

change the fasta header

I could do 1. and 2.

```<code>awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }'
sed "s/\*//g"
</code>```

and I can also add a sequential number to the end of the header line:

```<code>awk '/^>/{$0=$0"_"(++i)}1'
</code>```

but I am failing at the last step with the replacing/removing and adding a sequential number:

desired output

```<code>>TM0001|hypothetical_protein
LIAPTMILRIRLTEFCPMRTEGFEETGIGPLDSRMPRYDDVVHHREIITYPPEALSNDPFDPTSIDGSPSAFF
>TM0002|protein_of_unknown_function
VRKAERDSPCKRRGADRSFPKSARLISSKAFRDVFAESITNSDPFFVVRARPNLAETARLGIAVSKKCARRSVDRSRIKRIIRESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA
>TM0003|ribonuclease_P_protein_component
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRARTTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAPRRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL
</code>```

答:
According to your "desired" output - gawk solution:

```<code>awk 'BEGIN{ RS=">"; FS="[|\\]\\[]" }!$0{ next }
     { gsub(/^ */,"",$3); gsub(/[*[:space:]]/,"",$5); printf(">TM%04d|%s\n%s\n",++c,$3,$5)
}' yourfile
</code>```

The output:

```<code>>TM0001|hypothetical protein
LIAPTMILRIRLTEFCPMRTEGFEETGIGPLDSRMPRYDDVVHHREIITYPPEALSNDPFDPTSIDGSPSAFF
>TM0002|protein of unknown function
VRKAERDSPCKRRGADRSFPKSARLISSKAFRDVFAESITNSDPFFVVRARPNLAETARLGIAVSKKCARRSVDRSRIKRIIRESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA
>TM0003|ribonuclease P protein component
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRARTTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAPRRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL
</code>```

Details:

RS=">" - considering > as record separator

FS="[|\\]\\[]" - field separator, any of characters |[]

!$0{ next } - skip empty records

gsub(/^ */,"",$3) - remove leading spaces in the 3rd field

gsub(/[*[:space:]]/,"",$5) - replace/remove asterisk * and whitespace characters within the 5th field

Body:
I have following input:

>Thimo_0001|ID:40710520| hypothetical protein [Thioflavicoccus mobilis 8321]
LIAPTMILRIRLTEFCPMRTEGFEE
TGIGPLDSRMPRYDDVVHHREIIT
YPPEALSNDPFDPTSIDGSPSAFF*
>ThimoAM_0002|ID:40707134| protein of unknown function [Thioflavicoccus mobilis 8321]
VRKAERDSPCKRRGADRSFP
KSARLISSKAFRDVFAESITNSDPFFVVR
ARPNLAETARLGIAVSKKCARRSVDRSRIKRII
RESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA*
>Thimo_0002|ID:40710524| ribonuclease P protein component [Thioflavicoccus mobilis 8321]
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRAR
TTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAP
RRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL*

And I would like to

remove the linebreaks in lines after the header starting with >

remove the asterisk

change the fasta header

I could do 1. and 2.

awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }'
sed "s/\*//g"

and I can also add a sequential number to the end of the header line:

awk '/^>/{$0=$0"_"(++i)}1'

but I am failing at the last step with the replacing/removing and adding a sequential number:

desired output

>TM0001|hypothetical_protein
LIAPTMILRIRLTEFCPMRTEGFEETGIGPLDSRMPRYDDVVHHREIITYPPEALSNDPFDPTSIDGSPSAFF
>TM0002|protein_of_unknown_function
VRKAERDSPCKRRGADRSFPKSARLISSKAFRDVFAESITNSDPFFVVRARPNLAETARLGIAVSKKCARRSVDRSRIKRIIRESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA
>TM0003|ribonuclease_P_protein_component
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRARTTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAPRRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL

Body:
According to your "desired" output - gawk solution:

awk 'BEGIN{ RS=">"; FS="[|\\]\\[]" }!$0{ next }
     { gsub(/^ */,"",$3); gsub(/[*[:space:]]/,"",$5); printf(">TM%04d|%s\n%s\n",++c,$3,$5)
}' yourfile

The output:

>TM0001|hypothetical protein
LIAPTMILRIRLTEFCPMRTEGFEETGIGPLDSRMPRYDDVVHHREIITYPPEALSNDPFDPTSIDGSPSAFF
>TM0002|protein of unknown function
VRKAERDSPCKRRGADRSFPKSARLISSKAFRDVFAESITNSDPFFVVRARPNLAETARLGIAVSKKCARRSVDRSRIKRIIRESFRWVRNDLPVMDYVVIARHAAVKRTNPRLFESLRSHWTKFSEPDA
>TM0003|ribonuclease P protein component
MILLIRLRSTDRRAHFFDTAIPNLAVSARLGRARTTKNGSEFVMDSAKTSRNAFEEISLADFGKERSAPRRLQGESLSAFRTTRGQDEPATFRCPTRPKPMCMRAL

Details:

RS=">" - considering > as record separator

FS="[|\\]\\[]" - field separator, any of characters |[]

!$0{ next } - skip empty records

gsub(/^ */,"",$3) - remove leading spaces in the 3rd field

gsub(/[*[:space:]]/,"",$5) - replace/remove asterisk * and whitespace characters within the 5th field


问:
Changing Schema Name
I have created a table in a  schema called sample1 and now i want to change the schema name of the table. I tried doing it by

alter schema sample2 transfer sample1.table1

But it gives me an error.

How do I change the schema name from sample1 to sample2

答: start with CREATE SCHEMA sample2 and then run the same command.

ContentLicense: CC BY-SA 2.5

Title: Changing Schema Name


问:
Confusing Character String Interaction
I'm currently doing the CS50 course, and I'm stuck on the credit problem. The idea is to make a program to verify cards due to their inbuilt checksum. The first step is to take every second digit and multiply it by 2, then add all the digits of the products together.

My code isn't finished, but I've set it up to print some intermediary steps just so I can see what's going on.

```<code>#include <stdio.h>
#include <string.h>

void checksum (char number[20]);

int main (void){
  char *card;

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < 17; i += 2){
    printf("No%c\n", number[i]);
    digits = (number[i] * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}
</code>```

I know the first part is far from perfect but it's the checksum function I'm concerned with at the moment. When it takes the second digit(5) everything is fine. But then when it's multiplied by 2 according to the next line, somehow the result is 106(?)

Can someone explain what's going on here?

terminal output

答:
A couple of things:

char *card; scanf("%s", card); is not going to work. You need to either declare card as an array of fixed size (i.e. char card[20]), or use malloc to allocate memory for the pointer char *card;.  If you choose the latter option you also need to use free on the memory when you're done with it.

In your function checksum, you need to convert the characters you read in the string card into numbers. If the character set on your system is ASCII, you can achieve this by subtracting the value 0x30 (i.e. the numeric value of the character '0') from each character in the string before performing arithmetic on it.

char number[20] in a function signature is pointless; see this question for more information. Since the array decays to a pointer to its first element when passed as a function argument, you may as well have char *number in the function signature.

Title: Confusing Character String Interaction

Body:
I'm currently doing the CS50 course, and I'm stuck on the credit problem. The idea is to make a program to verify cards due to their inbuilt checksum. The first step is to take every second digit and multiply it by 2, then add all the digits of the products together.

My code isn't finished, but I've set it up to print some intermediary steps just so I can see what's going on.

#include <stdio.h>
#include <string.h>

void checksum (char number[20]);

int main (void){
  char *card;

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < 17; i += 2){
    printf("No%c\n", number[i]);
    digits = (number[i] * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}

I know the first part is far from perfect but it's the checksum function I'm concerned with at the moment. When it takes the second digit(5) everything is fine. But then when it's multiplied by 2 according to the next line, somehow the result is 106(?)

Can someone explain what's going on here?

terminal output


问:
How to return two different classes from single method
```<code>public ResponseEntity<Profile> getProfile(@PathVariable("id") String id){
    if(id != null){
    //getting CUSTOMER from DB
    returning EntityProfile

    if(CUSTOMER == null)
    //getting data from webservice
    returning Profile
</code>```

答:
You can achieve this using Generics. You haven't explained the relation between the Profile and EntityProfile. So, assuming you have something called  BaseProfile and these 2 Profile objects extends them, you can write the return type as:

```<code>public ResponseEntity <? extends BaseProfile>
</code>```

This way you can return any object of type BaseProfile.

If Profile is a parent class of EntityProfile, your code (public ResponseEntity <Profile>) should work fine. However, if you want to return any type of object, you could change the return type as:

```<code> public ResponseEntity <?>
</code>```

Body:
You can achieve this using Generics. You haven't explained the relation between the Profile and EntityProfile. So, assuming you have something called  BaseProfile and these 2 Profile objects extends them, you can write the return type as:

public ResponseEntity <? extends BaseProfile>

This way you can return any object of type BaseProfile.

If Profile is a parent class of EntityProfile, your code (public ResponseEntity <Profile>) should work fine. However, if you want to return any type of object, you could change the return type as:

 public ResponseEntity <?>


问:
GatewayChallengeHandler: handleChallenge() not being called after upgrading to MobileFirst v.8.0
We have a production iOS app that currently runs under MFP 7.0.  I am upgrading it to MFP 8.0.

In the existing version, we extend ChallengeHander as ISAMChallengeHandler to handle ISAM gateway login requests.  For v8.0, I changed ISAMChallengeHandler to extend GatewayChallengeHandler. This involved changing isCustomResponse() to canHandleResponse() and removing a call to submitFailure().

The new version isn't working as expected.  When I call an adapter using WLClient.getInstance().invokeProcedure(...), the gateway returns the login screen, and ISAMChallengeHandler.canHandleResponse() is properly called and is returning true.  But handleChallenge() never gets called.

Instead it appears that the HTTP request to the adapter is tried again, resulting in another call to canHandleResponse().  This happens 7 times in a row without any attempt to call handleChallenge().  Then an error from WLResourceRequest occurs, and the WLDelegate gets the onFailure() callback.

What can be causing this behavior? The application's logic has not changed from the 7.0 version.   Is invokeProcedure() not supported anymore?  I get Xcode deprecation warnings on wlConnectWithDelegate() and  WLProcedureInvocationData(), but not invokeProcedure() (which doesn't make sense).

The HTTP retries always happen seven times. Below are the log entries from the app showing this. I've removed the "Response Content" lines for readablility. LoginManager is the class that calls invokeProcedure() using LoginListener as the WLDelegate.

```<code>2017-02-07 20:41:41.613 sitecompliance[50592:4035152] <AppDelegate> App starting: Optional("1.0") Optional("309.2")
2017-02-07 20:41:41.619 sitecompliance[50592:4035152] <AppDelegate> deviceDate (UTC): 2017-02-08 02:41:41 +0000
2017-02-07 20:41:41.620 sitecompliance[50592:4035152] <AppDelegate> deviceDate (localtime): Feb 7, 2017, 8:41:41 PM
2017-02-07 20:41:41.669 sitecompliance[50592:4035152] <LoginManager.connectAndLogin>
2017-02-07 20:41:42.386 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning FALSE
2017-02-07 20:41:43.595 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning FALSE
2017-02-07 20:41:43.595 sitecompliance[50592:4035152] <ConnectListener.onSuccess> connectionSuccess
2017-02-07 20:41:43.596 sitecompliance[50592:4035152] <LoginManager.connectionSuccess>
2017-02-07 20:41:43.599 sitecompliance[50592:4035152] <LoginManager.authenticate> Invoking Worker/getWorker
2017-02-07 20:41:44.469 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.470 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.584 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.585 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.682 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.682 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.782 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.782 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.878 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.878 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.973 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.974 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:45.075 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:45.076 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:45.076 sitecompliance[50592:4035152] [ERROR] [WORKLIGHT] -[WLResourceRequest requestFailed:error:] in WLResourceRequest.m:695 :: WL_OAUTH
2017-02-07 20:41:45.094 sitecompliance[50592:4035152] <LoginListener.onFailure> Cannot retrieve a valid authorization header for header. Check resource and authorization server configuration.
2017-02-07 20:41:45.095 sitecompliance[50592:4035152] <LoginViewController.loginFailure> System error.
</code>```

Here is the beginning of ISAMChallenger handler showing the canHandleResponse() and handleChallenge() methods:

```<code>class ISAMChallengeHandler: GatewayChallengeHandler
{
    let baseURL: String!

    override init(){
        baseURL = "\(getBaseURL()!)"
        super.init(gatewayName: "HeaderAuthRealm")
    }

    override func canHandleResponse(response: WLResponse!) -> Bool
    {
        if response != nil {
            if response.responseText != nil {
                if response.responseText.rangeOfString("PKMS Administration: Expired Password") != nil {
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> Found \"PKMS Administration: Expired Password\"")
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning TRUE")
                    return true
                }
                if response.responseText.rangeOfString("/pkmslogin.form") != nil {
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> Found \"/pkmslogin.form\"")
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning TRUE")
                    return true
                }

            }
        }
        MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning FALSE")
        return false
    }

    override func handleChallenge(response: WLResponse!)
    {
        //HPDIA0200W Authentication failed. You have used an invalid user name, password or client certificate.
        let failedLogin = response.responseText.rangeOfString("HPDIA0200W") != nil
        let passwordExpired = response.responseText.rangeOfString("PKMS Administration: Expired Password") != nil
        let worker = Worker.getWorker()

        if worker.authDataSet && !failedLogin && !passwordExpired
        {
            MQALogger.log("<ISAMChallengeHandler.handleChallenge> Sending stored login data to ISAM")
            submitISAMAuthData()
        }
        else
        {
            MQALogger.log("<ISAMChallengeHandler.handleChallenge> A login screen form should appear")
            if failedLogin {
                needCredentials("Please check your credentials.")
            } else if passwordExpired {
                worker.password = nil
                saveObjects()
                notify("Password expired",
                    myMessage: "Change on ServiceArizona secure gateway, then sign into app again.", vc: nil)
                    { self.showLoginView() }
            } else {
                needCredentials(nil)
            }
        }
    }
</code>```

答:
Our architecture has a proxy server in front both the ISAM/WebSeal server and the MFP server.  The proxy directs each MFP request to one or the other depending on whether or not it needs to be authorized by WebSeal.  This was working in MFP 7 but not MFP 8.

We discovered that if we set up all MFP traffic to go through the ISAM, then the GatewayChallengeHandler worked properly, but this wasn't a valid solution for our environment.

A little proxy log investigation found up that the MFP 8 API sends a "pre-auth" HTTP request to the server after canHandleResponse() returns but before handleChallenge() is called.  This wasn't clear from the docs or the API logging. The proxy was sending that pre-auth request directly to the MFP server (not the ISAM).

When we added a proxy rule to send all pre-auth requests (/mfp/api/preauth/*) to ISAM, the GatewayChallengeHandler problem was fixed, and we could keep our non-secured MFP requests going directly to the MFP server.

Body:
We have a production iOS app that currently runs under MFP 7.0.  I am upgrading it to MFP 8.0.

In the existing version, we extend ChallengeHander as ISAMChallengeHandler to handle ISAM gateway login requests.  For v8.0, I changed ISAMChallengeHandler to extend GatewayChallengeHandler. This involved changing isCustomResponse() to canHandleResponse() and removing a call to submitFailure().

The new version isn't working as expected.  When I call an adapter using WLClient.getInstance().invokeProcedure(...), the gateway returns the login screen, and ISAMChallengeHandler.canHandleResponse() is properly called and is returning true.  But handleChallenge() never gets called.

Instead it appears that the HTTP request to the adapter is tried again, resulting in another call to canHandleResponse().  This happens 7 times in a row without any attempt to call handleChallenge().  Then an error from WLResourceRequest occurs, and the WLDelegate gets the onFailure() callback.

What can be causing this behavior? The application's logic has not changed from the 7.0 version.   Is invokeProcedure() not supported anymore?  I get Xcode deprecation warnings on wlConnectWithDelegate() and  WLProcedureInvocationData(), but not invokeProcedure() (which doesn't make sense).

The HTTP retries always happen seven times. Below are the log entries from the app showing this. I've removed the "Response Content" lines for readablility. LoginManager is the class that calls invokeProcedure() using LoginListener as the WLDelegate.

2017-02-07 20:41:41.613 sitecompliance[50592:4035152] <AppDelegate> App starting: Optional("1.0") Optional("309.2")
2017-02-07 20:41:41.619 sitecompliance[50592:4035152] <AppDelegate> deviceDate (UTC): 2017-02-08 02:41:41 +0000
2017-02-07 20:41:41.620 sitecompliance[50592:4035152] <AppDelegate> deviceDate (localtime): Feb 7, 2017, 8:41:41 PM
2017-02-07 20:41:41.669 sitecompliance[50592:4035152] <LoginManager.connectAndLogin>
2017-02-07 20:41:42.386 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning FALSE
2017-02-07 20:41:43.595 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning FALSE
2017-02-07 20:41:43.595 sitecompliance[50592:4035152] <ConnectListener.onSuccess> connectionSuccess
2017-02-07 20:41:43.596 sitecompliance[50592:4035152] <LoginManager.connectionSuccess>
2017-02-07 20:41:43.599 sitecompliance[50592:4035152] <LoginManager.authenticate> Invoking Worker/getWorker
2017-02-07 20:41:44.469 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.470 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.584 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.585 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.682 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.682 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.782 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.782 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.878 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.878 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:44.973 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:44.974 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:45.075 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> Found "/pkmslogin.form"
2017-02-07 20:41:45.076 sitecompliance[50592:4035152] <ISAMChallengeHandler.canHandleResponse> returning TRUE
2017-02-07 20:41:45.076 sitecompliance[50592:4035152] [ERROR] [WORKLIGHT] -[WLResourceRequest requestFailed:error:] in WLResourceRequest.m:695 :: WL_OAUTH
2017-02-07 20:41:45.094 sitecompliance[50592:4035152] <LoginListener.onFailure> Cannot retrieve a valid authorization header for header. Check resource and authorization server configuration.
2017-02-07 20:41:45.095 sitecompliance[50592:4035152] <LoginViewController.loginFailure> System error.

Here is the beginning of ISAMChallenger handler showing the canHandleResponse() and handleChallenge() methods:

class ISAMChallengeHandler: GatewayChallengeHandler
{
    let baseURL: String!

    override init(){
        baseURL = "\(getBaseURL()!)"
        super.init(gatewayName: "HeaderAuthRealm")
    }

    override func canHandleResponse(response: WLResponse!) -> Bool
    {
        if response != nil {
            if response.responseText != nil {
                if response.responseText.rangeOfString("PKMS Administration: Expired Password") != nil {
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> Found \"PKMS Administration: Expired Password\"")
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning TRUE")
                    return true
                }
                if response.responseText.rangeOfString("/pkmslogin.form") != nil {
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> Found \"/pkmslogin.form\"")
                    MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning TRUE")
                    return true
                }

            }
        }
        MQALogger.log("<ISAMChallengeHandler.canHandleResponse> returning FALSE")
        return false
    }

    override func handleChallenge(response: WLResponse!)
    {
        //HPDIA0200W Authentication failed. You have used an invalid user name, password or client certificate.
        let failedLogin = response.responseText.rangeOfString("HPDIA0200W") != nil
        let passwordExpired = response.responseText.rangeOfString("PKMS Administration: Expired Password") != nil
        let worker = Worker.getWorker()

        if worker.authDataSet && !failedLogin && !passwordExpired
        {
            MQALogger.log("<ISAMChallengeHandler.handleChallenge> Sending stored login data to ISAM")
            submitISAMAuthData()
        }
        else
        {
            MQALogger.log("<ISAMChallengeHandler.handleChallenge> A login screen form should appear")
            if failedLogin {
                needCredentials("Please check your credentials.")
            } else if passwordExpired {
                worker.password = nil
                saveObjects()
                notify("Password expired",
                    myMessage: "Change on ServiceArizona secure gateway, then sign into app again.", vc: nil)
                    { self.showLoginView() }
            } else {
                needCredentials(nil)
            }
        }
    }


问:
Conditional group membership with Ansible
I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.

```<code>- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775
</code>```

The debug task returns this when the group doesn't exist:

```<code>ok: [host] => {
    "getent_group.webadmins": ""
}
</code>```

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.

The group may exists in AD domain, so I cannot parse /etc/group.

答:
The following condition should work for you:

```<code>group="{{ (getent_group.webadmins is defined) | ternary('webadmins', 'root') }}"
</code>```

If you displayed the value of getent_group in your debug task, you'd notice the value of webgroup key is actually set to null, not an empty string.

```<code>"getent_group": {
    "webgroup": null
}
</code>```

Body:
I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.

- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775

The debug task returns this when the group doesn't exist:

ok: [host] => {
    "getent_group.webadmins": ""
}

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.

The group may exists in AD domain, so I cannot parse /etc/group.

Body:
The following condition should work for you:

group="{{ (getent_group.webadmins is defined) | ternary('webadmins', 'root') }}"

If you displayed the value of getent_group in your debug task, you'd notice the value of webgroup key is actually set to null, not an empty string.

"getent_group": {
    "webgroup": null
}


问:
Guidelines for testing multithreaded code or ensuring that code is thread-safe
Are there any guidelines for testing multi-threaded code (other than throwing a bunch of threads at the problem and crossing your fingers).

I'm basically looking for good ways to test for data corruption, deadlocks, and other concurrency issues. Essentially I want to be able to prove that the code is thread-safe via a test.

Are there any frameworks in Java that let you easily write tests for a multithreaded scenario?

答: GroboUtils, http://groboutils.sourceforge.net/testing-junit/using_mtt.html, provides some JUnit utilities for testing Threads.</p>


问:
Failed to locate Element from a CheckOut Table
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

```<code>String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);
</code>```

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

```<code><div id="order-detail-content" class="table_block table-responsive">
<table id="cart_summary" class="table table-bordered stock-management-on">
<thead>
<tr>
<th class="cart_product first_item">Product</th>
<th class="cart_description item">Description</th>
<th class="cart_avail item">Avail.</th>
<th class="cart_unit item">Unit price</th>
<th class="cart_quantity item">Qty</th>
<th class="cart_total item">Total</th>
<th class="cart_delete last_item"> </th>
</tr>
</thead>
<tfoot>
<tr class="cart_total_price">
<td id="cart_voucher" class="cart_voucher" rowspan="3" colspan="3"> </td>
<td class="text-right" colspan="3">Total products</td>
<td id="total_product" class="price" colspan="2">$39.51</td>
</tr>
<tr style="display: none;">
<tr class="cart_total_delivery">
<tr class="cart_total_voucher" style="display:none">
<tr class="cart_total_price">
</tfoot>
<tbody>
<tr id="product_1_1_0_0" class="cart_item last_item first_item address_0 odd">
<td class="cart_product">
<td class="cart_description">
<td class="cart_avail">
<td class="cart_unit" data-title="Unit price">
<span id="product_price_1_1_0" class="price">
<span class="price">$39.51</span>
</span>
</td>
<td class="cart_quantity text-center">
<td class="cart_total" data-title="Total">
<td class="cart_delete text-center" data-title="Delete">
</tr>
</tbody>
</table>
</div>
</code>```

答:
Try to select the element with the Text you want:

```<code>String price = driver.findElement(By.cssSelector("#product_1_1_0_0 > td:nth-child(4) > span > span")).getText();
</code>```

This should work, so long as the ID #product_1_1_0_0 is not dynamic. Your element not found exception leads me to believe it is dynamic. If that is the case ignore that id and go up the hierarchy a bit with the selector:

```<code>"#cart_summary > table > tbody > tr > td:nth-child(4) > span > span"
</code>```

EDIT

I just noticed the id="product_price_1_1_0" on the first span, so you could just do:

```<code>"#product_price_1_1_0 > span"
</code>```

Body:
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

Product
Description
Avail.
Unit price
Qty
Total

Total products
$39.51

$39.51

Body:
Try to select the element with the Text you want:

String price = driver.findElement(By.cssSelector("#product_1_1_0_0 > td:nth-child(4) > span > span")).getText();

This should work, so long as the ID #product_1_1_0_0 is not dynamic. Your element not found exception leads me to believe it is dynamic. If that is the case ignore that id and go up the hierarchy a bit with the selector:

"#cart_summary > table > tbody > tr > td:nth-child(4) > span > span"

EDIT

I just noticed the id="product_price_1_1_0" on the first span, so you could just do:

"#product_price_1_1_0 > span"


问:
Mongoose - cant push the result of findById into array
I am trying to push the result of an findById to an existing array. My code looks like this:

var targetArray = [];
var groupId; //gets the ID from another function.

```<code>Group.findById((groupId), (error, group) => {
  targetArray.push(group.toObject());
  console.log(targetArray);
}
console.log(targetArray);
</code>```

The first log returns the array with the group in it, the second log returns an empty array [].

I tried it with and without the ".toObject()", I even tried pushing a simple string into the array. Everything vanished after I left the function.

I don't know if this is a mongoose-specific question or general javascript, but usually if I push something into an array it doesn't vanish on it's own.

Can you guys (and girls ofc) maybe point out what I am doing wrong?

答:
This is actually more how javascript deal with asynchronous code.

It is happening because you are passing to the findById a callback function which will run some time in the javascript call stack. This means that as soon as you call findById function passing those arguments, javascript run the bottom console.log which in that case the array it's still empty.

The function that you have passed as an argument will run as soon as mongoose receive and acknowledgment from the mongo driver with some error or some data.

The truth is that this is expected and if you really want to do something with the data returned from mongoose you should in fact do it on the callback function.

Body:
I am trying to push the result of an findById to an existing array. My code looks like this:

var targetArray = [];
var groupId; //gets the ID from another function.

Group.findById((groupId), (error, group) => {
  targetArray.push(group.toObject());
  console.log(targetArray);
}
console.log(targetArray);

The first log returns the array with the group in it, the second log returns an empty array [].

I tried it with and without the ".toObject()", I even tried pushing a simple string into the array. Everything vanished after I left the function.

I don't know if this is a mongoose-specific question or general javascript, but usually if I push something into an array it doesn't vanish on it's own.

Can you guys (and girls ofc) maybe point out what I am doing wrong?


问:
How to ignore python modules during import?
During the build process of a Python application I need to ignore some imports (because these modules are created by the build process). It is a chicken-and-egg-question, that I can't resolve easily.
So I thought I could use the import hook to do this like this:

```<code>class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def load_module(self, name):
        raise ImportError("%s is blocked and cannot be imported" % name)

import sys
sys.meta_path = [ImportBlocker('chickenlib')]
</code>```

But because I raise an error the build process stop --- I just want to silently ignore the import ... returning "None" does not work, too.
Is there a way to do this?

答:
Referring to "silently ignore the import", you can try this:</p>
```<code>def TryImport(module_name):
    try:
        import module_name
    except ImportError:
        pass #or anything to log
</code>```

Body:
During the build process of a Python application I need to ignore some imports (because these modules are created by the build process). It is a chicken-and-egg-question, that I can't resolve easily.
So I thought I could use the import hook to do this like this:

class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def load_module(self, name):
        raise ImportError("%s is blocked and cannot be imported" % name)

import sys
sys.meta_path = [ImportBlocker('chickenlib')]

But because I raise an error the build process stop --- I just want to silently ignore the import ... returning "None" does not work, too.
Is there a way to do this?

Body:
Referring to "silently ignore the import", you can try this:

def TryImport(module_name):
    try:
        import module_name
    except ImportError:
        pass #or anything to log


问:
How can one filter out a day(DATEPART) from a DATETIME value while declaring variables?
```<code>DECLARE     @LatestFlightDate DATETIME, @LFDay INT

SET  @LatestFlightDate = (
              SELECT        MAX(FlightDateTime)
          FROM              dbo.Flight
                        )

SET   @LFDay = (
    SELECT  DATEPART(DD, @LatestFlightDate)
    FROM    dbo.Flight
    )
         )
</code>```

答:
```<code>DECLARE @LatestFlightDate DATETIME, @LFDay INT

SELECT @LatestFlightDate = MAX(FlightDateTime) FROM dbo.Flight

SELECT @LFDay =  DATEPART(DD, @LatestFlightDate) FROM dbo.Flight
</code>```


问:
Add VAR as attribute name or description
I am calling a h4 text to use as the aria-label on a checkbox. Not the best way, however, I it is the only option I have on this project. I cab't get the variable to insert in the aria-label.

```<code>var prodname = $(".checkbox").closest("tr").find("td.product-shortdesc h4").text();
    console.log(prodname);
        $("td.select .checkbox").attr("aria-label", "'' +prodname+ '");
</code>```

Thanks for any help

答:
In that last line, it should be

$("td.select .checkbox").attr("aria-label", prodname);

Body:
I am calling a h4 text to use as the aria-label on a checkbox. Not the best way, however, I it is the only option I have on this project. I cab't get the variable to insert in the aria-label.

var prodname = $(".checkbox").closest("tr").find("td.product-shortdesc h4").text();
    console.log(prodname);
        $("td.select .checkbox").attr("aria-label", "'' +prodname+ '");

Thanks for any help


问:
Problems with React-Native v 0.45.0 on building on XCode
I initialized a react native project. It installed with 0.45.0 version of react-native.

XCode isn't able to build it.

There is a problem with config.hpp file.
Error is highlighted in red color, which says "'boost/config/user.hpp' file not found"

答:
Been struggling with this issue all day today. Looks like there might be something in the latest version of react-native that is causing the build issues. And I tried just about everything to fix it. </p>

<p>Not sure what the long-term solution is, but I just rolled back to 0.44.0 and that seems to be working for me as a temporary fix. </p>

```<code>react-native init MyAwesomeApp --version react-native@0.44.0
</code>```

Body:
Been struggling with this issue all day today. Looks like there might be something in the latest version of react-native that is causing the build issues. And I tried just about everything to fix it.

Not sure what the long-term solution is, but I just rolled back to 0.44.0 and that seems to be working for me as a temporary fix.

react-native init MyAwesomeApp --version react-native@0.44.0


问:
While working with QProgressBar: Cannot create children for a parent that is in a different thread
I tried to create QProgressBar according to Manual. Yet it works really bad (for instance, if I create QProgressDialog in the constructor, it will appear as soon as app is running, so I decided to use QProgressBar). But there is a problem:

Although I used advices from the internet. My code:

UPD![2]

```<code>// StudentAbsenceTableApp.h
using Job = std::function<void ()>;
Q_DECLARE_METATYPE(Job)
class StudentAbsenceTableApp{
public:
    StudentAbsenceTableApp(QWidget *parent = 0);

private:
    Q_SIGNAL void reqLoadFile(const QString& fileName);
    Q_SIGNAL void reqSaveFile(const QString& fileName);
    Q_SIGNAL void reqGui(const Job&);

    bool documentModified;
    QProgressBar *progressBar;
};

// StudentAbsenceTableApp.cpp
StudentAbsenceTableApp::StudentAbsenceTableApp(QWidget *parent)
   : QMainWindow(parent)
{
    // ...

    setStatusBar(new QStatusBar(this));

    qRegisterMetaType<Job>();
    progressBar = new QProgressBar(statusBar());
    progressBar->setMinimum(0);
    progressBar->setMaximum(0);
    progressBar->setMaximumWidth(150);
    progressBar->hide();
    statusBar()->addPermanentWidget(progressBar);

    connect(this, &StudentAbsenceTableApp::reqLoadFile, this, [this] (const QString& fileName){
        QtConcurrent::run(this, &StudentAbsenceTableApp::loadFile, fileName);
    });
    connect(this, &StudentAbsenceTableApp::reqGui, [this](const Job & job){
        job();
    });
}

// funtion that emit reqLoadFile(fileName)

bool StudentAbsenceTableApp::loadFile(const QString& fileName)
{
    reqGui([=] () { progressBar->show(); });
    auto xmlParser = XMLParser(model);

    try
    {
        reqGui([&] () {
            xmlParser.read(fileName);
            setCurrentFileName(fileName);
            statusBar()->showMessage(tr("Файл загружен"), 2000);
            documentModified = false;
        });
    }
    catch(FileOpenException)
    {
        reqGui([=] () {
            QMessageBox::warning(this, "Ошибка!", "Ошибка открытия файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
        });
        return false;
    }
    catch(FileReadException)
    {
        reqGui([=] () {
            QMessageBox::warning(this, "Ошибка!", "Ошибка чтения файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
        });
        return false;
    }

    reqGui([=] () { progressBar->hide(); });
    return true;
}
</code>```

I don't know how to write code, that is possible to compile, because there is a lot of code.

答:
No QWidget (and derived classes) methods provided by Qt are thread-safe. Thus you can't access QProgressBar nor any other widgets from any thread other then the GUI thread.

The experimentFunction runs in a non-GUI thread and thus must not access widgets. You must figure out some other means of communication, e.g. using signals and slots. Recall that you're free to emit signals in experimentFunction, since the signal implementations are by contract thread-safe.

It's all really simple, and you don't need the future watcher. In your attempts to "fix" the issue, you've hopelessly combobulated your code.

For other ways of invoking methods safely across threads, see this question and that question.

```<code>// https://github.com/KubaO/stackoverflown/tree/master/questions/thread-progress-future-44445248
#include <QtConcurrent>
#include <QtWidgets>
#include <exception>
#include <functional>

struct FileOpenException : std::exception {};
struct FileReadException : std::exception {};
struct Model {};
struct XMLParser {
   XMLParser(Model &) {}
   void read(const QString &) {
      static int outcome;
      QThread::sleep(3);
      switch (outcome++ % 3) {
      case 0: return;
      case 1: throw FileOpenException();
      case 2: throw FileReadException();
      }
   }
};

using Job = std::function<void()>;
Q_DECLARE_METATYPE(Job)

class StudentAbsenceTable : public QMainWindow {
   Q_OBJECT
   QStatusBar m_statusBar;
   QProgressBar m_progress;
   QPushButton m_start{"Start Concurrent Task"};
   Model m_model;
   bool m_documentModified = {};
public:
   StudentAbsenceTable() {
      qRegisterMetaType<Job>();
      m_statusBar.addPermanentWidget(&m_progress);
      m_progress.setMinimum(0);
      m_progress.setMaximum(0);
      m_progress.setMaximumWidth(150);
      m_progress.hide();
      setStatusBar(&m_statusBar);
      setCentralWidget(&m_start);
      connect(&m_start, &QPushButton::clicked, this, [this]{
         m_start.setEnabled(false);
         QtConcurrent::run(this, &StudentAbsenceTable::loadFile);
      });
      connect(this, &StudentAbsenceTable::reqGui, this, [this](const Job & job){
         job();
      });
   }
private:
   bool loadFile() {
      reqGui([=]{ m_progress.show(); });
      auto fileName = QStringLiteral("/media/bsuir/data.xml");
      auto xmlParser = XMLParser(m_model);
      try {
         xmlParser.read(fileName);
         reqGui([=]{
            setCurrentFileName(fileName);
            statusBar()->showMessage(tr("Файл загружен"), 2000);
            m_documentModified = false;
         });
      }
      catch(FileOpenException&) {
         reqGui([=]{
            QMessageBox::warning(this, "Ошибка!", "Ошибка открытия файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
         });
      }
      catch(FileReadException&) {
         reqGui([=]{
            QMessageBox::warning(this, "Ошибка!", "Ошибка чтения файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
         });
      }
      reqGui([=]{ m_progress.hide(); m_start.setEnabled(true); });
      return false;
   }
   Q_SIGNAL void reqGui(const Job &);
   void setCurrentFileName(const QString &) {}
};

int main(int argc, char ** argv) {
   QApplication app(argc, argv);
   StudentAbsenceTable ui;
   ui.setMinimumSize(350, 350);
   ui.show();
   return app.exec();
}
#include "main.moc"
</code>```

Body:
I tried to create QProgressBar according to Manual. Yet it works really bad (for instance, if I create QProgressDialog in the constructor, it will appear as soon as app is running, so I decided to use QProgressBar). But there is a problem:

Although I used advices from the internet. My code:

UPD![2]

// StudentAbsenceTableApp.h
using Job = std::function<void ()>;
Q_DECLARE_METATYPE(Job)
class StudentAbsenceTableApp{
public:
    StudentAbsenceTableApp(QWidget *parent = 0);

private:
    Q_SIGNAL void reqLoadFile(const QString& fileName);
    Q_SIGNAL void reqSaveFile(const QString& fileName);
    Q_SIGNAL void reqGui(const Job&);

    bool documentModified;
    QProgressBar *progressBar;
};

// StudentAbsenceTableApp.cpp
StudentAbsenceTableApp::StudentAbsenceTableApp(QWidget *parent)
   : QMainWindow(parent)
{
    // ...

    setStatusBar(new QStatusBar(this));

    qRegisterMetaType<Job>();
    progressBar = new QProgressBar(statusBar());
    progressBar->setMinimum(0);
    progressBar->setMaximum(0);
    progressBar->setMaximumWidth(150);
    progressBar->hide();
    statusBar()->addPermanentWidget(progressBar);

    connect(this, &StudentAbsenceTableApp::reqLoadFile, this, [this] (const QString& fileName){
        QtConcurrent::run(this, &StudentAbsenceTableApp::loadFile, fileName);
    });
    connect(this, &StudentAbsenceTableApp::reqGui, [this](const Job & job){
        job();
    });
}

// funtion that emit reqLoadFile(fileName)

bool StudentAbsenceTableApp::loadFile(const QString& fileName)
{
    reqGui([=] () { progressBar->show(); });
    auto xmlParser = XMLParser(model);

    try
    {
        reqGui([&] () {
            xmlParser.read(fileName);
            setCurrentFileName(fileName);
            statusBar()->showMessage(tr("Файл загружен"), 2000);
            documentModified = false;
        });
    }
    catch(FileOpenException)
    {
        reqGui([=] () {
            QMessageBox::warning(this, "Ошибка!", "Ошибка открытия файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
        });
        return false;
    }
    catch(FileReadException)
    {
        reqGui([=] () {
            QMessageBox::warning(this, "Ошибка!", "Ошибка чтения файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
        });
        return false;
    }

    reqGui([=] () { progressBar->hide(); });
    return true;
}

I don't know how to write code, that is possible to compile, because there is a lot of code.

Body:
No QWidget (and derived classes) methods provided by Qt are thread-safe. Thus you can't access QProgressBar nor any other widgets from any thread other then the GUI thread.

The experimentFunction runs in a non-GUI thread and thus must not access widgets. You must figure out some other means of communication, e.g. using signals and slots. Recall that you're free to emit signals in experimentFunction, since the signal implementations are by contract thread-safe.

It's all really simple, and you don't need the future watcher. In your attempts to "fix" the issue, you've hopelessly combobulated your code.

For other ways of invoking methods safely across threads, see this question and that question.

// https://github.com/KubaO/stackoverflown/tree/master/questions/thread-progress-future-44445248
#include <QtConcurrent>
#include <QtWidgets>
#include <exception>
#include <functional>

struct FileOpenException : std::exception {};
struct FileReadException : std::exception {};
struct Model {};
struct XMLParser {
   XMLParser(Model &) {}
   void read(const QString &) {
      static int outcome;
      QThread::sleep(3);
      switch (outcome++ % 3) {
      case 0: return;
      case 1: throw FileOpenException();
      case 2: throw FileReadException();
      }
   }
};

using Job = std::function<void()>;
Q_DECLARE_METATYPE(Job)

class StudentAbsenceTable : public QMainWindow {
   Q_OBJECT
   QStatusBar m_statusBar;
   QProgressBar m_progress;
   QPushButton m_start{"Start Concurrent Task"};
   Model m_model;
   bool m_documentModified = {};
public:
   StudentAbsenceTable() {
      qRegisterMetaType<Job>();
      m_statusBar.addPermanentWidget(&m_progress);
      m_progress.setMinimum(0);
      m_progress.setMaximum(0);
      m_progress.setMaximumWidth(150);
      m_progress.hide();
      setStatusBar(&m_statusBar);
      setCentralWidget(&m_start);
      connect(&m_start, &QPushButton::clicked, this, [this]{
         m_start.setEnabled(false);
         QtConcurrent::run(this, &StudentAbsenceTable::loadFile);
      });
      connect(this, &StudentAbsenceTable::reqGui, this, [this](const Job & job){
         job();
      });
   }
private:
   bool loadFile() {
      reqGui([=]{ m_progress.show(); });
      auto fileName = QStringLiteral("/media/bsuir/data.xml");
      auto xmlParser = XMLParser(m_model);
      try {
         xmlParser.read(fileName);
         reqGui([=]{
            setCurrentFileName(fileName);
            statusBar()->showMessage(tr("Файл загружен"), 2000);
            m_documentModified = false;
         });
      }
      catch(FileOpenException&) {
         reqGui([=]{
            QMessageBox::warning(this, "Ошибка!", "Ошибка открытия файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
         });
      }
      catch(FileReadException&) {
         reqGui([=]{
            QMessageBox::warning(this, "Ошибка!", "Ошибка чтения файла!", QMessageBox::Ok);
            statusBar()->showMessage(tr("Загрузка отменена"), 2000);
         });
      }
      reqGui([=]{ m_progress.hide(); m_start.setEnabled(true); });
      return false;
   }
   Q_SIGNAL void reqGui(const Job &);
   void setCurrentFileName(const QString &) {}
};

int main(int argc, char ** argv) {
   QApplication app(argc, argv);
   StudentAbsenceTable ui;
   ui.setMinimumSize(350, 350);
   ui.show();
   return app.exec();
}
#include "main.moc"


问:
AWS iOS Cognito - How To Check For a User in a Userpool?
I am just starting to work with, and learn AWS. I am using the services in the AWS Mobile Hub and so far have set up the Sign In & Sign Up methods.

Everything works fine, and now I am working on the Forgot Password and Update Password.

Problem:

The problem is, is that the way AWS has set up the Forgot Password is that:

You first enter a username and then after the user enters a username AWS sends a verification code via SMS to the phone number associated
    with that username.

That's an issue because it means that anyone can enter any username and a text message will be sent, resulting in my SMS payments increasing and to be honest it just looks sloppy.

What I want to have done is that:

After a user enters a username, they then have to enter the phone number associated with the account

Then if it matches, it sends the SMS.

Question

How do I check if a user exists in a userpool?

And then if it does, how do I get the user attribute associated with the phone number to check if it matches the phone number that the user enters?

Is this even possible? Can I even get the credentials of a user who isn't the one logged in?

Thanks in advance!

答:
Here is how you should do it:
1) Create a web API using the APIGateway. Ideally you want to restrict access with an API Key, which you should bundle with your application.
2) Connect a POST method to a Lambda function, which will
  (a) perform the necessary checks (whether the phone number specified is indeed the correct one, etc), calling the admin_* functions.
  (b) issue the client version of the password reset, which will trigger the sending of the SMS code.</p>


问:
using data from java classes and methods
i have an entry level question:

if there is external java class let's say 'Class1' inside this class there is a method called 'method1' inside this method there is Override method 'onResponse' inside this method two variables is being set 'a' and 'b'.

in the android mainActivity i called the method from the class like this:

```<code>Class1.method1();
</code>```

after calling the method how i can retrieve these variables to be used in mainActivity...

thanks..

```<code>public abstract class Class1 extends Context {

final Context mcontext;

public static void method1(final Context mcontext, final String x){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                        String a = userDetails.getString("a");
                        String b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}
</code>```

答:
Why not create a wrapper class for a and b

```<code>public class Details {
    public string a;
    public string b;
}
</code>```

and then read/return it in the method1

```<code>public abstract class Class1 extends Context {

final Context mcontext;

public static Details method1(final Context mcontext, final String x){

    Details data = new Details;

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                         data.a = userDetails.getString("a");
                         data.b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);

    return data;
}
</code>```

Body:
i have an entry level question:

if there is external java class let's say 'Class1' inside this class there is a method called 'method1' inside this method there is Override method 'onResponse' inside this method two variables is being set 'a' and 'b'.

in the android mainActivity i called the method from the class like this:

Class1.method1();

after calling the method how i can retrieve these variables to be used in mainActivity...

thanks..

public abstract class Class1 extends Context {

final Context mcontext;

public static void method1(final Context mcontext, final String x){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                        String a = userDetails.getString("a");
                        String b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}

Body:
Why not create a wrapper class for a and b

public class Details {
    public string a;
    public string b;
}

and then read/return it in the method1

public abstract class Class1 extends Context {

final Context mcontext;

public static Details method1(final Context mcontext, final String x){

    Details data = new Details;

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                         data.a = userDetails.getString("a");
                         data.b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);

    return data;
}


问:
R get rows based on multiple conditions - use dplyr and reshape2
```<code>df <- data.frame(
    exp=c(1,1,2,2),
  name=c("gene1", "gene2", "gene1", "gene2"),
    value=c(1,1,3,-1)
    )
</code>```

In trying to get customed to the dplyr and reshape2I stumbled over a "simple" way to select rows based on several conditions. If I want to have those genes (the namevariable) that have valueabove 0 in experiment 1 (exp== 1) AND at the same time valuebelow 0 in experiment 2; in df this would be "gene2". Sure there must be many ways to this, e.g. subset df for each set of conditions (exp==1 & value > 0, and exp==2 and value < 0) and then join the results of these subset:

```<code>library(dplyr)
inner_join(filter(df,exp == 1 & value > 0),filter(df,exp == 2 & value < 0), by= c("name"="name"))[[1]]
</code>```

Although this works it looks very akward, and I feel that such conditioned filtering lies at the heart of reshape2 and dplyr but cannot figure out how to do this. Can someone enlighten me here?

答:
filter allows multiple parameters with comma, sames as select. Each extra condition is an AND:

group_by(df, name) %>% filter(value[exp == 1] > 0, value[exp == 2] < 0)

From official documentation: https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html

The examples shown there are:

flights[flights$month == 1 & flights$day == 1, ] in base R

filter(flights, month == 1, day == 1) in dplyr.

Body:
df <- data.frame(
    exp=c(1,1,2,2),
  name=c("gene1", "gene2", "gene1", "gene2"),
    value=c(1,1,3,-1)
    )

In trying to get customed to the dplyr and reshape2I stumbled over a "simple" way to select rows based on several conditions. If I want to have those genes (the namevariable) that have valueabove 0 in experiment 1 (exp== 1) AND at the same time valuebelow 0 in experiment 2; in df this would be "gene2". Sure there must be many ways to this, e.g. subset df for each set of conditions (exp==1 & value > 0, and exp==2 and value < 0) and then join the results of these subset:

library(dplyr)
inner_join(filter(df,exp == 1 & value > 0),filter(df,exp == 2 & value < 0), by= c("name"="name"))[[1]]

Although this works it looks very akward, and I feel that such conditioned filtering lies at the heart of reshape2 and dplyr but cannot figure out how to do this. Can someone enlighten me here?


问:
Vagrant 1.9.5: setting permissions for the default synced folders
I need to set permissions and ownership to /vagrant in my ubuntu/xenial64 box, and I have found several great solutions for config options in the Vagrant file. My problem however is this - and I couldn't find an answer to it:
My default Vagrant file (Vagrant 1.9.5) doesn't have any config on synced folders. Yet the the project dir gets synced alright to /vagrant in the guest. So that's fine.

But if I add any config to the Vagrant file, like for example:

```<code>    config.vm.synced_folder ".", "/vagrant",
    mount_options: ["dmode=755, fmode=644"]
</code>```

I get an error on vagrant up, which basically tells me Guest Additions are not installed on the box. So obviously vagrant interprets my directives as referring to additional synced folders, which I don't need.

```<code>    Vagrant was unable to mount VirtualBox shared folders. This is usually
    because the filesystem "vboxsf" is not available. This filesystem is
    made available via the VirtualBox Guest Additions and kernel module.
    Please verify that these guest additions are properly installed in the
    guest...
</code>```

Basically I don't understand where I can set options for the default synced folders?

答:
So a solution to this question would be to just disable the default synced folder in the Vagrantfile, like so

```<code>config.vm.synced_folder ".", "/vagrant", disabled: true
</code>```

and then specifically set the desired options for syncing the folders, like for example

```<code>config.vm.synced_folder ".", "/vagrant_dev_shg",
    owner: "vagrant",
    group: "www-data",
    mount_options: ["dmode=775,fmode=644"]
</code>```

Body:
I need to set permissions and ownership to /vagrant in my ubuntu/xenial64 box, and I have found several great solutions for config options in the Vagrant file. My problem however is this - and I couldn't find an answer to it:
My default Vagrant file (Vagrant 1.9.5) doesn't have any config on synced folders. Yet the the project dir gets synced alright to /vagrant in the guest. So that's fine.

But if I add any config to the Vagrant file, like for example:

    config.vm.synced_folder ".", "/vagrant",
    mount_options: ["dmode=755, fmode=644"]

I get an error on vagrant up, which basically tells me Guest Additions are not installed on the box. So obviously vagrant interprets my directives as referring to additional synced folders, which I don't need.

    Vagrant was unable to mount VirtualBox shared folders. This is usually
    because the filesystem "vboxsf" is not available. This filesystem is
    made available via the VirtualBox Guest Additions and kernel module.
    Please verify that these guest additions are properly installed in the
    guest...

Basically I don't understand where I can set options for the default synced folders?

Body:
So a solution to this question would be to just disable the default synced folder in the Vagrantfile, like so

config.vm.synced_folder ".", "/vagrant", disabled: true

and then specifically set the desired options for syncing the folders, like for example

config.vm.synced_folder ".", "/vagrant_dev_shg",
    owner: "vagrant",
    group: "www-data",
    mount_options: ["dmode=775,fmode=644"]


问:
Angular can't read property data of undefined
I'm having an issue with calling my data from a json file.  When I click a button to have it appear in a textarea, it does nothing for the first click, but works like expected after that.  What the program does is gets an id from dashboard and based on that id grabs different json file to pull in.
The program shows an error of:

ERROR TypeError: Cannot read property 'data' of undefined
    at StepService.webpackJsonp.102.StepService.populateList (step.service.ts:69)
    at CalibrationDetailComponent.webpackJsonp.101.CalibrationDetailComponent.next

step.service.ts

```<code>private jsonData: any; //Json data
public list: String[] = []; //Holds the list of steps
public listLength: number; //Length of the list
public listCurrent: number = 0; //Current step the list is on

//Gets the json file
  public getJson(): Observable<any> {
    return this.http.get(this.jsonUrl)
      .map(response => response.json());
  }

  //Subscribe
  public subScribe2Json() {
    this.getJson().subscribe(data => (this.jsonData = data));
  }

  //Populates the list from the json so I can pull out specific steps
  public populateList() {
    this.jsonData.data.forEach(element => { //The line that throws the error
      this.list.push(element.name);
    });
    this.listLength = this.list.length;
  }

  //Returns the mainStepText with the current step
  public getJsonData(): String {
    this.mainStepText = this.list[this.listCurrent];
    return this.mainStepText;
  }
</code>```

calibration-detail.component.ts

next button method

```<code>next() { //Advances step
    this.stepService.subScribe2Json();
    if (this.stepService.listCurrent < 1) { //Makes sure only runs once to populate the list
      this.stepService.populateList(); //Populates list from the json array
     }
    if (this.stepService.listCurrent < this.stepService.listLength) { //make sure dont go past number of steps
        this.stepService.subScribe2Json(); //Sub to list
        this.mainStepText = this.stepService.getJsonData(); //Grab the data from the list and output to main textarea
        this.stepService.listCurrent ++; //Increments the step
</code>```

答:
This is not a complete solution but an answer to what the problem is. And direct your thought into the right direction depending on what you want to achieve.

You call

```<code>this.stepService.subScribe2Json();
if (this.stepService.listCurrent < 1) {
...
</code>```

this calls the first method and immediately the second without waiting for the data. And then of course it fails because it is not there yet.

Depending on your use case you could either return the Observable (maybe change it to a Promise,... not 100% sure) and then:

```<code>return this.getJson().subscribe(data => (this.jsonData = data));
</code>```

and something like

```<code>this.stepService.subScribe2Json().then(/* do all stuff here */);
</code>```

or initialize

```<code>private jsonData: any = [];
</code>```

but here of course you don't have anything on the first run.

Body:
I'm having an issue with calling my data from a json file.  When I click a button to have it appear in a textarea, it does nothing for the first click, but works like expected after that.  What the program does is gets an id from dashboard and based on that id grabs different json file to pull in.
The program shows an error of:

ERROR TypeError: Cannot read property 'data' of undefined
    at StepService.webpackJsonp.102.StepService.populateList (step.service.ts:69)
    at CalibrationDetailComponent.webpackJsonp.101.CalibrationDetailComponent.next

step.service.ts

private jsonData: any; //Json data
public list: String[] = []; //Holds the list of steps
public listLength: number; //Length of the list
public listCurrent: number = 0; //Current step the list is on

//Gets the json file
  public getJson(): Observable<any> {
    return this.http.get(this.jsonUrl)
      .map(response => response.json());
  }

  //Subscribe
  public subScribe2Json() {
    this.getJson().subscribe(data => (this.jsonData = data));
  }

  //Populates the list from the json so I can pull out specific steps
  public populateList() {
    this.jsonData.data.forEach(element => { //The line that throws the error
      this.list.push(element.name);
    });
    this.listLength = this.list.length;
  }

  //Returns the mainStepText with the current step
  public getJsonData(): String {
    this.mainStepText = this.list[this.listCurrent];
    return this.mainStepText;
  }

calibration-detail.component.ts

next button method

next() { //Advances step
    this.stepService.subScribe2Json();
    if (this.stepService.listCurrent < 1) { //Makes sure only runs once to populate the list
      this.stepService.populateList(); //Populates list from the json array
     }
    if (this.stepService.listCurrent < this.stepService.listLength) { //make sure dont go past number of steps
        this.stepService.subScribe2Json(); //Sub to list
        this.mainStepText = this.stepService.getJsonData(); //Grab the data from the list and output to main textarea
        this.stepService.listCurrent ++; //Increments the step

Body:
This is not a complete solution but an answer to what the problem is. And direct your thought into the right direction depending on what you want to achieve.

You call

this.stepService.subScribe2Json();
if (this.stepService.listCurrent < 1) {
...

this calls the first method and immediately the second without waiting for the data. And then of course it fails because it is not there yet.

Depending on your use case you could either return the Observable (maybe change it to a Promise,... not 100% sure) and then:

return this.getJson().subscribe(data => (this.jsonData = data));

and something like

this.stepService.subScribe2Json().then(/* do all stuff here */);

or initialize

private jsonData: any = [];

but here of course you don't have anything on the first run.


问:
cond fails when I add a puts function
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

```<code>   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end
</code>```

Is this the correct syntax for cond ? Why this error seems so random ?

答:
That is because the anonymous function you pass to Enum.reduce/3 must return the table at the end.

When you execute IO.puts("TEST"), it returns :ok so the next iteration table will be bounded to :ok instead of a map and it will fail, because put_in/3 expects a map.

Try to move the IO.puts/1 above the put_in/3 call

Title: cond fails when I add a puts function

Body:
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end

Is this the correct syntax for cond ? Why this error seems so random ?


问:
Why do I get a ConcurrentModificationException?
Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin() method is being used to locate the min in the list pq, remove it, and return its value

```<code>import java.util.Iterator;
import java.util.LinkedList;

public class test1 {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);

        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator<Integer> itPQ = pq.iterator();

        // Put contents of list into pq
        for (int i = 0; i < list.size(); i++) {
            pq.add(list.removeFirst());
        }

        int min = Integer.MAX_VALUE;
        int pos = 0;
        int remPos = 0;

        while (itPQ.hasNext()) {
            Integer element = itPQ.next(); // I get ConcurrentModificationException here
            if (element < min) {
                min = element;
                remPos = pos;
            }
            pos++;
        }

        pq.remove(remPos);
        return remPos;
    }

}
</code>```

答:
You face an issue because you added items to pq, using the normal .add() method after you had already created an Iterator for pq. The Iterator doesn't complain when you do the hasNext() because it sees the change in pq.

```<code>while (itPQ.hasNext()) {
    ...
    Integer element = itPQ.next(); --> you get exception here
    ...
</code>```

}

However, it throws an exception when you attempt to iterate through pq. According to this post,  "If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception."

Body:
Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin() method is being used to locate the min in the list pq, remove it, and return its value

import java.util.Iterator;
import java.util.LinkedList;

public class test1 {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);

        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator<Integer> itPQ = pq.iterator();

        // Put contents of list into pq
        for (int i = 0; i < list.size(); i++) {
            pq.add(list.removeFirst());
        }

        int min = Integer.MAX_VALUE;
        int pos = 0;
        int remPos = 0;

        while (itPQ.hasNext()) {
            Integer element = itPQ.next(); // I get ConcurrentModificationException here
            if (element < min) {
                min = element;
                remPos = pos;
            }
            pos++;
        }

        pq.remove(remPos);
        return remPos;
    }

}

Body:
You face an issue because you added items to pq, using the normal .add() method after you had already created an Iterator for pq. The Iterator doesn't complain when you do the hasNext() because it sees the change in pq.

while (itPQ.hasNext()) {
    ...
    Integer element = itPQ.next(); --> you get exception here
    ...

}

However, it throws an exception when you attempt to iterate through pq. According to this post,  "If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception."