问:
Replicate STUFF in Snowflake SQL
Hello Snowflake Community,

I am attempting to replicate the STUFF function in Snowflake. I didn't find a like-named function on the reference list and so was hoping someone could point me in the right direction?

Googled example

Thank you good folks

DU

答:
Adding on what Gordon provided, if you want a user defined function to reduce the amount of conversions you have to write, this one should work:</p>

```<code>create or replace function STUFF(S string, STARTPOS int, LENGTH int, NEWSTRING string)
returns string
language SQL
as
$$
left(S, STARTPOS) || NEWSTRING || substr(S, STARTPOS + LENGTH + 1)
$$;
</code>```

Title: Replicate STUFF in Snowflake SQL

Body:
Adding on what Gordon provided, if you want a user defined function to reduce the amount of conversions you have to write, this one should work:

create or replace function STUFF(S string, STARTPOS int, LENGTH int, NEWSTRING string)
returns string
language SQL
as
$$
left(S, STARTPOS) || NEWSTRING || substr(S, STARTPOS + LENGTH + 1)
$$;


来源: stackexchange

问:
How to update my local master branch to include changes made to my local feature branch that are up-to-date on origin (remote) master?
TLDR: My local feature branch has merged with remote origin/master, but my local master is not merging with remote master ("already up to date") and git pull/fetch doesn't work.

The origin/master (remote) repo that I can see on github that my team is working on is up-to-date and working. It includes everything from both my master branch and feature branch.

My local master branch is missing data from the feature branch and is behind my team's remote origin/master.

My local feature branch is ahead of my local master branch but behind the origin/master.

How do I synchronize my local branches to be at the same level?

When I git pull/fetch on my local master it says it's up to date, but it's not.

Why did this happen? Should I have only merged my local feature with my local master branch, and then only merge my local master with remote origin/master?

Edit: It seems like my branches have only pulled from remote/origin master when I have pushed my changes.

答:
If you already merge your feature to master and don't have any missing changes on master, you can simple reset your master to origin. Go to master branch and try: git reset --hard origin/master.

I'm not sure why this happens, but already happened to me and I fix by this way.

ContentLicense: CC BY-SA 4.0


问:
"too few template arguments error" when using a template class with default template parameter in c++
I had a class that worked fine. I wanted to change it to a template class. Suppose I have now:

```<code>template <MyTypes::smallType T = Mytypes::myInt>
class A{....}
</code>```

Now assume that the class A is used in many other hpp and cpp files, sometimes by including the header file and sometimes by forward declaration as:

```<code>template <MyTypes::smallType T> class A;
</code>```

And it is mostly used as std::shared_ptr<A<>> in other classes and function calls.

Now assume that I have another class B which is very similar to A, but used in fewer places (still in other cpp files through forward declaration), and not in a shared_ptr.

```<code>template <MyTypes::smallType T = Mytypes::myInt>
class B{....}
</code>```

When trying to compile, I get the error "too few template arguments" for A<>, but not for B<>. The project is very large and I do not have a guess in order to produce a simple example with the same problem. Could you help me (even by gusses), what might be causing the problem? Can it be shared_ptr? Can it be some typedefs in the form of typedef std::shared_ptr<A<>> APtr? I also get the error "unspecialized class template or generic can't be used as a template or generic argument for template or generic parameter 'param', expected a real type" if that can help with guesses.

I would appreciate your help.

答:
Quite simply, the forward declaration needs the default parameters. Simply look at it this way, in simplified form:

```<code>template<class T> A;
std::shared_ptr<A<>> a;
</code>```

When the compiler sees this, that is all the information it has. So, in this case, A<> is obviously missing a type for its template parameters. Now, if you do:

```<code>template<class T = int> A;
std::shared_ptr<A<>> a;
</code>```

Then the compiler can deduce that A<> is really A<int>.

Here's the problem with that though. From [temp.param]/12

A template-parameter shall not be given default arguments by two different declarations in the same scope.

```<code>[ Example:
template<class T = int> class X;
template<class T = int> class X { /* ... */ }; // error
—end example ]
</code>```

So, if you use a default parameter on your forward declaration, you can't use it on the template itself. Fun times.

A cheat to get around this is to have an extra header file which contains just the forward declaration of the template with default params, and all files using the template include that, instead of the full definition of the template (until the full definition is required), including the template's definition. The template definition would not need the default parameters. Not very fun, but it would work.

Alternatively, don't forward declare.

See examples here

Body:
I had a class that worked fine. I wanted to change it to a template class. Suppose I have now:

template <MyTypes::smallType T = Mytypes::myInt>
class A{....}

Now assume that the class A is used in many other hpp and cpp files, sometimes by including the header file and sometimes by forward declaration as:

template <MyTypes::smallType T> class A;

And it is mostly used as std::shared_ptr<A<>> in other classes and function calls.

Now assume that I have another class B which is very similar to A, but used in fewer places (still in other cpp files through forward declaration), and not in a shared_ptr.

template <MyTypes::smallType T = Mytypes::myInt>
class B{....}

When trying to compile, I get the error "too few template arguments" for A<>, but not for B<>. The project is very large and I do not have a guess in order to produce a simple example with the same problem. Could you help me (even by gusses), what might be causing the problem? Can it be shared_ptr? Can it be some typedefs in the form of typedef std::shared_ptr<A<>> APtr? I also get the error "unspecialized class template or generic can't be used as a template or generic argument for template or generic parameter 'param', expected a real type" if that can help with guesses.

I would appreciate your help.

Body:
Quite simply, the forward declaration needs the default parameters. Simply look at it this way, in simplified form:

template<class T> A;
std::shared_ptr<A<>> a;

When the compiler sees this, that is all the information it has. So, in this case, A<> is obviously missing a type for its template parameters. Now, if you do:

template<class T = int> A;
std::shared_ptr<A<>> a;

Then the compiler can deduce that A<> is really A<int>.

Here's the problem with that though. From [temp.param]/12

A template-parameter shall not be given default arguments by two different declarations in the same scope.

[ Example:
template<class T = int> class X;
template<class T = int> class X { /* ... */ }; // error
—end example ]

So, if you use a default parameter on your forward declaration, you can't use it on the template itself. Fun times.

A cheat to get around this is to have an extra header file which contains just the forward declaration of the template with default params, and all files using the template include that, instead of the full definition of the template (until the full definition is required), including the template's definition. The template definition would not need the default parameters. Not very fun, but it would work.

Alternatively, don't forward declare.

See examples here


问:
Laravel Voyager not showing images
I have created a Laravel app using installatron on godaddy.com (shared hosting). After installing Voyager the default admin avatar is not showing. The storage link is automatically created by Voyager. But when I open the admin panel voyager tries to get admin avatar from [app_url]/storage/users/default.png and receives a 404. The avatar is at [app_url]/public/storage/users/default.png

Screenshot

Versions:
Laravel: 5.8
Voyager: 1.3

答:
I've faced the exact same issue before, after checking the APP_URL, go ahead and execute

```<code>php artisan config:clear
</code>```

After that try again.

If it doesn't work, delete the symlink storage in public/ and execute

```<code>php artisan storage:link
</code>```

Title: Laravel Voyager not showing images

Body:
I've faced the exact same issue before, after checking the APP_URL, go ahead and execute

php artisan config:clear

After that try again.

If it doesn't work, delete the symlink storage in public/ and execute

php artisan storage:link


问:
CSS, Images, JS not loading in IIS
My all applications were working fine but suddenly all sites under IIS are not loading css, images, scripts. It redirect to login page.

If i login it works fine. e.g. mysite.com/Account/LogOn?ReturnUrl=%2fpublic%2fimages%2ficons%2f41.png

