问:
NullPointerException Caused by getActionBar()
Trying to set up the Navigation Drawer of an app right now, and every time I try to run the app on my Android device, I get a NullPointerException. The error is caused by getActionBar.setDisplayHomeUpAsEnabled(true) and getActionBar.setHomeButtonEnabled(true)

Even if I remove these two lines of code, I still get an error.

How do I fix this quickly?

Code:

```<code>import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
    private String[] navDrawerTitles;
    private DrawerLayout navDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mTitle;
    Fragment fragment = new Fragment();
    private Fragment blankFrag = new Fragment();
    private final int POSITION = 0;

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

        navDrawerTitles = getResources().getStringArray(R.array.nav_array);
        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, navDrawerTitles));

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                navDrawerLayout, /* DrawerLayout object */
                //R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open, /* "open drawer" description */
                R.string.drawer_close /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                // super.onDrawerClosed(view);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                // super.onDrawerOpened(drawerView);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }
        };

        // Set the drawer toggle as the DrawerListener
        navDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content
        // view
        boolean drawerOpen = navDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            selectItem(position);
        }
    }

    /** Swaps fragments in the main content view */
    /**
     * Starts an Activity when item is clicked
     */
    private void selectItem(int position) {

//        }

        Bundle args = new Bundle();
        args.putInt(StartingFragment.TEA_TYPE_POS, position);
        fragment.setArguments(args);

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
//      setTitle(navDrawerTitles[position]);
        navDrawerLayout.closeDrawer(mDrawerList);

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}
</code>```

01-31 14:11:11.298: E/AndroidRuntime(20904): FATAL EXCEPTION: main
  01-31 14:11:11.298: E/AndroidRuntime(20904): Process:
  appathon.bu.com.appathon, PID: 20904 01-31 14:11:11.298:
  E/AndroidRuntime(20904): java.lang.RuntimeException: Unable to start
  activity
  ComponentInfo{appathon.bu.com.appathon/appathon.bu.com.appathon.MainActivity}:
  java.lang.NullPointerException 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.access$800(ActivityThread.java:144) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.os.Handler.dispatchMessage(Handler.java:102) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.os.Looper.loop(Looper.java:136) 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  android.app.ActivityThread.main(ActivityThread.java:5146) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  java.lang.reflect.Method.invokeNative(Native Method) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  java.lang.reflect.Method.invoke(Method.java:515) 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  dalvik.system.NativeStart.main(Native Method) 01-31 14:11:11.298:
  E/AndroidRuntime(20904): Caused by: java.lang.NullPointerException
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  appathon.bu.com.appathon.MainActivity.onCreate(MainActivity.java:45)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.Activity.performCreate(Activity.java:5231) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  ... 11 more

答: I had the same error as you. My solution was to set theme with ThemeAppCompat, make your activity extend AppCompatActivity and use the method of getSupportActionBar instead of using the method of getActionBar. In short, you should make sure the actionBar of theme and the method which to get actionBar have the same support library.</p>

Body:
Trying to set up the Navigation Drawer of an app right now, and every time I try to run the app on my Android device, I get a NullPointerException. The error is caused by getActionBar.setDisplayHomeUpAsEnabled(true) and getActionBar.setHomeButtonEnabled(true)

Even if I remove these two lines of code, I still get an error.

How do I fix this quickly?

Code:

import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
    private String[] navDrawerTitles;
    private DrawerLayout navDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mTitle;
    Fragment fragment = new Fragment();
    private Fragment blankFrag = new Fragment();
    private final int POSITION = 0;

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

        navDrawerTitles = getResources().getStringArray(R.array.nav_array);
        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, navDrawerTitles));

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                navDrawerLayout, /* DrawerLayout object */
                //R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open, /* "open drawer" description */
                R.string.drawer_close /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                // super.onDrawerClosed(view);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                // super.onDrawerOpened(drawerView);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }
        };

        // Set the drawer toggle as the DrawerListener
        navDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content
        // view
        boolean drawerOpen = navDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            selectItem(position);
        }
    }

    /** Swaps fragments in the main content view */
    /**
     * Starts an Activity when item is clicked
     */
    private void selectItem(int position) {

//        }

        Bundle args = new Bundle();
        args.putInt(StartingFragment.TEA_TYPE_POS, position);
        fragment.setArguments(args);

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
//      setTitle(navDrawerTitles[position]);
        navDrawerLayout.closeDrawer(mDrawerList);

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

01-31 14:11:11.298: E/AndroidRuntime(20904): FATAL EXCEPTION: main
  01-31 14:11:11.298: E/AndroidRuntime(20904): Process:
  appathon.bu.com.appathon, PID: 20904 01-31 14:11:11.298:
  E/AndroidRuntime(20904): java.lang.RuntimeException: Unable to start
  activity
  ComponentInfo{appathon.bu.com.appathon/appathon.bu.com.appathon.MainActivity}:
  java.lang.NullPointerException 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.access$800(ActivityThread.java:144) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.os.Handler.dispatchMessage(Handler.java:102) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.os.Looper.loop(Looper.java:136) 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  android.app.ActivityThread.main(ActivityThread.java:5146) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  java.lang.reflect.Method.invokeNative(Native Method) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  java.lang.reflect.Method.invoke(Method.java:515) 01-31 14:11:11.298:
  E/AndroidRuntime(20904):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  dalvik.system.NativeStart.main(Native Method) 01-31 14:11:11.298:
  E/AndroidRuntime(20904): Caused by: java.lang.NullPointerException
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  appathon.bu.com.appathon.MainActivity.onCreate(MainActivity.java:45)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.Activity.performCreate(Activity.java:5231) 01-31
  14:11:11.298: E/AndroidRuntime(20904):    at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
  01-31 14:11:11.298: E/AndroidRuntime(20904):  ... 11 more


来源: stackexchange

问:
Change UIBarButtonItem Icon after pressed iOS swift
In the viewDidload method, I've declared a button and set RightBarButton...

```<code>    let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
    btnFavourite.addTarget(self, action: "btnFavourite:", forControlEvents: .TouchUpInside)
    btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
    btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Highlighted)
    let rightButton = UIBarButtonItem(customView: btnFavourite)
    self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
</code>```

How do I pressed the button from image 'star.png' then change to 'star_filled.png'? and press the button from 'star_filled.png' to 'star.png'?

How to make two functions like

```<code>func btnFavourite()
{
    //clicked the favourite button then image change to star_filled.png
}

fun btnUnfavourite()
{
    //clicked the button then the bar button image change to star.png
}
</code>```

答:
I'm sure there's a more elegant way to do it, but this is what worked for me:

In viewDidLoad():

```<code>    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let fave_button = UIBarButtonItem(image: UIImage(named: "icon-star"), style: .plain, target: self, action: #selector(favorite))
    let faved_button = UIBarButtonItem(image: UIImage(named: "icon-star-filled"), style: .plain, target: self, action: #selector(unfavorite))
    if YOUROBJECT.faved{
        navigationItem.rightBarButtonItems = [share_button, faved_button]
    }
    else{
        navigationItem.rightBarButtonItems = [share_button, fave_button]
    }
</code>```

Then create the two #selector functions:

```<code>@objc func favorite(){
    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let faved_button = UIBarButtonItem(image: UIImage(named: "icon-star-filled"), style: .plain, target: self, action: #selector(unfavorite))
    navigationItem.rightBarButtonItems = [share_button, faved_button]
    YOUROBJECT.faved = true
}
@objc func unfavorite(){
    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let fave_button = UIBarButtonItem(image: UIImage(named: "icon-star"), style: .plain, target: self, action: #selector(favorite))
    navigationItem.rightBarButtonItems = [share_button, fave_button]
    YOUROBJECT.faved = false
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the viewDidload method, I've declared a button and set RightBarButton...

    let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
    btnFavourite.addTarget(self, action: "btnFavourite:", forControlEvents: .TouchUpInside)
    btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
    btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Highlighted)
    let rightButton = UIBarButtonItem(customView: btnFavourite)
    self.navigationItem.setRightBarButtonItems([rightButton], animated: true)

How do I pressed the button from image 'star.png' then change to 'star_filled.png'? and press the button from 'star_filled.png' to 'star.png'?

How to make two functions like

func btnFavourite()
{
    //clicked the favourite button then image change to star_filled.png
}

fun btnUnfavourite()
{
    //clicked the button then the bar button image change to star.png
}

Body:
I'm sure there's a more elegant way to do it, but this is what worked for me:

In viewDidLoad():

    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let fave_button = UIBarButtonItem(image: UIImage(named: "icon-star"), style: .plain, target: self, action: #selector(favorite))
    let faved_button = UIBarButtonItem(image: UIImage(named: "icon-star-filled"), style: .plain, target: self, action: #selector(unfavorite))
    if YOUROBJECT.faved{
        navigationItem.rightBarButtonItems = [share_button, faved_button]
    }
    else{
        navigationItem.rightBarButtonItems = [share_button, fave_button]
    }

Then create the two #selector functions:

@objc func favorite(){
    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let faved_button = UIBarButtonItem(image: UIImage(named: "icon-star-filled"), style: .plain, target: self, action: #selector(unfavorite))
    navigationItem.rightBarButtonItems = [share_button, faved_button]
    YOUROBJECT.faved = true
}
@objc func unfavorite(){
    let share_button = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    let fave_button = UIBarButtonItem(image: UIImage(named: "icon-star"), style: .plain, target: self, action: #selector(favorite))
    navigationItem.rightBarButtonItems = [share_button, fave_button]
    YOUROBJECT.faved = false
}


问:
Pandas GroupBy column value and create list of fixed size from values in each group
First post, did my best to describe my issue. Let me know if I need to adjust anything with respect to format or clarify any aspects of the problem. Thanks!

I have large Pandas data frame of movie ratings and I need to create user ratings vectors for each movie. I am looking for a way to this more efficiently (using pandas / numpy operations or vectorization??) in order to process the 26M rows or user, movie rating pairs in my dataset.

The data frame of movie ratings looks like this:
Input:

```<code>movieId userId  rating
1            1     1.0
1            2     4.5
1            5     5.0
1            8     5.0
1           10     5.0
2            1     2.0
2            3     4.5
2            5     5.0
2            6     3.0
2            8     4.0
</code>```

Output:

Key = MovieID

Value = Dense array of ratings for each user, 0 means the user did not rate the movie.

```<code>{
   0:[1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0]
   1:[2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]
}
</code>```

I currently have this function which performs the job correctly but is not scaling which the amount of data I need to process.
user_rating_by_movie is a global pandas data frame matching the form of the input.
num_users is the largest user id to serve as the length of the vector.

```<code>def build_rating_vector_for_movie(movie_id, num_users):
    rating_vector = [0] * num_users
    movie_group = user_rating_by_movie.get_group(movie_id)

    for u, r in zip(movie_group.userId.values, movie_group.rating.values):
        rating_vector[u - 1] = r

    movie_user_ratings[movie_id] = rating_vector
</code>```

Body:
First post, did my best to describe my issue. Let me know if I need to adjust anything with respect to format or clarify any aspects of the problem. Thanks!

I have large Pandas data frame of movie ratings and I need to create user ratings vectors for each movie. I am looking for a way to this more efficiently (using pandas / numpy operations or vectorization??) in order to process the 26M rows or user, movie rating pairs in my dataset.

The data frame of movie ratings looks like this:
Input:

movieId userId  rating
1            1     1.0
1            2     4.5
1            5     5.0
1            8     5.0
1           10     5.0
2            1     2.0
2            3     4.5
2            5     5.0
2            6     3.0
2            8     4.0

Output:

Key = MovieID

Value = Dense array of ratings for each user, 0 means the user did not rate the movie.

{
   0:[1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0]
   1:[2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]
}

I currently have this function which performs the job correctly but is not scaling which the amount of data I need to process.
user_rating_by_movie is a global pandas data frame matching the form of the input.
num_users is the largest user id to serve as the length of the vector.

def build_rating_vector_for_movie(movie_id, num_users):
    rating_vector = [0] * num_users
    movie_group = user_rating_by_movie.get_group(movie_id)

    for u, r in zip(movie_group.userId.values, movie_group.rating.values):
        rating_vector[u - 1] = r

    movie_user_ratings[movie_id] = rating_vector

Body:
By using pivot+reindex

df.pivot('movieId','userId',values='rating').reindex(columns=list(range(1,11))).fillna(0)
Out[219]:
userId    1    2    3    4    5    6    7    8    9    10
movieId
1        1.0  4.5  0.0  0.0  5.0  0.0  0.0  5.0  0.0  5.0
2        2.0  0.0  4.5  0.0  5.0  3.0  0.0  4.0  0.0  0.0

For build the dict add .T.to_dict('list') at the end

df.pivot('movieId','userId',values='rating').reindex(columns=list(range(1,11))).fillna(0).T.to_dict('list')
Out[223]:
{1: [1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0],
 2: [2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]}


问:
The return of AsyncTask is null. Why?
I have created an app that gets the data from mysql server. As long as I need to use the AsyncTask a lot of times. I created a class that holds the AsyncTask and then, I used a getter method to get the results from my AsyncTask class.
So, First, I created AsyncTask as the followings  :

```<code>public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
}

public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}
</code>```

Then I called it from another class as the followings:

```<code>public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this);
    get_contacts_details.execute();
        \\ my is always NULL.

     my = get_contacts_details.getNames();
    for(int i = 0 ; i> my.length;i++)
    {
        TheNames+=my[i]+"\n";
    }
    return TheNames ;
}
</code>```

The string array my is always Null. How can I solve that ?

答:
Asynctask doesn't work in that way.
You should update your UI/logic after onPostExecute

```<code>@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
//HERE
    String names = "";
    for(int i = 0 ; i> TheNames.length;i++)
    {
        names+=TheNames[i]+"\n";
    }

}
</code>```

If you want returns data to your activity use an Interface ,
Refer to this documentation about the AsyncTask :
https://developer.android.com/reference/android/os/AsyncTask.html

Update

Use the code below

Create this interface class:

```<code>public interface DataListener {

    void onDataListener (String[] data);
}
</code>```

Modifiy your Asynctask class

```<code>public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
private DataListener mListener;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext, DataListener mListener)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
    this.mListener = mListener;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);

    if (mListener != null){
       mListener.onDataListener(TheNames);
    }
}

public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}
</code>```

Modify your activity class

```<code>public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this, listener);
    get_contacts_details.execute();

    //you can't return TheNames value here

    return TheNames ;
}