On my local machine it works fine without login.

答:
In my case when none of my javascript, png, or css files were getting loaded I tried most of the answers above and none seemed to do the trick.

I finally found "Request Filters", and actually had to add .js, .png, .css as an enabled/accepted file type.

Once I made this change, all files were being served properly.

ContentLicense: CC BY-SA 3.0

Title: CSS, Images, JS not loading in IIS


问:
The method getApplicationContext() is undefined - fragment issues
I am getting the following errors:
The method getApplicationContext() is undefined
The method findViewById(int) is undefined for the type Fragment1

These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.

Any help would be greatly appreciated.
Thanks in advance.

Below is the code

```<code>public class Fragment1 extends Fragment {

    private String currentUserId;
    private ArrayAdapter<String> namesArrayAdapter;
    private ArrayList<String> names;
    private ListView usersListView;
    private Button logoutButton;
    String userGender = ParseUser.getCurrentUser().getString("Gender");
    String activityName = ParseUser.getCurrentUser().getString("ActivityName");
    Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");

    String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
    Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
    Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
    Number userage = ParseUser.getCurrentUser().getNumber("Age");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
                container,false);

    logoutButton = (Button) findViewById(R.id.logoutButton);
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ParseUser.logOut();
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
        }
    });

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();

    //  query.whereEqualTo("ActivityName",userActivitySelectionName);

    query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
    // users with Gender = currentUser.Looking_Gender
    query.whereEqualTo("Gender", userLookingGender);
    // users with Looking_Gender = currentUser.Gender
    query.whereEqualTo("Looking_Gender", userGender);
    query.setLimit(1);
    query.whereEqualTo("ActivityName", activityName);
    query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage);
    query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage);
    //  query.whereWithinKilometers("Maximum_Distance", point, maxDistance)

    query.findInBackground(new FindCallback<ParseUser>() {

        public void done(List<ParseUser> userList, ParseException e) {
            if (e == null) {
                for (int i=0; i<userList.size(); i++) {
                    names.add(userList.get(i).get("Name").toString());
                    names.add(userList.get(i).get("Headline").toString());
                    names.add(userList.get(i).get("Age").toString());

                    //       names.add(userList.get(i).getParseObject("ProfilePicture").;

                }

                usersListView = (ListView)findViewById(R.id.usersListView);
                namesArrayAdapter =
                        new ArrayAdapter<String>(getApplicationContext(),
                                R.layout.user_list_item, names);
                usersListView.setAdapter(namesArrayAdapter);

                usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
                        openConversation(names, i);
                    }
                });

            } else {
                Toast.makeText(getApplicationContext(),
                        "Error loading user list",
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

public void openConversation(ArrayList<String> names, int pos) {
    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("Name", names.get(pos));
    query.findInBackground(new FindCallback<ParseUser>() {
        public void done(List<ParseUser> user, ParseException e) {
            if (e == null) {
                Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
                intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error finding that user",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}
</code>```