public DataListener listener = new DataListener() {

      @Override
      public void onDataListener (String[] data) {
           for(int i = 0 ; i> data.length;i++)
            {
                TheNames+=data[i]+"\n";
            }

            //now your have the data here, use in your activity, update your UI, etc.

      }
}

}
</code>```

Keep in mind that AsyncTask is used for asynchronous task, do don't expect to return your data inside your getText() method, btw who is calling to getText() method?

Title: The return of AsyncTask is null. Why?

Body:
I have created an app that gets the data from mysql server. As long as I need to use the AsyncTask a lot of times. I created a class that holds the AsyncTask and then, I used a getter method to get the results from my AsyncTask class.
So, First, I created AsyncTask as the followings  :

public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
}

public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}

Then I called it from another class as the followings:

public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this);
    get_contacts_details.execute();
        \\ my is always NULL.

     my = get_contacts_details.getNames();
    for(int i = 0 ; i> my.length;i++)
    {
        TheNames+=my[i]+"\n";
    }
    return TheNames ;
}

The string array my is always Null. How can I solve that ?

Body:
Asynctask doesn't work in that way.
You should update your UI/logic after onPostExecute

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
//HERE
    String names = "";
    for(int i = 0 ; i> TheNames.length;i++)
    {
        names+=TheNames[i]+"\n";
    }

}

If you want returns data to your activity use an Interface ,
Refer to this documentation about the AsyncTask :
https://developer.android.com/reference/android/os/AsyncTask.html

Update

Use the code below

Create this interface class:

public interface DataListener {

    void onDataListener (String[] data);
}

Modifiy your Asynctask class

public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
private DataListener mListener;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext, DataListener mListener)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
    this.mListener = mListener;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);

    if (mListener != null){
       mListener.onDataListener(TheNames);
    }
}

public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}

Modify your activity class

public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this, listener);
    get_contacts_details.execute();

    //you can't return TheNames value here

    return TheNames ;
}

public DataListener listener = new DataListener() {

      @Override
      public void onDataListener (String[] data) {
           for(int i = 0 ; i> data.length;i++)
            {
                TheNames+=data[i]+"\n";
            }

            //now your have the data here, use in your activity, update your UI, etc.

      }
}

}

Keep in mind that AsyncTask is used for asynchronous task, do don't expect to return your data inside your getText() method, btw who is calling to getText() method?


问:
Implementing Publish Subscribe Using JMS Spring ActiveMQ
I want to know how to define Topoic,COnnectionfactory,session in  the configuration file(in XML File) that has to be done for implementing Publish Subscribe(Using Topic) in JMS Spring ActiveMQ?

Please find the below link for detailed explanation.

http://forum.springsource.org/showthread.php?t=101397

Please help on this..
Regards
Srini

答:
I have found the problem.

The destination-type was not given before.Hence it has taken the default as Queue.

Regards
Srini

ContentLicense: CC BY-SA 2.5


问:
Regex replace and append string
I managed to delete every '-xx' in a string (Example 1).
I would like your help to make examples 2 and 3 to work.

function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';

    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;

    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';

    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Test this</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p></code>```

答:
You can replace vi-([-\w]+)-xx to vi-$1 for case 2

and vi-([-\w]+) to vi-$1-xx for case 3.

Snippet:

function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';

    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;

    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';
    var res2 = str1.replace(/vi-([-\w]+)-xx/g, "vi-$1");
    document.getElementById("demo2").innerHTML = res2;

    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';
    var res3 = str2.replace(/vi-([-\w]+)/g, "vi-$1-xx");
    document.getElementById("demo3").innerHTML = res3;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Test this</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p></code>```

Title: Regex replace and append string

Body:
I managed to delete every '-xx' in a string (Example 1).
I would like your help to make examples 2 and 3 to work.

function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';

    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;

    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';

    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';

}

<button onclick="myFunction()">Test this</button>

Body:
You can replace vi-([-\w]+)-xx to vi-$1 for case 2

and vi-([-\w]+) to vi-$1-xx for case 3.

Snippet:

function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';

    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;

    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';
    var res2 = str1.replace(/vi-([-\w]+)-xx/g, "vi-$1");
    document.getElementById("demo2").innerHTML = res2;

    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';
    var res3 = str2.replace(/vi-([-\w]+)/g, "vi-$1-xx");
    document.getElementById("demo3").innerHTML = res3;

}

<button onclick="myFunction()">Test this</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>


问:
Angular 4 http get request - Exception: A network error occured
I am trying to connect my ionic / angular app to a spring boot back end. I check the back end with postman and am able to get a result from the get request. When I do it with my app I get "A network error occurred". I am just learning angular - but I do another get request to firebase - and that request works fine. After doing some research ppl suggested it might be related to CORS - I have Cross Origins enabled on the spring boot app - also downloaded the extension to turn off just to make sure.

Any help would be great! Code below.

Error Message

localhost:8080

Springboot Controller

(from service)

```<code>getTimesheets() {
    console.log('Service: getTimesheets()')
    console.log('URL: ' + this.url)

    return this.http
        .get(this.url)
        .subscribe(data => {
            console.log(data)
        });
}
</code>```

(from timesheet.ts)

```<code>getTimeSheets() {
    this.timeSheetService.getTimesheets()
  }
</code>```

答: I fixed it - I forgot the 'http://' in front of the url...</p>

Body:
I am trying to connect my ionic / angular app to a spring boot back end. I check the back end with postman and am able to get a result from the get request. When I do it with my app I get "A network error occurred". I am just learning angular - but I do another get request to firebase - and that request works fine. After doing some research ppl suggested it might be related to CORS - I have Cross Origins enabled on the spring boot app - also downloaded the extension to turn off just to make sure.

Any help would be great! Code below.

Error Message

localhost:8080

Springboot Controller

(from service)

getTimesheets() {
    console.log('Service: getTimesheets()')
    console.log('URL: ' + this.url)

    return this.http
        .get(this.url)
        .subscribe(data => {
            console.log(data)
        });
}

(from timesheet.ts)

getTimeSheets() {
    this.timeSheetService.getTimesheets()
  }


问:
How to correctly perform multithreading so that icons on individual threads move across the screen together?
I'm trying to create an animation in which a given number of icons start on the left side of the frame and move to the right side of the screen. The icons are lined up vertically and each is supposed to run on its own thread.

How do I get all icons to do this? I tried adjusting posY when I create each racer, but so far I can only get the last racer that's created to show.

```<code>import javax.swing.*;
import java.awt.*;

public class Races {
    private JFrame frame;
    private JPanel gui;
    private Icon img;
    private int imgWidth;
    private int imgHeight;
    private int numOfRacers;  // num of threads / racers

    public static void main(String[] args) {
        new Races(5);
    }

    public Races(int num) {
        numOfRacers = num;
        createGUI();
        frame.add(gui);
        frame.pack();
        frame.setVisible(true);
    }

    private void createGUI() {
        frame = new JFrame("Off to the Races - by Brienna Herold");
        gui = new JPanel();
        gui.setPreferredSize(new Dimension(imgWidth * 20, imgHeight * numOfRacers));

        img = new ImageIcon("races.png");
        imgWidth = img.getIconWidth();
        imgHeight = img.getIconHeight();

        int posY = 0;
        for (int i = 0; i < numOfRacers; i++) {
            System.out.println("Starting new thread..." + posY);
            racer = new Racer(posY);
            Thread racerThread = new Thread(racer);
            racerThread.start();
            posY += imgHeight;
        }
    }

    protected class Racer extends JPanel implements Runnable {
        private int lastPosX;
        private int posX;
        private int posY;

        public Racer(int _posY) {
            posX = 0;
            posY = _posY;
        }

        @Override
        public void paintComponent(Graphics g) {
            // Call the method on the JPanel
            super.paintComponent(g);
            img.paintIcon(gui, g, posX, posY);
            //posY += imgHeight;
            posX += lastPosX + 3;
        }

        @Override
        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
</code>```

答:
```<code>gui.add(racer, BorderLayout.CENTER);
</code>```

You only ever add one Racer component to the frame.

but so far I can only get the last racer that's created to show.

The "racer" variable points to the last Racer component created.

If you want multiple components then you will need to create a panel using a null layout. Then you need to add each Racer component to this panel and then add the panel to the frame. Using this approach you would move the component by using the setLocation(...) method of the component.

If you want to paint an image in a different location, then you would use a single panel which would contain an ArrayList or Racer objects. Then when the paintComponent() method of the panel is invoked you iterate through the List and paint each Racer at its new location.

Body:
I'm trying to create an animation in which a given number of icons start on the left side of the frame and move to the right side of the screen. The icons are lined up vertically and each is supposed to run on its own thread.

How do I get all icons to do this? I tried adjusting posY when I create each racer, but so far I can only get the last racer that's created to show.

import javax.swing.*;
import java.awt.*;

public class Races {
    private JFrame frame;
    private JPanel gui;
    private Icon img;
    private int imgWidth;
    private int imgHeight;
    private int numOfRacers;  // num of threads / racers

    public static void main(String[] args) {
        new Races(5);
    }

    public Races(int num) {
        numOfRacers = num;
        createGUI();
        frame.add(gui);
        frame.pack();
        frame.setVisible(true);
    }

    private void createGUI() {
        frame = new JFrame("Off to the Races - by Brienna Herold");
        gui = new JPanel();
        gui.setPreferredSize(new Dimension(imgWidth * 20, imgHeight * numOfRacers));

        img = new ImageIcon("races.png");
        imgWidth = img.getIconWidth();
        imgHeight = img.getIconHeight();

        int posY = 0;
        for (int i = 0; i < numOfRacers; i++) {
            System.out.println("Starting new thread..." + posY);
            racer = new Racer(posY);
            Thread racerThread = new Thread(racer);
            racerThread.start();
            posY += imgHeight;
        }
    }

    protected class Racer extends JPanel implements Runnable {
        private int lastPosX;
        private int posX;
        private int posY;

        public Racer(int _posY) {
            posX = 0;
            posY = _posY;
        }

        @Override
        public void paintComponent(Graphics g) {
            // Call the method on the JPanel
            super.paintComponent(g);
            img.paintIcon(gui, g, posX, posY);
            //posY += imgHeight;
            posX += lastPosX + 3;
        }

        @Override
        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}

Body:
gui.add(racer, BorderLayout.CENTER);

You only ever add one Racer component to the frame.

but so far I can only get the last racer that's created to show.

The "racer" variable points to the last Racer component created.

If you want multiple components then you will need to create a panel using a null layout. Then you need to add each Racer component to this panel and then add the panel to the frame. Using this approach you would move the component by using the setLocation(...) method of the component.

If you want to paint an image in a different location, then you would use a single panel which would contain an ArrayList or Racer objects. Then when the paintComponent() method of the panel is invoked you iterate through the List and paint each Racer at its new location.


问:
Chrome update suddenly breaks @font-face
I'm trying to use @font-face to replace instances of a font. This has usually worked for me:

```<code>@font-face {
    font-family: 'Arial';
    font-weight: bold;
    font-style: italic;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    font-weight: bold;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    font-style: italic;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    src: local('Times New Roman');
}
</code>```

With the end result being instances of Arial being replaced with Times New Roman. In fact, this works on a separate computer running Windows 10 and Chrome 61.0.3163.100.

However, after a recent update to 62.0.3202.62, Arial is still replaced with Times New Roman, but bold and italics no longer work. Trying to reference something like "Times New Roman Bold" doesn't work and just defaults back to Arial. Placing !important after the bold and italic src lines gives faux-bold and faux-italics.

Was the old behaviour wrong? What is the proper way to replace a font through CSS, if that is even possible?

答:
We can't reference something like "Times New Roman Bold" or "Arial Bold", looks like it's a bug of Chrome, Read below.

The tracked issue: https://bugs.chromium.org/p/chromium/issues/detail?id=627143, in #25 drott refer the spec for local().

Here drott replied why:

Our local matching is broken and uses family name for matching, instead of postscript name

  ——drott

Here drott said previous workaround breaks what Google Fonts is expecting on Android Chrome.

this change actually makes src: local() handling more correct by taking the styling out the equation, but indeed breaks what Google Fonts is expecting.

There are two problems: Our src: local() matching is broken and does not match full font name or postscript font name, that's issue 627143.

What we do instead, we match src: local() against font family name, plus we take into account the stretch, style, weight request (coming from the CSS styling, stored in FontDescription) and feed this into the family matching.

With this broken local() matching, Google fonts' CSS manages to match against the local robot variants using just local("sans-serif") plus font-weight: bold and font-weight: 100, or 300.

I am going to partially revert the above CL and reinstate the bug, until I get to fixing local() matching in a more durable way.

  ——drott

Related commits.

Previous workaround: https://chromium-review.googlesource.com/c/chromium/src/+/589270/3/third_party/WebKit/Source/core/css/LocalFontFaceSource.cpp

Then tried to fix Google Fonts issue on Android Chrome: https://chromium-review.googlesource.com/c/chromium/src/+/708269/3/third_party/WebKit/Source/core/css/LocalFontFaceSource.cpp

Body:
I'm trying to use @font-face to replace instances of a font. This has usually worked for me:

@font-face {
    font-family: 'Arial';
    font-weight: bold;
    font-style: italic;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    font-weight: bold;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    font-style: italic;
    src: local('Times New Roman');
}

@font-face {
    font-family: 'Arial';
    src: local('Times New Roman');
}

With the end result being instances of Arial being replaced with Times New Roman. In fact, this works on a separate computer running Windows 10 and Chrome 61.0.3163.100.

However, after a recent update to 62.0.3202.62, Arial is still replaced with Times New Roman, but bold and italics no longer work. Trying to reference something like "Times New Roman Bold" doesn't work and just defaults back to Arial. Placing !important after the bold and italic src lines gives faux-bold and faux-italics.

Was the old behaviour wrong? What is the proper way to replace a font through CSS, if that is even possible?


问:
html figure element: can figcaption be placed before img
Is it semantically/syntactically correct to have the figcaption element be positioned anywhere within the figure element?

Consider the following:

```<code><figure>
  <figcaption>Hello caption</figcaption>
  <img src="/path/to/file">
</figure>
</code>```

答:
tl;dr:

W3C: figcaption can be placed anywhere in figure (as child, not  descendant)

WHATWG: figcaption can be placed as first or as last child of figure

W3C

In HTML5, the figcaption element has to be the first or the last child of figure:

Either: One figcaption element followed by flow content.

  Or: Flow content followed by one figcaption element.

  Or: Flow content.

In HTML 5.1, the figcaption element can be placed anywhere in the figure element:

Flow content optionally including a figcaption child element.

In HTML 5.1 2nd Edition, too.

In HTML 5.2 (Proposed REC), too.

Here’s the issue about the change:

Allow figcaption anywhere in a figure element?

WHATWG

In the HTML Living Standard (as of 2017-11-17), it’s the same as in HTML5:

Either: One figcaption element followed by flow content.

  Or: Flow content followed by one figcaption element.

  Or: Flow content.

Body:
Is it semantically/syntactically correct to have the figcaption element be positioned anywhere within the figure element?

Consider the following:

Hello caption


问:
How do I declare a user defined attribute in version 0.9.1
I am trying to migrate from version 0.8.1 to 0.9.1 in Scala js. Previously, if I wanted to have a user defined attribute in an element I did so as follows:

```<code>button("my-attribute".attr = "false")
</code>```

But does no longer compiles in version 0.9.1. What is the correct approach now?

答:
I'm not sure what library you were using, but it almost looks like ScalaTags. If so, the syntax you want is:

```<code>button(attr("my-attribute") := "false")
</code>```

ScalaTags Docs

I vaguely recall that ScalaTags used to have the .attr syntax you describe – it definitely looks familiar, but I can't find it right now. Maybe it was removed... And it is definitely :=, not =.

Also, the only relevant library I know where 0.9.1 is a relevant version number is scala-js-dom, but that library doesn't provide anything like the example you're describing.

Body:
I am trying to migrate from version 0.8.1 to 0.9.1 in Scala js. Previously, if I wanted to have a user defined attribute in an element I did so as follows:

button("my-attribute".attr = "false")

But does no longer compiles in version 0.9.1. What is the correct approach now?

Body:
I'm not sure what library you were using, but it almost looks like ScalaTags. If so, the syntax you want is:

button(attr("my-attribute") := "false")

ScalaTags Docs

I vaguely recall that ScalaTags used to have the .attr syntax you describe – it definitely looks familiar, but I can't find it right now. Maybe it was removed... And it is definitely :=, not =.

Also, the only relevant library I know where 0.9.1 is a relevant version number is scala-js-dom, but that library doesn't provide anything like the example you're describing.


问:
How do I tell programatically if I am running under Medium Trust?
In C# how do I tell if my assembly is running under medium trust in asp.net?  Is there something similar to Debugger.IsAttached for this?</p>

答:
Or you can use this slightly shorter version</p>

```<code>public AspNetHostingPermissionLevel GetCurrentTrustLevel()
{
    foreach (AspNetHostingPermissionLevel trustLevel in Enum.GetValues(typeof(AspNetHostingPermissionLevel)))
    {
        try
        {
            new AspNetHostingPermission(trustLevel).Demand();
        }
        catch (System.Security.SecurityException)
        {
            continue;
        }
        return trustLevel;
    }
    return AspNetHostingPermissionLevel.None;
}
</code>```

Body:
Or you can use this slightly shorter version

public AspNetHostingPermissionLevel GetCurrentTrustLevel()
{
    foreach (AspNetHostingPermissionLevel trustLevel in Enum.GetValues(typeof(AspNetHostingPermissionLevel)))
    {
        try
        {
            new AspNetHostingPermission(trustLevel).Demand();
        }
        catch (System.Security.SecurityException)
        {
            continue;
        }
        return trustLevel;
    }
    return AspNetHostingPermissionLevel.None;
}


问:
Pyramid Framework : Stream Camera using Opencv
I have been trying to stream my webcam using the pyramid framework. The thing is the object generated is a generator object, and when I'm passing it over views, I do get the video stream at route (/video_feed) but it lags a lot. anyone?

here's the block of code for it

from pyramid.response import Response
from pyramid.view import view_config

from sqlalchemy.exc import DBAPIError

from ..models import MyModel
import cv2

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __iter__(self):
        return self

    def close(self):
        self.video.release()

    def get_frame(self):
        success,image = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

    __next__=get_frame

@view_config(route_name='home', renderer='templates/stream.jinja2')
def my_view(request):
    return {'project': 'my_project'}

def generate(camera):
    while True:
        frame = camera.__next__()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@view_config(route_name="video_feed")
def video(request):
    return Response(
        app_iter=generate(VideoCamera()),
        content_type="multipart/x-mixed-replace; boundary=frame")
```

Help!

答:
It's probable that your WSGI server or any other upstream proxy is buffering the streaming responses. If this is waitress I think you can set send_bytes to something lower than the default.

https://docs.pylonsproject.org/projects/waitress/en/latest/arguments.html

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to stream my webcam using the pyramid framework. The thing is the object generated is a generator object, and when I'm passing it over views, I do get the video stream at route (/video_feed) but it lags a lot. anyone?

here's the block of code for it

from pyramid.response import Response
from pyramid.view import view_config

from sqlalchemy.exc import DBAPIError

from ..models import MyModel
import cv2

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __iter__(self):
        return self