Update
Unreachable code error for setConversationList

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
                container,false);

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();
</code>```

Update

Upon launching the activity, I received the following message:

```<code>08-15 14:52:16.365: E/AndroidRuntime(3332): FATAL EXCEPTION: main
08-15 14:52:16.365: E/AndroidRuntime(3332): Process: com.dooba.beta, PID: 3332
08-15 14:52:16.365: E/AndroidRuntime(3332): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.usermatch}: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.os.Looper.loop(Looper.java:136)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at java.lang.reflect.Method.invoke(Method.java:515)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at dalvik.system.NativeStart.main(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): Caused by: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.dooba.beta.usermatch.initialisePaging(usermatch.java:32)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.dooba.beta.usermatch.onCreate(usermatch.java:20)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.Activity.performCreate(Activity.java:5231)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-15 14:52:16.365: E/AndroidRuntime(3332):     ... 11 more
</code>```

Below is the activity page that calls for the fragment

```<code>import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class usermatch extends FragmentActivity {
    private PageAdapter mPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager_layout);
        initialisePaging();

    }

    private void initialisePaging() {
        // TODO Auto-generated method stub
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
        mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(mPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mood, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

Update 2
Below is the message I receive in logcat

```<code>08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main
08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974
08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.dooba.beta.Fragment1$1.done(Fragment1.java:108)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:45)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:1)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.Parse$6$1.run(Parse.java:888)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.handleCallback(Handler.java:733)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Looper.loop(Looper.java:136)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invoke(Method.java:515)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
you can access context from onAttach() like below example</p>

```<code> @Override
    public void onAttach(@NonNull Context context) {

        super.onAttach(context);
    }
</code>```

Body:
I am getting the following errors:
The method getApplicationContext() is undefined
The method findViewById(int) is undefined for the type Fragment1

These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.

Any help would be greatly appreciated.
Thanks in advance.

Below is the code

public class Fragment1 extends Fragment {

    private String currentUserId;
    private ArrayAdapter<String> namesArrayAdapter;
    private ArrayList<String> names;
    private ListView usersListView;
    private Button logoutButton;
    String userGender = ParseUser.getCurrentUser().getString("Gender");
    String activityName = ParseUser.getCurrentUser().getString("ActivityName");
    Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");

    String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
    Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
    Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
    Number userage = ParseUser.getCurrentUser().getNumber("Age");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
                container,false);

    logoutButton = (Button) findViewById(R.id.logoutButton);
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ParseUser.logOut();
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
        }
    });

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();

    //  query.whereEqualTo("ActivityName",userActivitySelectionName);

    query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
    // users with Gender = currentUser.Looking_Gender
    query.whereEqualTo("Gender", userLookingGender);
    // users with Looking_Gender = currentUser.Gender
    query.whereEqualTo("Looking_Gender", userGender);
    query.setLimit(1);
    query.whereEqualTo("ActivityName", activityName);
    query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage);
    query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage);
    //  query.whereWithinKilometers("Maximum_Distance", point, maxDistance)

    query.findInBackground(new FindCallback<ParseUser>() {

        public void done(List<ParseUser> userList, ParseException e) {
            if (e == null) {
                for (int i=0; i<userList.size(); i++) {
                    names.add(userList.get(i).get("Name").toString());
                    names.add(userList.get(i).get("Headline").toString());
                    names.add(userList.get(i).get("Age").toString());

                    //       names.add(userList.get(i).getParseObject("ProfilePicture").;

                }

                usersListView = (ListView)findViewById(R.id.usersListView);
                namesArrayAdapter =
                        new ArrayAdapter<String>(getApplicationContext(),
                                R.layout.user_list_item, names);
                usersListView.setAdapter(namesArrayAdapter);

                usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
                        openConversation(names, i);
                    }
                });

            } else {
                Toast.makeText(getApplicationContext(),
                        "Error loading user list",
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

public void openConversation(ArrayList<String> names, int pos) {
    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("Name", names.get(pos));
    query.findInBackground(new FindCallback<ParseUser>() {
        public void done(List<ParseUser> user, ParseException e) {
            if (e == null) {
                Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
                intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error finding that user",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}

Update
Unreachable code error for setConversationList

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
                container,false);

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();

Update

Upon launching the activity, I received the following message:

08-15 14:52:16.365: E/AndroidRuntime(3332): FATAL EXCEPTION: main
08-15 14:52:16.365: E/AndroidRuntime(3332): Process: com.dooba.beta, PID: 3332
08-15 14:52:16.365: E/AndroidRuntime(3332): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.usermatch}: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.os.Looper.loop(Looper.java:136)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at java.lang.reflect.Method.invoke(Method.java:515)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at dalvik.system.NativeStart.main(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): Caused by: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.dooba.beta.usermatch.initialisePaging(usermatch.java:32)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at com.dooba.beta.usermatch.onCreate(usermatch.java:20)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.Activity.performCreate(Activity.java:5231)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-15 14:52:16.365: E/AndroidRuntime(3332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-15 14:52:16.365: E/AndroidRuntime(3332):     ... 11 more

Below is the activity page that calls for the fragment

import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class usermatch extends FragmentActivity {
    private PageAdapter mPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager_layout);
        initialisePaging();

    }

    private void initialisePaging() {
        // TODO Auto-generated method stub
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
        mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(mPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mood, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Update 2
Below is the message I receive in logcat

08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main
08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974
08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.dooba.beta.Fragment1$1.done(Fragment1.java:108)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:45)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:1)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.Parse$6$1.run(Parse.java:888)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.handleCallback(Handler.java:733)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Looper.loop(Looper.java:136)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invoke(Method.java:515)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at dalvik.system.NativeStart.main(Native Method)

Body:
you can access context from onAttach() like below example

 @Override
    public void onAttach(@NonNull Context context) {

        super.onAttach(context);
    }


问:
Invoking value from remote state
I have a module cluster that spins up a GKE cluster and associated GCS buckets.
The backend for this is a GCS bucket called cluster_tf_state_bucket

I have defined an output in this module

```<code>output "vault_storage_bucket_name" {
  value = "${google_storage_bucket.vault_storage.name}"
}
</code>```

Once I run the code, I get the output

```<code>✗ terraform output
vault_storage_bucket_name = vault-storage
</code>```

Now I have a another module vault and in that module I need to invoke the value of vault_storage_bucket_name from the other module that is using a different GCS backend bucket.

So in the main.tf of my vault module, Im doing something like

```<code>terraform {
  required_version = ">= 0.12.2"
}

terraform {
  backend "gcs" {
    bucket = "app_tf_state_bucket"
    prefix = "vault"
  }
}
data "terraform_remote_state" "cluster_vault" {
  backend = "gcs"
  config = {
    bucket  = "cluster_tf_state_bucket"
  }
}

module "vault" {
  source                = "../../../modules/vault"
  env                   = "test"
  region                = "europe-west5"
  storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"
</code>```

But when I run this code, I get

```<code>Error: Unsupported argument

  on main.tf line 24, in module "vault":
  24:   storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"

An argument named "storage_bucket_name" is not expected here.
</code>```

I resolved the above issue by adding the below to the `variables.tf file

```<code>variable "storage_bucket_name"{
  type = "string"
}
</code>```

And now I run into the error

```<code>Error: Unsupported attribute

  on main.tf line 24, in module "vault":
  24:   storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"

This object has no argument, nested block, or exported attribute named
"vault_storage_bucket_name".
</code>```

What am I missing here ?

答:
The output values from the upstream state snapshot are exposed on terraform_remote_state via an attribute called outputs, so you need to include that in your expression:

```<code>  storage_bucket_name   = data.terraform_remote_state.cluster_vault.outputs.vault_storage_bucket_name
</code>```

Note the extra .outputs before .vault_storage_bucket_name. That outputs attribute is a map value, so you can potentially also use the map as a whole in expressions. For example, you might want to create a Local Value if you expect to be referring to those remote attributes a lot and want to simplify the references:

```<code>locals {
  vault_cluster = data.terraform_remote_state.cluster_vault.outputs
}

module "vault" {
  source                = "../../../modules/vault"
  env                   = "test"
  region                = "europe-west5"
  storage_bucket_name   = local.vault_cluster.vault_storage_bucket_name
}
</code>```

Title: Invoking value from remote state

Body:
I have a module cluster that spins up a GKE cluster and associated GCS buckets.
The backend for this is a GCS bucket called cluster_tf_state_bucket

I have defined an output in this module

output "vault_storage_bucket_name" {
  value = "${google_storage_bucket.vault_storage.name}"
}

Once I run the code, I get the output

✗ terraform output
vault_storage_bucket_name = vault-storage

Now I have a another module vault and in that module I need to invoke the value of vault_storage_bucket_name from the other module that is using a different GCS backend bucket.

So in the main.tf of my vault module, Im doing something like

terraform {
  required_version = ">= 0.12.2"
}

terraform {
  backend "gcs" {
    bucket = "app_tf_state_bucket"
    prefix = "vault"
  }
}
data "terraform_remote_state" "cluster_vault" {
  backend = "gcs"
  config = {
    bucket  = "cluster_tf_state_bucket"
  }
}

module "vault" {
  source                = "../../../modules/vault"
  env                   = "test"
  region                = "europe-west5"
  storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"

But when I run this code, I get

Error: Unsupported argument

  on main.tf line 24, in module "vault":
  24:   storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"

An argument named "storage_bucket_name" is not expected here.

I resolved the above issue by adding the below to the `variables.tf file

variable "storage_bucket_name"{
  type = "string"
}

And now I run into the error

Error: Unsupported attribute

  on main.tf line 24, in module "vault":
  24:   storage_bucket_name   = "${data.terraform_remote_state.cluster_vault.vault_storage_bucket_name}"

This object has no argument, nested block, or exported attribute named
"vault_storage_bucket_name".

What am I missing here ?

Body:
The output values from the upstream state snapshot are exposed on terraform_remote_state via an attribute called outputs, so you need to include that in your expression:

  storage_bucket_name   = data.terraform_remote_state.cluster_vault.outputs.vault_storage_bucket_name

Note the extra .outputs before .vault_storage_bucket_name. That outputs attribute is a map value, so you can potentially also use the map as a whole in expressions. For example, you might want to create a Local Value if you expect to be referring to those remote attributes a lot and want to simplify the references:

locals {
  vault_cluster = data.terraform_remote_state.cluster_vault.outputs
}

module "vault" {
  source                = "../../../modules/vault"
  env                   = "test"
  region                = "europe-west5"
  storage_bucket_name   = local.vault_cluster.vault_storage_bucket_name
}


问:
Interaction of DragGesture and ScrollView in SwiftUI
In an app I'm working on, there is a part that has, mostly, a "forward" navigation – tapping on buttons would display the next slide. However, a secondary "backward" navigation is also necessary. Here's the approach I've used:

import SwiftUI

struct Sample: View {
    @State private var dragOffset: CGFloat = -100
    var body: some View {
        VStack {

            Text("Perhaps a title")

            ScrollView {
                VStack {
                    Text("Some scrollable content is going to be here")

                    // ...

                    Button(action: {
                        // Go to the next slide
                    }) { Text("Next") }
                }
            }

            Text("and, maybe, something else")
        }
        .overlay(
            Image(systemName: "arrow.left").offset(x: dragOffset / 2),
            alignment: .leading
        )
        .gesture(
            DragGesture()
                .onChanged{
                    self.dragOffset = $0.translation.width
                }
                .onEnded {
                    self.dragOffset = -100 // Hide the arrow

                    if $0.translation.width > 100 {
                        // Go to the previous slide
                    }
                }
        )
    }
}
```

There is a small indicator (left arrow) that is, initially, hidden (dragOffset = -100). When the drag gesture begins, offset is fed into the dragOffset state variable and that, effectively, shows the arrow. When drag gesture ends, the arrow is hidden again and, if a certain offset is reached, the previous slide is displayed.

Works well enough, except, when the user scrolls the content in the ScrollView, this gesture is also triggered and updated for a while but then is, I assume, cancelled by the ScrollView and the "onEnded" is not called. As a result, the arrow indicator stays on the screen.

Hence the question: what is the correct way to do a gesture like that, that would work together with a ScrollView? Is it even possible with the current state of SwiftUI?

答:
For such temporary states it is better to use GestureState as it is automatically reset to initial state after gesture cancels/finished.

So here is possible approach

Update: retested with Xcode 13.4 / iOS 15.5

Demo:

Code:

```<code>struct Sample: View {
    @GestureState private var dragOffset: CGFloat = -100
    var body: some View {
        VStack {

            Text("Perhaps a title")

            ScrollView {
                VStack {
                    Text("Some scrollable content is going to be here")

                    // ...

                    Button(action: {
                        // Go to the next slide
                    }) { Text("Next") }
                }
            }

            Text("and, maybe, something else")
        }
        .overlay(
            Image(systemName: "arrow.left").offset(x: dragOffset / 2),
            alignment: .leading
        )
        .gesture(
            DragGesture()
                .updating($dragOffset) { (value, gestureState, transaction) in
                    let delta = value.location.x - value.startLocation.x
                    if delta > 10 { // << some appropriate horizontal threshold here
                        gestureState = delta
                    }
                }
                .onEnded {
                    if $0.translation.width > 100 {
                        // Go to the previous slide
                    }
                }
        )
    }
}
</code>```

Note: dragOffset: CGFloat = -100 this might have different effect on different real devices, so probably it is better to calculate it explicitly.

Body:
In an app I'm working on, there is a part that has, mostly, a "forward" navigation – tapping on buttons would display the next slide. However, a secondary "backward" navigation is also necessary. Here's the approach I've used:

import SwiftUI

struct Sample: View {
    @State private var dragOffset: CGFloat = -100
    var body: some View {
        VStack {

            Text("Perhaps a title")

            ScrollView {
                VStack {
                    Text("Some scrollable content is going to be here")

                    // ...

                    Button(action: {
                        // Go to the next slide
                    }) { Text("Next") }
                }
            }

            Text("and, maybe, something else")
        }
        .overlay(
            Image(systemName: "arrow.left").offset(x: dragOffset / 2),
            alignment: .leading
        )
        .gesture(
            DragGesture()
                .onChanged{
                    self.dragOffset = $0.translation.width
                }
                .onEnded {
                    self.dragOffset = -100 // Hide the arrow

                    if $0.translation.width > 100 {
                        // Go to the previous slide
                    }
                }
        )
    }
}

There is a small indicator (left arrow) that is, initially, hidden (dragOffset = -100). When the drag gesture begins, offset is fed into the dragOffset state variable and that, effectively, shows the arrow. When drag gesture ends, the arrow is hidden again and, if a certain offset is reached, the previous slide is displayed.

Works well enough, except, when the user scrolls the content in the ScrollView, this gesture is also triggered and updated for a while but then is, I assume, cancelled by the ScrollView and the "onEnded" is not called. As a result, the arrow indicator stays on the screen.

Hence the question: what is the correct way to do a gesture like that, that would work together with a ScrollView? Is it even possible with the current state of SwiftUI?

Body:
For such temporary states it is better to use GestureState as it is automatically reset to initial state after gesture cancels/finished.

So here is possible approach

Update: retested with Xcode 13.4 / iOS 15.5

Demo:

Code:

struct Sample: View {
    @GestureState private var dragOffset: CGFloat = -100
    var body: some View {
        VStack {

            Text("Perhaps a title")

            ScrollView {
                VStack {
                    Text("Some scrollable content is going to be here")

                    // ...

                    Button(action: {
                        // Go to the next slide
                    }) { Text("Next") }
                }
            }

            Text("and, maybe, something else")
        }
        .overlay(
            Image(systemName: "arrow.left").offset(x: dragOffset / 2),
            alignment: .leading
        )
        .gesture(
            DragGesture()
                .updating($dragOffset) { (value, gestureState, transaction) in
                    let delta = value.location.x - value.startLocation.x
                    if delta > 10 { // << some appropriate horizontal threshold here
                        gestureState = delta
                    }
                }
                .onEnded {
                    if $0.translation.width > 100 {
                        // Go to the previous slide
                    }
                }
        )
    }
}

Note: dragOffset: CGFloat = -100 this might have different effect on different real devices, so probably it is better to calculate it explicitly.


问:
Views misplaced when setting frames
I am trying to make a view programatically, making a card with an image and some text and overlaying it with some color. I have turned off clip to bounds and added some colors to make it more visual.
So when I set

```<code>overlay.frame = self.frame
</code>```

or

```<code>overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
</code>```

the overlay should cover the entire view but it does not, why is this?

This is what is showing

This is what I want to see, but with each card having a blue layer on top

```<code>private var leftImage: UIImageView = {
  let i = UIImageView(frame: .zero)
  i.contentMode = .scaleAspectFill
  i.image = UIImage()
  return i
}()

private var topLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.font = UIFont.boldSystemFont(ofSize: 16.0)
  label.lineBreakMode = .byWordWrapping
  label.adjustsFontSizeToFitWidth = true
  label.numberOfLines = 2
  return label
}()

var bottomLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.lineBreakMode = .byWordWrapping
  label.font = UIFont.systemFont(ofSize: 12.0)
  label.numberOfLines = 1
  label.text = "60 seconds"
 return label
}()

private var stackView: UIStackView = {
  let stack = UIStackView(frame: .zero)
  stack.axis = .vertical
  stack.isUserInteractionEnabled = false
  stack.distribution = .fillEqually
  stack.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  stack.isLayoutMarginsRelativeArrangement = true
  return stack
}()

private var overlay: UIView = {
  let view = UIView(frame: .zero)
  view.backgroundColor = .blue
  view.alpha = 0.8
  //view.isHidden = true
  return view
}()

override init(frame: CGRect) {
  super.init(frame: frame)
  create()
}

required init?(coder: NSCoder) {
  super.init(coder: coder)
  create()
}

private func create() {
  self.translatesAutoresizingMaskIntoConstraints = false

  //leftview
  leftImage.frame = CGRect(x: 0, y: 0, width: frame.width / 2, height: frame.height)
  addSubview(leftImage)

  //rightVIew
  stackView.frame = CGRect(x: frame.midX, y: 0, width: frame.width / 2, height: frame.height)

  clipsToBounds = false

  //add views to stack
  stackView.addArrangedSubview(topLabel)
  stackView.addArrangedSubview(bottomLabel)

  addSubview(stackView)

  overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
  addSubview(overlay)

  //card styling
  layer.cornerRadius = 10
}
</code>```

答:
```<code>overlay.frame = self.frame
</code>```

That can never be right, except by accident, because the frame of overlay and the frame of self are in two different coordinate systems. At the very least you want to say

```<code>overlay.frame = self.bounds // bounds, not frame
</code>```

However, that isn't going to work either unless you say it in the right place. The right place is when layout occurs:

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    self.overlay.frame = self.bounds
}
</code>```

Simply adding that to your existing code should solve the problem.

Title: Views misplaced when setting frames

Body:
I am trying to make a view programatically, making a card with an image and some text and overlaying it with some color. I have turned off clip to bounds and added some colors to make it more visual.
So when I set

overlay.frame = self.frame

or

overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

the overlay should cover the entire view but it does not, why is this?

This is what is showing

This is what I want to see, but with each card having a blue layer on top

private var leftImage: UIImageView = {
  let i = UIImageView(frame: .zero)
  i.contentMode = .scaleAspectFill
  i.image = UIImage()
  return i
}()

private var topLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.font = UIFont.boldSystemFont(ofSize: 16.0)
  label.lineBreakMode = .byWordWrapping
  label.adjustsFontSizeToFitWidth = true
  label.numberOfLines = 2
  return label
}()

var bottomLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.lineBreakMode = .byWordWrapping
  label.font = UIFont.systemFont(ofSize: 12.0)
  label.numberOfLines = 1
  label.text = "60 seconds"
 return label
}()

private var stackView: UIStackView = {
  let stack = UIStackView(frame: .zero)
  stack.axis = .vertical
  stack.isUserInteractionEnabled = false
  stack.distribution = .fillEqually
  stack.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  stack.isLayoutMarginsRelativeArrangement = true
  return stack
}()

private var overlay: UIView = {
  let view = UIView(frame: .zero)
  view.backgroundColor = .blue
  view.alpha = 0.8
  //view.isHidden = true
  return view
}()

override init(frame: CGRect) {
  super.init(frame: frame)
  create()
}

required init?(coder: NSCoder) {
  super.init(coder: coder)
  create()
}

private func create() {
  self.translatesAutoresizingMaskIntoConstraints = false

  //leftview
  leftImage.frame = CGRect(x: 0, y: 0, width: frame.width / 2, height: frame.height)
  addSubview(leftImage)

  //rightVIew
  stackView.frame = CGRect(x: frame.midX, y: 0, width: frame.width / 2, height: frame.height)

  clipsToBounds = false

  //add views to stack
  stackView.addArrangedSubview(topLabel)
  stackView.addArrangedSubview(bottomLabel)

  addSubview(stackView)

  overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
  addSubview(overlay)

  //card styling
  layer.cornerRadius = 10
}

Body:
overlay.frame = self.frame

That can never be right, except by accident, because the frame of overlay and the frame of self are in two different coordinate systems. At the very least you want to say

overlay.frame = self.bounds // bounds, not frame

However, that isn't going to work either unless you say it in the right place. The right place is when layout occurs:

override func layoutSubviews() {
    super.layoutSubviews()
    self.overlay.frame = self.bounds
}

Simply adding that to your existing code should solve the problem.


问:
How do you get a selected value from gridview dropdown using javascript
i have a gridview which has one of the columns as a dropdown. When the user selects a different drop down option i would like to get the selected value. How do i go about this? Please see code below. This code seems to work in IE9  and Firefox but does not work in IE8.  In IE8 i get the following error "options.selectedIndex' is null or not an object" . </p>

```<code>     var gridview =  document.getElementById('ctl00_ContentPlaceHolder1_grvTrainHistoryCapture');

     if (selectedRowIndex == null) return;
     var statusCell = gridview.rows[parseInt(selectedRowIndex)+ 1].cells[5];
     var ddlStatus = statusCell.childNodes[1];

     var statusID = ddlStatus.options[ddlStatus.options.selectedIndex].value;
</code>```

答:
EDIT: I HAVE TESTED THIS CODE UNDER IE8, AND IT WORKS AS IT SHOULD.
i guess the problem is the object you are passing.</p>

```<code><script type="text/javascript">
    var e = document.getElementById('test');
    alert(e.options[e.selectedIndex].value );
</script>
</code>```

Body:
i have a gridview which has one of the columns as a dropdown. When the user selects a different drop down option i would like to get the selected value. How do i go about this? Please see code below. This code seems to work in IE9  and Firefox but does not work in IE8.  In IE8 i get the following error "options.selectedIndex' is null or not an object" .

     var gridview =  document.getElementById('ctl00_ContentPlaceHolder1_grvTrainHistoryCapture');

     if (selectedRowIndex == null) return;
     var statusCell = gridview.rows[parseInt(selectedRowIndex)+ 1].cells[5];
     var ddlStatus = statusCell.childNodes[1];

     var statusID = ddlStatus.options[ddlStatus.options.selectedIndex].value;

Body:
EDIT: I HAVE TESTED THIS CODE UNDER IE8, AND IT WORKS AS IT SHOULD.
i guess the problem is the object you are passing.

<script type="text/javascript">
    var e = document.getElementById('test');
    alert(e.options[e.selectedIndex].value );
</script>


问:
What kind of data structure is this? Python
Studying Python, I am following an excellent Corey Schafer tutorial on Flask, he does this (I have extracted and summarized it for obvious reasons):

```<code>    from folder_app import app # I did it to follow the structure and that the code is equal to the original

    s = Serializer(app.config['SECRET_KEY'], 1800) # key, seconds
    token = s.dumps({'user_id': 1}).decode('utf-8')
    s = Serializer(app.config['SECRET_KEY'])

    user_id = s.loads(token)['user_id'] # This is where I have the doubt

    print(user_id)
    print(type(s.loads(token)))
</code>```

The code works, the problem I have is that although as you can see (s.loads (token)) is a dict, I expected to see something like this s.loads ({token ['user_id']}), or s.loads (token ['user_id']) or something like that. That is, it is a dict but it does not seem so. And my doubt goes in the sense if this comes from a greater concept of those they call "pythonic" (which I have not seen so far), or is something that only happens particularly as in this case. Incidentally, https://itsdangerous.palletsprojects.com/en/1.1.x/jws/ this appears: loads (self, s, salt = None, return_header = False) the arguments are in parentheses. I hope it is clear what my doubt is :)

答:
I know this is not answer per say but just to add to my comment. This is an example of how the loads function works on dictionaries with the json module. https://docs.python.org/3/library/json.html#json.loads. What it does is take a json string and return the dictionary type object in Python. Your Serializer is doing something similar. It takes the token string and represents it as an object like dict

The s.dumps I am assuming is similar to json.dumps which gives you the json string representation of python dictionary.

import json
my_dict = json.loads('{"user_id": "Mane", "name": "Joe"}')
my_dict['user_id']
```

So you could just do json.loads('{"user_id": "Mane", "name": "Joe"}')['user_id'] which is just chaining the operations.

Body:
Studying Python, I am following an excellent Corey Schafer tutorial on Flask, he does this (I have extracted and summarized it for obvious reasons):

    from folder_app import app # I did it to follow the structure and that the code is equal to the original

    s = Serializer(app.config['SECRET_KEY'], 1800) # key, seconds
    token = s.dumps({'user_id': 1}).decode('utf-8')
    s = Serializer(app.config['SECRET_KEY'])

    user_id = s.loads(token)['user_id'] # This is where I have the doubt

    print(user_id)
    print(type(s.loads(token)))

The code works, the problem I have is that although as you can see (s.loads (token)) is a dict, I expected to see something like this s.loads ({token ['user_id']}), or s.loads (token ['user_id']) or something like that. That is, it is a dict but it does not seem so. And my doubt goes in the sense if this comes from a greater concept of those they call "pythonic" (which I have not seen so far), or is something that only happens particularly as in this case. Incidentally, https://itsdangerous.palletsprojects.com/en/1.1.x/jws/ this appears: loads (self, s, salt = None, return_header = False) the arguments are in parentheses. I hope it is clear what my doubt is :)

Body:
I know this is not answer per say but just to add to my comment. This is an example of how the loads function works on dictionaries with the json module. https://docs.python.org/3/library/json.html#json.loads. What it does is take a json string and return the dictionary type object in Python. Your Serializer is doing something similar. It takes the token string and represents it as an object like dict

The s.dumps I am assuming is similar to json.dumps which gives you the json string representation of python dictionary.

import json
my_dict = json.loads('{"user_id": "Mane", "name": "Joe"}')
my_dict['user_id']

So you could just do json.loads('{"user_id": "Mane", "name": "Joe"}')['user_id'] which is just chaining the operations.


问:
How to deal with extremely big initial loss?
I build a model (glow) for image density estimation. It worked when using CUB200 dataset for training, with images size (224,224,3) and 40 per batch.

Loss function is calculate log probability using tensorflow_probability's distributions.

Initial loss is around 40000 and the rest of training went well. But if I use celebA dataset for training, the initial loss goes to like 1e+26 sometimes Nan.

Two datasets use same way to process, so I believe datasets should be fine.

The problem is I wonder what would cause such a high loss initially and how to deal with it because once it raised NaN error, training stops.

答:
That means you have very low predicted probabilities for the true class at the beginning of training. This could mean that the initial values for the weights are too large, or that the input itself is not normalized, causing extreme outputs (very close to zero or one for a softmax output). You can fix this by:

normalizing the inputs

having smaller initial weights

adding a small constant to the argument of the logarithm, so that the log will not be too large


问:
my textview is not working in android studio
I have created one activity and i have stored my data in another class with encapsulation and from that class, I am not able to retrieve my data to the text field of another class. below is the code please help me so solve. when I run the app I am getting nothing on the screen.

Name.java

```<code>package com.example.voiceprescription;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.icu.text.IDNA;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Locale;

public class Name extends AppCompatActivity {

    EditText et_Nname,et_Nage,et_Nphone;

    RadioButton rb_Nmale,rb_Nfemale;
    Button btn_Nnext;enter code here
    ImageButton ib_Nvoice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);

        et_Nphone=findViewById(R.id.et_Nphone);
        et_Nname=findViewById(R.id.et_Nname);
        et_Nage=findViewById(R.id.et_Nage);
        ib_Nvoice=findViewById(R.id.ib_Nvoice);
        rb_Nfemale=findViewById(R.id.rb_Nfemale);
        rb_Nmale=findViewById(R.id.rb_Nmale);
        btn_Nnext=findViewById(R.id.btn_Nnext);

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

                String name=et_Nname.getText().toString().trim();
                String age=et_Nage.getText().toString().trim();
                String phone=et_Nphone.getText().toString().trim();
               PersonInfo personInfo=new PersonInfo();

               personInfo.setName(name);
               personInfo.setAge(age);
               personInfo.setPhone(phone);

               Intent intent=new Intent(Name.this,Symptoms.class);
               startActivity(intent);

            }
        });

    }
}

</code>```

Personinfo.java

```<code>package com.example.voiceprescription;

public class PersonInfo {

    private String name;
    private String age;
    private String phone;
    private String gender;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}
</code>```

symptoms.java

```<code>package com.example.voiceprescription;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Symptoms extends AppCompatActivity {

    TextView tv1;
    PersonInfo personInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_symptoms);

        personInfo=new PersonInfo();
        tv1=findViewById(R.id.tv1);

        tv1.setText(personInfo.getName());

    }
}
</code>```

答:
This doesn't work this way what you have done. To do is pass the object as a bundle param to the symptoms activity.

```<code>Bundle bundle = new Bundle();
</code>```

bundle.putSerializable("value", your_person_class_obj);
intent.putExtras(bundle);

For this, your class must implement the Serializable interface.

```<code>public class PersonInfo implements Serializable {

}
</code>```

Your code doesn't work because you set the object in one activity and it's not available for the second.
Reference -  Check this link for more details

Body:
I have created one activity and i have stored my data in another class with encapsulation and from that class, I am not able to retrieve my data to the text field of another class. below is the code please help me so solve. when I run the app I am getting nothing on the screen.

Name.java

package com.example.voiceprescription;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.icu.text.IDNA;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Locale;

public class Name extends AppCompatActivity {

    EditText et_Nname,et_Nage,et_Nphone;

    RadioButton rb_Nmale,rb_Nfemale;
    Button btn_Nnext;enter code here
    ImageButton ib_Nvoice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);

        et_Nphone=findViewById(R.id.et_Nphone);
        et_Nname=findViewById(R.id.et_Nname);
        et_Nage=findViewById(R.id.et_Nage);
        ib_Nvoice=findViewById(R.id.ib_Nvoice);
        rb_Nfemale=findViewById(R.id.rb_Nfemale);
        rb_Nmale=findViewById(R.id.rb_Nmale);
        btn_Nnext=findViewById(R.id.btn_Nnext);

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

                String name=et_Nname.getText().toString().trim();
                String age=et_Nage.getText().toString().trim();
                String phone=et_Nphone.getText().toString().trim();
               PersonInfo personInfo=new PersonInfo();

               personInfo.setName(name);
               personInfo.setAge(age);
               personInfo.setPhone(phone);

               Intent intent=new Intent(Name.this,Symptoms.class);
               startActivity(intent);

            }
        });

    }
}