    def close(self):
        self.video.release()

    def get_frame(self):
        success,image = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

    __next__=get_frame

@view_config(route_name='home', renderer='templates/stream.jinja2')
def my_view(request):
    return {'project': 'my_project'}

def generate(camera):
    while True:
        frame = camera.__next__()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@view_config(route_name="video_feed")
def video(request):
    return Response(
        app_iter=generate(VideoCamera()),
        content_type="multipart/x-mixed-replace; boundary=frame")

Help!


问:
Read file after open KB - Genexus extensions
I am creating a GeneXus extension and I want that on the AfterOpenKB event the extension reads a file. So, what I did was copy the files that I need read to the packages folder in GX. The thing is that when I am debugging the extension, the method AfterOpenKB is called twice and in one of those is searching for the file in the KB's folder.

The question is, it's expected that the method trigger twice or am I doing something wrong? Should I copy the file to the KB's folder too?

Thanks!

答:
The AfterOpenKB event should be fired only once every time a process opens a KB. Is your extension a UI or a BL extension? I suspect you're developing a BL extension, and what you're seeing is that the MSBuild process for the specifier, which is an independent process and also starts the GX BL, triggers the AfterOpenKB event when opening the same KB as the GX process is opening.

Can't give an answer to if you should copy the files to the KB folder, without knowing exactly what the extension is doing, but in general, don't believe is a good practice to copy files to the GX installation when opening a KB. Note that it'll be fairly common that GX is located inside Program Files, and writing files into that path will require elevated privileges. Currently GX requires to run as an elevated process, but that's something we may like to change in the future, so I heavily suggest against depending on that. The KB folder seems a better place to copy the files, but again, can't tell for sure without knowing exactly what the extension is doing and what are the files for.

Hope that helps.


问:
How to reset state of redux store while using react-navigation when react-navigation reset does not immediately unmount screens from stack?
I'm trying to do auth sign-out with react-native and am experiencing an issue where I want to reset the state of the redux store but, because I am using react-navigation, I have a bunch of redux-connected screens that are still mounted that re-render when the state tree is reset to it's initialState causing a bunch of exception errors. I tried to unmount them on sign-out with a react-navigation reset which redirects the user to the signup/login screen but I have no way of knowing when these screens are actually unmounted in order to call the RESET_STATE action. Initially I was dispatching the action via saga.

sagas/logout.js

import { LOGOUT, RESET_STATE } from 'Actions/user';

// clear localstorage once user logs out.
const clearData = function* clearData(action) {
  AsyncStorage.removeItem('user');

  yield put(
    NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'SignedOut' })
      ],
    })
  );
  // causes re-renders, screens still mounted
  yield put({type: RESET_STATE});
}

export default function* logoutSaga () {
  yield all([
    yield takeEvery(LOGOUT, clearData),
  ]);
}```
</div>
</div>
</p>

<p>I also tried to reset once user reaches the SignedOut screen in it's componentDidMount cycle but unfortunately the screens unmount at some point well after componentDidMount is triggered:</p>

<p><strong>screens/SignedOut.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { resetState } from 'Actions/user';
import ActionButton from 'Components/FormElements/ActionButton';

class SignedOut extends Component {
  // screens are still mounted, causing screens from
  // previous screens to throw exception errors
  componentDidMount() {
    this.props.dispatch(resetState());
  }

  componentWillUnmount() {
    // never called
  }

  handleSignup = () => {
    this.props.navigation.navigate('Signup');
  }

  handleLogin = () => {
    this.props.navigation.navigate('Login');
  }

  render() {
    return(
      <Container>
        <ActionButton
          text="Sign Up"
          handleButtonPress={this.handleSignup}
        />
        <ActionButton
          text="Log In"
          handleButtonPress={this.handleLogin}
        />
      </Container>
    );
  }
}

export default connect()(SignedOut);</code>```

My question is, can anyone think of a way to reset state of redux store after all of my screens have finally unmounted by the react-navigation reset action?