Personinfo.java

package com.example.voiceprescription;

public class PersonInfo {

    private String name;
    private String age;
    private String phone;
    private String gender;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

symptoms.java

package com.example.voiceprescription;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Symptoms extends AppCompatActivity {

    TextView tv1;
    PersonInfo personInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_symptoms);

        personInfo=new PersonInfo();
        tv1=findViewById(R.id.tv1);

        tv1.setText(personInfo.getName());

    }
}

Body:
This doesn't work this way what you have done. To do is pass the object as a bundle param to the symptoms activity.

Bundle bundle = new Bundle();

bundle.putSerializable("value", your_person_class_obj);
intent.putExtras(bundle);

For this, your class must implement the Serializable interface.

public class PersonInfo implements Serializable {

}

Your code doesn't work because you set the object in one activity and it's not available for the second.
Reference -  Check this link for more details


问:
Does heapq.heappush() compare on int AND string without been specified for?
I was checking out this solution to a question on leetcode.com

```<code>def topKFrequent(self, words, k):
        count = collections.Counter(words)
        heap = [(-freq, word) for word, freq in count.items()]
        heapq.heapify(heap)
        return [heapq.heappop(heap)[1] for _ in xrange(k)]
</code>```

and when I provide it an array of strings like ["aa", "aaa", "a"] and 1  it correctly returns ["a"]. My question is did the heap also lexographically sort the tuples internally? Because according to me if there was no sorting, it would have simply returned ["aa"] (the order in which the heap was constructed since counts of all three are the same). Or have I misunderstood heapq?

答:
You have a heap of integer/string pairs, and so it is ordered based on the definition of < for tuples, which takes into account both elements of each type.

Given ["aa", "aaa", "a"], count.items() is sequence of tuples [('aa', 1), ('aaa', 1), ('a', 1)]. You then build a heap using the list of tuples

```<code>[(-1, 'aa'), (-1, 'aaa'), (-1, 'a')]
</code>```

Since the first element of each tuple is the same, the comparisons are determined solely by the second, string, element.

Body:
I was checking out this solution to a question on leetcode.com

def topKFrequent(self, words, k):
        count = collections.Counter(words)
        heap = [(-freq, word) for word, freq in count.items()]
        heapq.heapify(heap)
        return [heapq.heappop(heap)[1] for _ in xrange(k)]

and when I provide it an array of strings like ["aa", "aaa", "a"] and 1  it correctly returns ["a"]. My question is did the heap also lexographically sort the tuples internally? Because according to me if there was no sorting, it would have simply returned ["aa"] (the order in which the heap was constructed since counts of all three are the same). Or have I misunderstood heapq?

Body:
You have a heap of integer/string pairs, and so it is ordered based on the definition of < for tuples, which takes into account both elements of each type.

Given ["aa", "aaa", "a"], count.items() is sequence of tuples [('aa', 1), ('aaa', 1), ('a', 1)]. You then build a heap using the list of tuples