答: As i have no idea how ur state looks like, which is always the issue here, why not try to use componentWillUnmount on all those components, to set a state variable and check that when you want to reset navigation?</p>

Body:
I'm trying to do auth sign-out with react-native and am experiencing an issue where I want to reset the state of the redux store but, because I am using react-navigation, I have a bunch of redux-connected screens that are still mounted that re-render when the state tree is reset to it's initialState causing a bunch of exception errors. I tried to unmount them on sign-out with a react-navigation reset which redirects the user to the signup/login screen but I have no way of knowing when these screens are actually unmounted in order to call the RESET_STATE action. Initially I was dispatching the action via saga.

sagas/logout.js

import { LOGOUT, RESET_STATE } from 'Actions/user';

// clear localstorage once user logs out.
const clearData = function* clearData(action) {
  AsyncStorage.removeItem('user');

  yield put(
    NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'SignedOut' })
      ],
    })
  );
  // causes re-renders, screens still mounted
  yield put({type: RESET_STATE});
}

export default function* logoutSaga () {
  yield all([
    yield takeEvery(LOGOUT, clearData),
  ]);
}

I also tried to reset once user reaches the SignedOut screen in it's componentDidMount cycle but unfortunately the screens unmount at some point well after componentDidMount is triggered:

screens/SignedOut.js

import { resetState } from 'Actions/user';
import ActionButton from 'Components/FormElements/ActionButton';

class SignedOut extends Component {
  // screens are still mounted, causing screens from
  // previous screens to throw exception errors
  componentDidMount() {
    this.props.dispatch(resetState());
  }

  componentWillUnmount() {
    // never called
  }

  handleSignup = () => {
    this.props.navigation.navigate('Signup');
  }

  handleLogin = () => {
    this.props.navigation.navigate('Login');
  }

  render() {
    return(
      <Container>
        <ActionButton
          text="Sign Up"
          handleButtonPress={this.handleSignup}
        />
        <ActionButton
          text="Log In"
          handleButtonPress={this.handleLogin}
        />
      </Container>
    );
  }
}

export default connect()(SignedOut);

My question is, can anyone think of a way to reset state of redux store after all of my screens have finally unmounted by the react-navigation reset action?


问:
Wrong Calculation by User-Defined SQL-Function
I have a function defined by

```<code>CREATE OR REPLACE FUNCTION public.div(dividend INTEGER, divisor INTEGER)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    LEAKPROOF
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT ($1 + $2/2) / $2;
    $BODY$;
</code>```

It should calculate a commercial rounded result. Most of the times, it does the job. I don't know why, but select div(5, 3) gives me the correct answer while it doesn't when one parameter is calculated by an aggregate, e.g. select div(sum(val), 3) from (select 1 as val UNION SELECT 4) list is sufficient to trigger that.
How can I fix div? I don't want to cast every input.

BTW, using SELECT (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer); as the definition of div didn't help.

答:
Allow floats as parameters, then explicitly cast at the calculation, otherwise you have an implied conversion whilst passing the parameter.

```<code>CREATE OR REPLACE FUNCTION my_div(dividend FLOAT, divisor FLOAT)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    -- LEAKPROOF -- not allowed at dbfiddle.uk
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT --($1 + $2/2) / $2;
           (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer)
    $BODY$;
</code>```
```
✓
```

```<code>select my_div(sum(val), 3)
from (select 1 as val UNION SELECT 4) x
</code>```
```
| my_div |
| -----: |
|      2 |
```

dbfiddle here

Body:
I have a function defined by

CREATE OR REPLACE FUNCTION public.div(dividend INTEGER, divisor INTEGER)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    LEAKPROOF
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT ($1 + $2/2) / $2;
    $BODY$;

It should calculate a commercial rounded result. Most of the times, it does the job. I don't know why, but select div(5, 3) gives me the correct answer while it doesn't when one parameter is calculated by an aggregate, e.g. select div(sum(val), 3) from (select 1 as val UNION SELECT 4) list is sufficient to trigger that.
How can I fix div? I don't want to cast every input.

BTW, using SELECT (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer); as the definition of div didn't help.

Body:
Allow floats as parameters, then explicitly cast at the calculation, otherwise you have an implied conversion whilst passing the parameter.

CREATE OR REPLACE FUNCTION my_div(dividend FLOAT, divisor FLOAT)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    -- LEAKPROOF -- not allowed at dbfiddle.uk
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT --($1 + $2/2) / $2;
           (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer)
    $BODY$;

✓

select my_div(sum(val), 3)
from (select 1 as val UNION SELECT 4) x

| my_div |
| -----: |
|      2 |

dbfiddle here


问:
Allowing Global Hotkeys
First of all, I am not a true coder however I am happy with what I have done thus far.

I have written this code below which is to do with robotics. The code below allows me to user keyboard shortcuts when you click on the form. However, I need the hotkeys to work whether the application is or is not in focus or even minimized.

I have looked already online but it is not very clear.

```<code>Public Class MainForm

    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        'End If

    End Sub

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "0")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R)
        'End If

    End Sub

Public Class MainForm

    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        'End If

    End Sub

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "0")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R)
        'End If

    End Sub

End Class
</code>```

Update:

Right. I have added a class now which allow GlobalKey to be registered.

In my main form I now have this key:

```<code>   Public Class MainForm
    Dim hkr As New HotKeyRegistryClass(Me.Handle)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.A).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.S).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.D).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.F).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.G).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_SHIFT Or HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.H).ToString()
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE
            Dim ID As String = m.WParam.ToString()
            Select Case ID
                Case 0 : If DF1Com1.Write("O:1/0", "1") Then DF1Com1.Write("O:1/0", "0")
                Case 1 : MessageBox.Show("S")
                Case 2 : MessageBox.Show("D")
                Case 3 : MessageBox.Show("F")
                Case 4 : MessageBox.Show("G")
                Case 5 : MessageBox.Show("H")
            End Select
        End If
        MyBase.WndProc(m)
    End Sub
</code>```

If you have a look at Case 0. It works however it does not put the key back up. It leaves it pressed down all the time. I need it when the key is depressed it 'DF1Com1.Write("O:1/0", "0")'

Class Code

```<code>Public NotInheritable Class HotKeyRegistryClass
    Private Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32, ByVal fsModifier As Int32, ByVal vk As Int32) As Int32
    Private Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32) As Int32
    Private Handle As IntPtr = IntPtr.Zero
    Private Registry As New System.Collections.Generic.List(Of Int32)
    Public Enum Messages
        [WM_HOTKEY] = &H312
    End Enum
    Public Enum Modifiers
        [MOD_ALT] = &H1
        [MOD_CTRL] = &H2
        [MOD_SHIFT] = &H4
    End Enum
    Sub New(ByVal Handle As IntPtr)
        Me.Handle = Handle
    End Sub
    Public Function Register(ByVal Modifier As Int32, ByVal Key As System.Windows.Forms.Keys) As Int32
        Dim ret As Int32
        ret = NextAvailableIndex()
        Call RegisterHotKey(Me.Handle, ret, Modifier, Key)
        Registry.Insert(ret, ret)
        Return ret
    End Function
    Public Sub Unregister(ByVal ID As Int32)
        Call UnregisterHotKey(Me.Handle, ID)
        Registry.Remove(ID)
    End Sub
    Private Function NextAvailableIndex() As Int32
        Dim ret As Int32 = 0
        Dim n As Int32 = 0
        For i As Int32 = 0 To Registry.Count - 1
            If Registry(i) = n Then
                n = n + 1
            ElseIf n < Registry(i) Then
                Return n
            End If
        Next
        If n = Registry.Count Then
            Return Registry.Count
        End If
        Return ret
    End Function
End Class
</code>```

答:
Unfortunately, RegisterHotkey only tells you when a key combination has been activated. Also, as you already realize, the KeyDown and KeyUp events you have will only work when your app has focus.

The only way you can get truly global KeyDown and KeyUp is by using a low level keyboard hook. Since I don't want to copy my entire answer I will simply link to it. The link will provide you some direction in setting up a keyboard hook.

How to disable/override Windows 10 Hotkeys with C#

Another possibility is to execute both commands on the hotkey activation like this...

```<code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE
            Dim ID As String = m.WParam.ToString()
            Select Case ID
                Case 0 :
                    DF1Com1.Write("O:1/0", "1")
                    System.Threading.Thread.Sleep(2000)
                    DF1Com1.Write("O:1/0", "0")
                Case 1 : MessageBox.Show("S")
                Case 2 : MessageBox.Show("D")
                Case 3 : MessageBox.Show("F")
                Case 4 : MessageBox.Show("G")
                Case 5 : MessageBox.Show("H")
            End Select
        End If
        MyBase.WndProc(m)
    End Sub
</code>```

Title: Allowing Global Hotkeys

Body:
First of all, I am not a true coder however I am happy with what I have done thus far.

I have written this code below which is to do with robotics. The code below allows me to user keyboard shortcuts when you click on the form. However, I need the hotkeys to work whether the application is or is not in focus or even minimized.

I have looked already online but it is not very clear.

Public Class MainForm

    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        'End If

    End Sub

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "0")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R)
        'End If

    End Sub

Public Class MainForm

    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "1")  ' (O:9/0) (R)
        'End If

    End Sub

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp

        If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
            DF1Com1.Write("O:1/0", "0")  ' (O:9/0) (R)
        End If

        'If e.KeyCode = Keys.R Then
        'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R)
        'End If

    End Sub

End Class

Update:

Right. I have added a class now which allow GlobalKey to be registered.

In my main form I now have this key:

   Public Class MainForm
    Dim hkr As New HotKeyRegistryClass(Me.Handle)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.A).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.S).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.D).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.F).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.G).ToString()
        hkr.Register(HotKeyRegistryClass.Modifiers.MOD_SHIFT Or HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.H).ToString()
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE
            Dim ID As String = m.WParam.ToString()
            Select Case ID
                Case 0 : If DF1Com1.Write("O:1/0", "1") Then DF1Com1.Write("O:1/0", "0")
                Case 1 : MessageBox.Show("S")
                Case 2 : MessageBox.Show("D")
                Case 3 : MessageBox.Show("F")
                Case 4 : MessageBox.Show("G")
                Case 5 : MessageBox.Show("H")
            End Select
        End If
        MyBase.WndProc(m)
    End Sub

If you have a look at Case 0. It works however it does not put the key back up. It leaves it pressed down all the time. I need it when the key is depressed it 'DF1Com1.Write("O:1/0", "0")'

Class Code

Public NotInheritable Class HotKeyRegistryClass
    Private Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32, ByVal fsModifier As Int32, ByVal vk As Int32) As Int32
    Private Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32) As Int32
    Private Handle As IntPtr = IntPtr.Zero
    Private Registry As New System.Collections.Generic.List(Of Int32)
    Public Enum Messages
        [WM_HOTKEY] = &H312
    End Enum
    Public Enum Modifiers
        [MOD_ALT] = &H1
        [MOD_CTRL] = &H2
        [MOD_SHIFT] = &H4
    End Enum
    Sub New(ByVal Handle As IntPtr)
        Me.Handle = Handle
    End Sub
    Public Function Register(ByVal Modifier As Int32, ByVal Key As System.Windows.Forms.Keys) As Int32
        Dim ret As Int32
        ret = NextAvailableIndex()
        Call RegisterHotKey(Me.Handle, ret, Modifier, Key)
        Registry.Insert(ret, ret)
        Return ret
    End Function
    Public Sub Unregister(ByVal ID As Int32)
        Call UnregisterHotKey(Me.Handle, ID)
        Registry.Remove(ID)
    End Sub
    Private Function NextAvailableIndex() As Int32
        Dim ret As Int32 = 0
        Dim n As Int32 = 0
        For i As Int32 = 0 To Registry.Count - 1
            If Registry(i) = n Then
                n = n + 1
            ElseIf n < Registry(i) Then
                Return n
            End If
        Next
        If n = Registry.Count Then
            Return Registry.Count
        End If
        Return ret
    End Function
End Class

Body:
Unfortunately, RegisterHotkey only tells you when a key combination has been activated. Also, as you already realize, the KeyDown and KeyUp events you have will only work when your app has focus.

The only way you can get truly global KeyDown and KeyUp is by using a low level keyboard hook. Since I don't want to copy my entire answer I will simply link to it. The link will provide you some direction in setting up a keyboard hook.

How to disable/override Windows 10 Hotkeys with C#

Another possibility is to execute both commands on the hotkey activation like this...

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE
            Dim ID As String = m.WParam.ToString()
            Select Case ID
                Case 0 :
                    DF1Com1.Write("O:1/0", "1")
                    System.Threading.Thread.Sleep(2000)
                    DF1Com1.Write("O:1/0", "0")
                Case 1 : MessageBox.Show("S")
                Case 2 : MessageBox.Show("D")
                Case 3 : MessageBox.Show("F")
                Case 4 : MessageBox.Show("G")
                Case 5 : MessageBox.Show("H")
            End Select
        End If
        MyBase.WndProc(m)
    End Sub


问:
how to separated One column to two with cases
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

```<code> select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number
</code>```

答:
```<code>select a.[batch],a.[Doc_Type],
        isnull(CASE   WHEN a.[Doc_Type]='AA' THEN convert(real,a.Qty)  END,0) as [Soaking In] ,
        isnull(CASE  WHEN a.[Doc_Type]='BB' THEN convert(real,a.Qty) END ,0)as [Soaking Out]
FROM Transaction_Hdr a
</code>```

Body:
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

 select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number


问:
About the meaning of perl \w
according to the doc

\w        [3]  Match a "word" character (alphanumeric plus "_", plus
  other connector punctuation chars plus Unicode marks)

I don't understand what is "plus other connector punctuation chars plus Unicode marks", the doc seems doesn't say. What is \w really?

答:
There are 119,821 matching characters in Unicode 9.0.0 (included in Perl 5.26.0):

$ unichars -a -u '\w' | wc -l
119821
```

<p>You can use <code>unichars</code> to list the characters matching a property, and you can use <code>uniprops</code> to list the properties that match a character. Both are provided by Unicode::Tussle.</p>

<hr>

<p>perluniprops documents <code>\p</code>, and <code>\w</code> is short for <code>\p{XPosixWord}</code><sup>[1]</sup>, so this is the document one should consult to find out more about <code>\w</code> and other properties.</p>

<p>A sufficiently-recent perluniprops<sup>[2]</sup> documents that <code>\w</code> consists of the union of the following properties:</p>

<ul>
<li><code>XPosixWord</code>:

<ul>
<li><code>XPosixAlnum</code>: Alphabetic and decimal digits.

<ul>
<li><code>Alphabetic</code></li>
<li><code>Decimal_Number</code>: Decimal digits.</li>
</ul></li>
<li><code>Mark</code></li>
<li><code>Connector_Punctuation</code></li>
<li><code>Join_Control</code></li>
</ul></li>
</ul>

<p>Verification:</p>

<pre class="lang-none prettyprint-override"><code>$ diff -u \
   <( unichars -a -u '\w' ) \
   <( unichars -a -u '[\p{Alphabetic}\p{Decimal_Number}\p{Mark}\p{Connector_Punctuation}\p{Join_Control}]' ) \
      && echo "No difference."
No difference.
</code>```