[(-1, 'aa'), (-1, 'aaa'), (-1, 'a')]

Since the first element of each tuple is the same, the comparisons are determined solely by the second, string, element.


问:
Printing only columns in rows that have values from a datagridview
Is it possible to only print the columns in a row in a DataGridView that have values and exclude the non empty ones? I'm trying to print the ones and only the ones that have actual values stored in it, but right now it is printing all of them.

Here is a screenshot of the actual print document (saved as a pdf): http://imgur.com/HiF9heq

I would like to eliminate the rest of the columns that are empty.

Here is the code I have in place to print and the code that fills the data table:

```<code>private void Printdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        try
        {
            qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            // set the left margin of the document to be printed
            int leftMargin = e.MarginBounds.Left;

            // set the top margin of the document to be printed
            int topMargin = e.MarginBounds.Top;

            // variable to determine if more pages are to be printed
            bool printMore = false;

            // temp width
            int tmpWidth = 0;

            // for the first page to print, set the cell width and header height
            if (firstPage)
            {
                foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                {
                    tmpWidth = (int)(Math.Floor((double)gridCol.Width /
                        totalWidth * totalWidth *
                        ((double)e.MarginBounds.Width / totalWidth)));

                    headerHeight = (int)(e.Graphics.MeasureString(gridCol.HeaderText, gridCol.InheritedStyle.Font, tmpWidth).Height) + 2;

                    // save the width and height of the headers
                    arrayLeftColumns.Add(leftMargin);
                    arrayColWidths.Add(tmpWidth);

                    leftMargin += tmpWidth;
                }
            }

            // loop until all of the grid rows get printed
            while (row <= qbcDataGridView.Rows.Count - 1)
            {
                DataGridViewRow gridRow = qbcDataGridView.Rows[row];

                // set the cell height
                cellHeight = gridRow.Height + 5;

                int count = 0;

                // check to see if the current page settings allow more rows to print
                if (topMargin + cellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    newPage = true;

                    firstPage = false;

                    printMore = true;

                    break;
                }
                else
                {
                    if (newPage)
                    {
                        // draw the header
                        e.Graphics.DrawString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Height - 13);

                        // set the data (now) and the current time
                        String date = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();

                        // draw the date on the print document
                        e.Graphics.DrawString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Width),
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory", new Font(new Font(qbcDataGridView.Font, FontStyle.Bold),
                            FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                        // draw the column headers
                        topMargin = e.MarginBounds.Top;

                        foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                        {
                            if (!string.IsNullOrEmpty(gridCol.HeaderText))
                            {
                                // header color
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header text box
                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header string
                                e.Graphics.DrawString(gridCol.HeaderText,
                                    gridCol.InheritedStyle.Font, new SolidBrush(gridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], headerHeight), string_format);
                            }
                            else
                            {
                                break;
                            }

                            count++;
                        }

                        newPage = false;

                        topMargin += headerHeight;
                    }

                    count = 0;

                    // draw the column's contents
                    foreach (DataGridViewCell gridCell in gridRow.Cells)
                    {
                        if (gridCell.Value != null)
                        {
                            if (!string.IsNullOrEmpty(gridCell.Value.ToString()))
                            {
                                e.Graphics.DrawString(gridCell.Value.ToString(),
                                    gridCell.InheritedStyle.Font, new SolidBrush(gridCell.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight), string_format);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }

                        // draw the borders for the cells
                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight));

                        count++;
                    }
                }

                row++;

                topMargin += cellHeight;

                // if more lines exist, print another page
                if (printMore)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }
</code>```

and the menu strip item that fills the DataGridView:

```<code>private void MenuViewMembers_Click(object sender, EventArgs e)
        {
            qbcDataGridView.Font = new Font(qbcDataGridView.Font.FontFamily, 10);

        qbcDataGridView.Location = new Point(30, 100);

        qbcDataGridView.Size = new Size(1500, 500);

        dbConn.Open();

        DataTable dt = new DataTable();

        DbAdapter = new OleDbDataAdapter("select ID, household_head, birthday, phone, email, address, status, spouse, spouse_birthday, spouse_email, anniversary, spouse_status," +
            "child1, child1_birthday, child1_email, child2, child2_birthday, child3_birthday, child4, child4_birthday, child4_email, child5, child5_birthday, child5_email," +
            "child6, child6_birthday, child6_email, child7, child7_birthday, child7_email from members", dbConn);
        DbAdapter.Fill(dt);

        qbcDataGridView.DataSource = dt;

        qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        qbcDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

        qbcDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dbConn.Close();

        Controls.Add(qbcDataGridView);
    }
</code>```

I think that if only the non-empty values were printed it would format the printed document correctly (see screenshot).

Any help would be greatly appreciated.

Thanks!

Update - I got it so where the empty cells are not shown (http://imgur.com/R0ueyft) but I guess my other question is how to not have the column headers shown as well if the cells are empty. I updated my code to reflect the changes I made.

答:
guys if u have that empty row in datagrid just erase it and it will work fine.
when the loop start and reach the end of the datagrid it will return an exception because the last row has no values</p>

Body:
Is it possible to only print the columns in a row in a DataGridView that have values and exclude the non empty ones? I'm trying to print the ones and only the ones that have actual values stored in it, but right now it is printing all of them.

Here is a screenshot of the actual print document (saved as a pdf): http://imgur.com/HiF9heq

I would like to eliminate the rest of the columns that are empty.

Here is the code I have in place to print and the code that fills the data table:

private void Printdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        try
        {
            qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            // set the left margin of the document to be printed
            int leftMargin = e.MarginBounds.Left;

            // set the top margin of the document to be printed
            int topMargin = e.MarginBounds.Top;

            // variable to determine if more pages are to be printed
            bool printMore = false;

            // temp width
            int tmpWidth = 0;

            // for the first page to print, set the cell width and header height
            if (firstPage)
            {
                foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                {
                    tmpWidth = (int)(Math.Floor((double)gridCol.Width /
                        totalWidth * totalWidth *
                        ((double)e.MarginBounds.Width / totalWidth)));

                    headerHeight = (int)(e.Graphics.MeasureString(gridCol.HeaderText, gridCol.InheritedStyle.Font, tmpWidth).Height) + 2;

                    // save the width and height of the headers
                    arrayLeftColumns.Add(leftMargin);
                    arrayColWidths.Add(tmpWidth);

                    leftMargin += tmpWidth;
                }
            }

            // loop until all of the grid rows get printed
            while (row <= qbcDataGridView.Rows.Count - 1)
            {
                DataGridViewRow gridRow = qbcDataGridView.Rows[row];

                // set the cell height
                cellHeight = gridRow.Height + 5;

                int count = 0;

                // check to see if the current page settings allow more rows to print
                if (topMargin + cellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    newPage = true;

                    firstPage = false;

                    printMore = true;

                    break;
                }
                else
                {
                    if (newPage)
                    {
                        // draw the header
                        e.Graphics.DrawString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Height - 13);

                        // set the data (now) and the current time
                        String date = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();

                        // draw the date on the print document
                        e.Graphics.DrawString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Width),
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory", new Font(new Font(qbcDataGridView.Font, FontStyle.Bold),
                            FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                        // draw the column headers
                        topMargin = e.MarginBounds.Top;

                        foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                        {
                            if (!string.IsNullOrEmpty(gridCol.HeaderText))
                            {
                                // header color
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header text box
                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header string
                                e.Graphics.DrawString(gridCol.HeaderText,
                                    gridCol.InheritedStyle.Font, new SolidBrush(gridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], headerHeight), string_format);
                            }
                            else
                            {
                                break;
                            }

                            count++;
                        }

                        newPage = false;

                        topMargin += headerHeight;
                    }

                    count = 0;

                    // draw the column's contents
                    foreach (DataGridViewCell gridCell in gridRow.Cells)
                    {
                        if (gridCell.Value != null)
                        {
                            if (!string.IsNullOrEmpty(gridCell.Value.ToString()))
                            {
                                e.Graphics.DrawString(gridCell.Value.ToString(),
                                    gridCell.InheritedStyle.Font, new SolidBrush(gridCell.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight), string_format);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }

                        // draw the borders for the cells
                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight));

                        count++;
                    }
                }

                row++;

                topMargin += cellHeight;

                // if more lines exist, print another page
                if (printMore)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