In detail:

Custom derived property XPosixWord:

Custom derived property XPosixAlnum: Alphabetic and decimal digits.

Derived property Alphabetic:

Derived property Uppercase:

General category Uppercase_Letter (Lu)

Other_Uppercase[3]

Derived property Lowercase:

General category Lowercase_Letter (Ll)

Other_Lowercase[3]

General category Titlecase_Letter (Lt)

General category Modifier_Letter (Lm)

General category Other_Letter (Lo)

General category Letter_Number (Nl)

Other_Alphabetic[3]

General category Decimal_Number (Nd): Decimal digits.

General category Mark (M):

General category Spacing_Mark (Mc)

General category Enclosing_Mark (Me)

General category Nonspacing_Mark (Mn)

General category Connector_Punctuation (Pc)

Join_Control

When using /u or use feature qw( unicode_strings );.

5.28 will be the first version that documents XPosixWord correctly (since Join_Control characters were added to it in 5.18).

Not exposed by Perl.

Title: About the meaning of perl \w

Body:
There are 119,821 matching characters in Unicode 9.0.0 (included in Perl 5.26.0):

$ unichars -a -u '\w' | wc -l
119821

You can use unichars to list the characters matching a property, and you can use uniprops to list the properties that match a character. Both are provided by Unicode::Tussle.

perluniprops documents \p, and \w is short for \p{XPosixWord}[1], so this is the document one should consult to find out more about \w and other properties.

A sufficiently-recent perluniprops[2] documents that \w consists of the union of the following properties:

XPosixWord:

XPosixAlnum: Alphabetic and decimal digits.

Alphabetic

Decimal_Number: Decimal digits.

Mark

Connector_Punctuation

Join_Control

Verification:

$ diff -u \
   <( unichars -a -u '\w' ) \
   <( unichars -a -u '[\p{Alphabetic}\p{Decimal_Number}\p{Mark}\p{Connector_Punctuation}\p{Join_Control}]' ) \
      && echo "No difference."
No difference.

In detail:

Custom derived property XPosixWord:

Custom derived property XPosixAlnum: Alphabetic and decimal digits.

Derived property Alphabetic:

Derived property Uppercase:

General category Uppercase_Letter (Lu)

Other_Uppercase[3]

Derived property Lowercase:

General category Lowercase_Letter (Ll)

Other_Lowercase[3]

General category Titlecase_Letter (Lt)

General category Modifier_Letter (Lm)

General category Other_Letter (Lo)

General category Letter_Number (Nl)

Other_Alphabetic[3]

General category Decimal_Number (Nd): Decimal digits.

General category Mark (M):

General category Spacing_Mark (Mc)

General category Enclosing_Mark (Me)

General category Nonspacing_Mark (Mn)

General category Connector_Punctuation (Pc)

Join_Control

When using /u or use feature qw( unicode_strings );.

5.28 will be the first version that documents XPosixWord correctly (since Join_Control characters were added to it in 5.18).

Not exposed by Perl.


问:
If a user inputs an invalid character how can I get my program to output a message to the user?
If the user enters the wrong character such as "E" or "A" in my program how can I output a message to the user? The line which I'm speaking about in my program is when the user has to choose to input one out of three characters P, M or D. However, if the user inputs another character which isn't listed I want the program to display a message.

As you can see if the user inputs "E" the program skips to the next step. However, I want the user to be notified and asked again to enter the correct value which is "P, M or D".

In order to do what I'm trying to achieve I believe I need to do an if statement so here what I have tried.

```<code>if((i = P,M,D) && (i < ?)) {
   System.out.println("ERROR, please input only P,M or D.");
}
</code>```

Screenshot of the program

JAVA CODE

```<code>String grade;
int yr2cred[] = new int[18];
char yr2grade[] = new char[18];
for (int i = 1; i <= 18; i++) {
    System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
    grade = userinput.next();
    yr2grade[i - 1] = grade.charAt(0);
    if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
        yr2cred[i - 1] = yr2cred[i - 1] + P;
    }
    if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
        yr2cred[i - 1] = yr2cred[i - 1] + M;
    }
    if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
        yr2cred[i - 1] = yr2cred[i - 1] + D;
    }
}
</code>```

答:
Possible code is here. We iterate on units, for each unit we ask to enter the grade value until valid one will be entered. At the end the list of grades is printed.</p>

```<code>import java.util.Arrays;
import java.util.Scanner;

public class CheckInput {
    public static void main(String[] args) {

        int unitsCount = 18;
        String[] unitGrades = new String[unitsCount];

        String grade;

        Scanner userInput = new Scanner(System.in);

        for (int i = 0; i < unitsCount; i++) {
            grade = "";
            while ( ! (grade.equalsIgnoreCase("P") || grade.equalsIgnoreCase("M") || grade.equalsIgnoreCase("D") ) ) {
                if (!"".equals(grade)){
                    System.out.println("ERROR, please input only P,M or D.");
                }
                System.out.print("Please enter your grade for unit " + i + ": ");
                grade = userInput.next();
            }
            unitGrades[i] = grade;
        }
        System.out.println("Unit grades: "+Arrays.toString(unitGrades));
    }
}
</code>```

Body:
If the user enters the wrong character such as "E" or "A" in my program how can I output a message to the user? The line which I'm speaking about in my program is when the user has to choose to input one out of three characters P, M or D. However, if the user inputs another character which isn't listed I want the program to display a message.

As you can see if the user inputs "E" the program skips to the next step. However, I want the user to be notified and asked again to enter the correct value which is "P, M or D".

In order to do what I'm trying to achieve I believe I need to do an if statement so here what I have tried.

if((i = P,M,D) && (i < ?)) {
   System.out.println("ERROR, please input only P,M or D.");
}

Screenshot of the program

JAVA CODE

String grade;
int yr2cred[] = new int[18];
char yr2grade[] = new char[18];
for (int i = 1; i <= 18; i++) {
    System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
    grade = userinput.next();
    yr2grade[i - 1] = grade.charAt(0);
    if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
        yr2cred[i - 1] = yr2cred[i - 1] + P;
    }
    if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
        yr2cred[i - 1] = yr2cred[i - 1] + M;
    }
    if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
        yr2cred[i - 1] = yr2cred[i - 1] + D;
    }
}

Body:
Possible code is here. We iterate on units, for each unit we ask to enter the grade value until valid one will be entered. At the end the list of grades is printed.

import java.util.Arrays;
import java.util.Scanner;

public class CheckInput {
    public static void main(String[] args) {

        int unitsCount = 18;
        String[] unitGrades = new String[unitsCount];

        String grade;

        Scanner userInput = new Scanner(System.in);

        for (int i = 0; i < unitsCount; i++) {
            grade = "";
            while ( ! (grade.equalsIgnoreCase("P") || grade.equalsIgnoreCase("M") || grade.equalsIgnoreCase("D") ) ) {
                if (!"".equals(grade)){
                    System.out.println("ERROR, please input only P,M or D.");
                }
                System.out.print("Please enter your grade for unit " + i + ": ");
                grade = userInput.next();
            }
            unitGrades[i] = grade;
        }
        System.out.println("Unit grades: "+Arrays.toString(unitGrades));
    }
}


问:
JavaScript - Determine how a user arrived at html page
I'm building a web application and for one of my pages, I need to determine how a user arrived at the page (i.e. by redirect or by directly typing in the URL).

Is this possible with vanilla JavaScript?

答:
document.referrer.

You can also read Referer header on your backend server, because browser automatically includes it.