and the menu strip item that fills the DataGridView:

private void MenuViewMembers_Click(object sender, EventArgs e)
        {
            qbcDataGridView.Font = new Font(qbcDataGridView.Font.FontFamily, 10);

        qbcDataGridView.Location = new Point(30, 100);

        qbcDataGridView.Size = new Size(1500, 500);

        dbConn.Open();

        DataTable dt = new DataTable();

        DbAdapter = new OleDbDataAdapter("select ID, household_head, birthday, phone, email, address, status, spouse, spouse_birthday, spouse_email, anniversary, spouse_status," +
            "child1, child1_birthday, child1_email, child2, child2_birthday, child3_birthday, child4, child4_birthday, child4_email, child5, child5_birthday, child5_email," +
            "child6, child6_birthday, child6_email, child7, child7_birthday, child7_email from members", dbConn);
        DbAdapter.Fill(dt);

        qbcDataGridView.DataSource = dt;

        qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        qbcDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

        qbcDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dbConn.Close();

        Controls.Add(qbcDataGridView);
    }

I think that if only the non-empty values were printed it would format the printed document correctly (see screenshot).

Any help would be greatly appreciated.

Thanks!

Update - I got it so where the empty cells are not shown (http://imgur.com/R0ueyft) but I guess my other question is how to not have the column headers shown as well if the cells are empty. I updated my code to reflect the changes I made.


问:
How to detect if app is being operating by automated testing tools?
Sometimes, hackers may use automation tools, such as Robotium、Espresso、UiAutomator2、Appium, to automatically operate my customers' apps, which will integrate our SDK, to earn profits.

So how to detect if current app is being operating by such automated testing tools (except checking the service and process) without editting the app itself? Thanks~

答:
The best way to do it is to remove all IDs, text descriptions and other helpers from the app. Even if there are IDs have multiple builds with different IDs or dynamic IDs. Other methods are:

To re-skin the app regularly to avoid automation using image comparisons.
Have more captcha or other security methods to avoid automation.


答:
Heaps are partial orderings.  They are not sorted.  You can, however, build sorts out of them by storing values in a heap and pulling them out one at a time.  These sorts are not stable, because heaps do not try to preserve the ordering of "equal" values.

Here's another kind of Python heap you might be interested in:
https://pypi.org/project/fibonacci-heap-mod/

Title: Does heapq.heappush() compare on int AND string without been specified for?


问:
giving priority to values in an SQL stmt
is there any way i can do a query to specify that I want to give priority to some value?

for instance i have:

```<code>SELECT TOP (20)
  r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM
  Resource AS r INNER JOIN tags AS t ON r.MD5 = t.MD5
WHERE
  (t.Category IN ('algorithm', 'k-means', 'statistics', 'clustering', 'science'))

GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY matching_terms DESC, t.tfidf DESC
</code>```

i want that 'algorithm' is given higher priority when finding results. any ideas?

答:
```<code>SELECT        TOP (10) r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM            Resource AS r INNER JOIN
                         tags AS t ON r.MD5 = t.MD5
WHERE        (t.Category IN ('astrophysics', 'athletics', 'sports', 'football', 'soccer'))
GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY (CASE t .Category WHEN 'astrophysics' THEN 0 WHEN 'athletics' THEN 1 WHEN 'sports' THEN 2 WHEN 'football' THEN 3 WHEN 'soccer' THEN 4 END)
</code>```

Thanks for giving me the idea Lukas Eder

Body:
is there any way i can do a query to specify that I want to give priority to some value?

for instance i have:

SELECT TOP (20)
  r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM
  Resource AS r INNER JOIN tags AS t ON r.MD5 = t.MD5
WHERE
  (t.Category IN ('algorithm', 'k-means', 'statistics', 'clustering', 'science'))

GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY matching_terms DESC, t.tfidf DESC

i want that 'algorithm' is given higher priority when finding results. any ideas?

Body:
SELECT        TOP (10) r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM            Resource AS r INNER JOIN
                         tags AS t ON r.MD5 = t.MD5
WHERE        (t.Category IN ('astrophysics', 'athletics', 'sports', 'football', 'soccer'))
GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY (CASE t .Category WHEN 'astrophysics' THEN 0 WHEN 'athletics' THEN 1 WHEN 'sports' THEN 2 WHEN 'football' THEN 3 WHEN 'soccer' THEN 4 END)

Thanks for giving me the idea Lukas Eder


问:
Types of PII for queries into AWS macie
I tried to make a query for classifying my documents using macie. But i don't know how i can find documents with driver licenses or National Identifications number...

In the examples that it use aws, appear pii_type: "mail" for email or pii_types: "cc_number" for credit cards numbers, but i don't find examples for Birth dates, Ip adresses, Drivers license IDs (USA), National identification numbers (USA).

How/what i can make to search or create a basic alert for these documents?

Thanks for the help.

答:
Try this query:

pii_types:"national_id"

Title: Types of PII for queries into AWS macie

Body:
Try this query:

pii_types:"national_id"


问:
Linq replace values until first X value
I have a list:

```<code>var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
</code>```

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

```<code>var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)
</code>```

Actual Result:

```<code>{null,null,null,null,null,null,null,5,6,3,0,null,null,3}
</code>```

Expected Result:

```<code>{null,null,null,null,null,null,4,5,6,3,0,0,2,3}
</code>```

MRE:

```<code>public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}
</code>```

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

答:
Another solution without auxiliary variables:</p>

```<code>var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
l = l.TakeWhile(x => x==0).Select(x => (int?)null).Concat(l.SkipWhile(x => x==0)).ToList();
</code>```

Title: Linq replace values until first X value

Body:
I have a list:

var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)

Actual Result:

{null,null,null,null,null,null,null,5,6,3,0,null,null,3}

Expected Result:

{null,null,null,null,null,null,4,5,6,3,0,0,2,3}

MRE:

public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

Body:
Another solution without auxiliary variables:

var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
l = l.TakeWhile(x => x==0).Select(x => (int?)null).Concat(l.SkipWhile(x => x==0)).ToList();


问:
Split x axis for every value in graph, in Power BI
I have the following graph in Power BI:

and I'm trying to recreate the below graph from Excel (note the X axis with the months February and January, with the Operation Text:

As you can see, my attempt only displays the Operation Text rather than the month and Operation Text).

Here is what my current axis looks like:

Changing the axis to have Actual Start Date on top, rather than the Operation Text:

Makes my graph look like this:

Is it possible to achieve the same outcome as in Excel, with the values in my graph showing the two months side by side, for each operation text? If so, how can I do this?

I've tried looking into the X axis 'format' settings and wasn't able to see anything obvious to help achieve this. In addition, unfortunately the graph I'm looking to recreate is only a screenshot so I am unable to see how it achieves that outcome.

EDIT:

As suggested, I attempted to place Operation Text into the Legend field in my Visualisations section but I am unable to, due to the fact that I have two Value fields (the two columns Actual Hours and Estimated Hours).

答:
@CR7SMS is correct. You just need to expand down to the next level using that split arrow in the upper right of the visual so that this:

Becomes this:

Note that to get the axis to look like this, you'll need to sort on month rather than one of the measures.

You'll also want to turn off 'Concatenate labels' toggle in the 'Format > X axis' section of the visual settings.