问:
tips for implementing AsyncTask
Hi all i've an app that places a circle on a bitmapa and with a slidebar alters the rgb values of the pixels within the circle. i'd like to use asynctask to speed up the process of altering the pixels. i'm not sure where to start. i've commented out some code at the bottom of the activity file as this is my first attept at it:). could anyone point me in the correct direction in how to implement this. The activity invokes a custom view(touchview), as i understand the asynctask must be instantiated on the UI thread. i'm thinking of initializing the slidebar ect in onPreExecute(), but not sure how to put all the worker stuff in doInBackground(). Any help will be appreciated, thanks Matt.

```<code>public class Jjilapp extends Activity {

    private Button b1;

    private static final String TAG = "*********jjil";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "***********inside oncreate about to set contentview = ");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.touchview);
        final TouchView touchView = (TouchView)findViewById(R.id.touchview);
        final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

        touchView.initSlider(slider);

        b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClickButton1");

            }
        });

    }//end of oncreate

   /* private class UpdateCirclePixels extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected void onPreExecute(){
            final TouchView touchView = (TouchView)findViewById(R.id.touchview);
            final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

            touchView.initSlider(slider);

        }

        @Override
        protected Integer doInBackground(Integer... arg0) {
            // TODO Auto-generated method stub

            publishProgress(progress);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress){

        }

    }//end of AsyncTask     */

}//end of jjilapp
</code>```

.

```<code>public class TouchView extends View{

    private File tempFile;
    private byte[] imageArray;
    private Bitmap bgr;
    private Bitmap bm;
    private Paint pTouch;
    private int centreX = 1;
    private int centreY = 1;
    private int radius = 50;
    private int Progress;
    private static final String TAG = "*********TouchView";

    public TouchView(Context context) {
        super(context);
       // TouchView(context, null);
    }

    public TouchView(Context context, AttributeSet attr) {
        super(context,attr);

        tempFile = new File(Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/"+"image.jpg");

        imageArray = new byte[(int)tempFile.length()];

     try{

            InputStream is = new FileInputStream(tempFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            int i = 0;

            while (dis.available() > 0) {
            imageArray[i] = dis.readByte();
            i++;
            }

            dis.close();

       } catch (Exception e) {

               e.printStackTrace();
            }

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inSampleSize = 1;

        bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
        bgr = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
        bgr = bm.copy(bm.getConfig(), true);

        pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
        pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
        pTouch.setColor(Color.TRANSPARENT);
        pTouch.setStyle(Paint.Style.STROKE);

        //pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));

    }// end of touchView constructor

    public void findCirclePixels(){

        for (int i=centreX-50; i < centreX+50; ++i) {
            for (int y=centreY-50; y <centreY+50 ; ++y) {

    if( Math.sqrt( Math.pow(i - centreX, 2) + ( Math.pow(y - centreY, 2) ) ) <= radius ){

                    bgr.setPixel(i,y,Color.rgb(Progress+50,Progress,Progress+100));
                }
            }
        }

        }// end of changePixel()

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN: {

                centreX = (int) ev.getX();
                centreY = (int) ev.getY();
                findCirclePixels();
                invalidate();

                break;
            }

            case MotionEvent.ACTION_MOVE: {

                    centreX = (int) ev.getX();
                    centreY = (int) ev.getY();
                    findCirclePixels();
                    invalidate();
                    break;

            }

            case MotionEvent.ACTION_UP:

                break;

        }
        return true;
    }//end of onTouchEvent

    public void initSlider(final HorizontalSlider slider)
    {
        Log.e(TAG, "******setting up slider*********** ");
        slider.setOnProgressChangeListener(changeListener);
    }

    private OnProgressChangeListener changeListener = new OnProgressChangeListener() {

        @Override
        public void onProgressChanged(View v, int progress) {
            // TODO Auto-generated method stub

            setProgress(progress);
            Log.e(TAG, "***********progress = "+Progress);

        }
    };

    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.drawBitmap(bgr, 0, 0, null);
        canvas.drawCircle(centreX, centreY, radius,pTouch);

    }//end of onDraw

    protected void setProgress(int progress2) {
        this.Progress = progress2;
        findCirclePixels();
        invalidate();

    }

}
</code>```

答:
As an alternative to runOnUiThread, you can use an AsyncTask, and use the publishProgress/onProgressUpdate mechanism to touch the Views. Google has a pretty good post about using AsyncTask, including which methods run in the task, and which ones run in the UI thread. Do your computations in doInBackground, and call publishProgress whenever there is some quanta of data to give to the UI to render. Then render that data in the onProgressUpdate function. Note that the parameters for both functions are quite arbitrary, and you can define them as you wish.

edit: Upon re-reading your question, I wonder if using a separate thread is the way to go, since you are taking input from the user as you are making your computations. It's possible that there could be a significant lag between the slider bar movement and the rendering, especially if the computation thread gets starved. If the computations are intense enough to warrant a separate thread, you may want to consider tossing up a progress bar during the computations, rather than confuse a user by having the rendering lag too far behind their movement of the slider bar. Either that, or you'll have to add in some logic to cancel the computation thread if a change is detected and the current render is incomplete, then fire it off again with the new parameters. For more information about cancelling AsyncTasks, read the introduction section(s) of the documentation for AsyncTask.

edit2: When I implemented my AsycTask, I defined an Object that contained all the elements I'd need: Views, Cursors, Exceptions, etc., and used that as a parameter for passing back and forth. I'm implying the same concept with TouchViewData, since the thread can't touch the View. Just pack it up with the data you need, and let the thread go crazy on it.

```<code>public class MyAsyncTask extends AsyncTask<TouchViewData, Object, void> {

    /*
     * These run on the UI thread, and can access the Views
     */
    protected void onProgressUpdate(Object... values) {
      // Here's where the magic happens!
      //   Update your views, open dialogs, Toast the user, whatever!
    }

    protected void onPreExecute() {
      // Prep anything you need for the thread
    }

    protected void onPostExecute() {
      // Finalize any rendering or cleanup
    }

    protected void onCancelled() {
      // Got cancelled! Time to clean up
    }

    /*
     * This runs in a separate thread, and can not change the View at all
     */
    public void doInBackground(TouchViewData... params) {
      while(stillCalculating && ! isCancelled()) {
        // Do your calculations, then...
        publishProgress(...); // pass some data to the UI thread to render
      }
      return;
    }

}
</code>```

In your Activity:

```<code>MyAppTask calculator = new MyAppTask();
calculator.execute(touchViewInstanceData, someObject);

...

// if you need to:
calculator.cancel();
</code>```

Title: tips for implementing AsyncTask

Body:
Hi all i've an app that places a circle on a bitmapa and with a slidebar alters the rgb values of the pixels within the circle. i'd like to use asynctask to speed up the process of altering the pixels. i'm not sure where to start. i've commented out some code at the bottom of the activity file as this is my first attept at it:). could anyone point me in the correct direction in how to implement this. The activity invokes a custom view(touchview), as i understand the asynctask must be instantiated on the UI thread. i'm thinking of initializing the slidebar ect in onPreExecute(), but not sure how to put all the worker stuff in doInBackground(). Any help will be appreciated, thanks Matt.

public class Jjilapp extends Activity {

    private Button b1;

    private static final String TAG = "*********jjil";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "***********inside oncreate about to set contentview = ");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.touchview);
        final TouchView touchView = (TouchView)findViewById(R.id.touchview);
        final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

        touchView.initSlider(slider);

        b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClickButton1");

            }
        });

    }//end of oncreate

   /* private class UpdateCirclePixels extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected void onPreExecute(){
            final TouchView touchView = (TouchView)findViewById(R.id.touchview);
            final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

            touchView.initSlider(slider);

        }

        @Override
        protected Integer doInBackground(Integer... arg0) {
            // TODO Auto-generated method stub

            publishProgress(progress);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress){

        }

    }//end of AsyncTask     */

}//end of jjilapp

.

public class TouchView extends View{

    private File tempFile;
    private byte[] imageArray;
    private Bitmap bgr;
    private Bitmap bm;
    private Paint pTouch;
    private int centreX = 1;
    private int centreY = 1;
    private int radius = 50;
    private int Progress;
    private static final String TAG = "*********TouchView";

    public TouchView(Context context) {
        super(context);
       // TouchView(context, null);
    }

    public TouchView(Context context, AttributeSet attr) {
        super(context,attr);

        tempFile = new File(Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/"+"image.jpg");

        imageArray = new byte[(int)tempFile.length()];

     try{

            InputStream is = new FileInputStream(tempFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            int i = 0;

            while (dis.available() > 0) {
            imageArray[i] = dis.readByte();
            i++;
            }

            dis.close();

       } catch (Exception e) {

               e.printStackTrace();
            }

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inSampleSize = 1;

        bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
        bgr = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
        bgr = bm.copy(bm.getConfig(), true);

        pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
        pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
        pTouch.setColor(Color.TRANSPARENT);
        pTouch.setStyle(Paint.Style.STROKE);

        //pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));

    }// end of touchView constructor

    public void findCirclePixels(){

        for (int i=centreX-50; i < centreX+50; ++i) {
            for (int y=centreY-50; y <centreY+50 ; ++y) {

    if( Math.sqrt( Math.pow(i - centreX, 2) + ( Math.pow(y - centreY, 2) ) ) <= radius ){

                    bgr.setPixel(i,y,Color.rgb(Progress+50,Progress,Progress+100));
                }
            }
        }

        }// end of changePixel()

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN: {

                centreX = (int) ev.getX();
                centreY = (int) ev.getY();
                findCirclePixels();
                invalidate();

                break;
            }

            case MotionEvent.ACTION_MOVE: {

                    centreX = (int) ev.getX();
                    centreY = (int) ev.getY();
                    findCirclePixels();
                    invalidate();
                    break;

            }

            case MotionEvent.ACTION_UP:

                break;

        }
        return true;
    }//end of onTouchEvent

    public void initSlider(final HorizontalSlider slider)
    {
        Log.e(TAG, "******setting up slider*********** ");
        slider.setOnProgressChangeListener(changeListener);
    }

    private OnProgressChangeListener changeListener = new OnProgressChangeListener() {

        @Override
        public void onProgressChanged(View v, int progress) {
            // TODO Auto-generated method stub

            setProgress(progress);
            Log.e(TAG, "***********progress = "+Progress);

        }
    };

    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.drawBitmap(bgr, 0, 0, null);
        canvas.drawCircle(centreX, centreY, radius,pTouch);

    }//end of onDraw

    protected void setProgress(int progress2) {
        this.Progress = progress2;
        findCirclePixels();
        invalidate();

    }

}

Body:
As an alternative to runOnUiThread, you can use an AsyncTask, and use the publishProgress/onProgressUpdate mechanism to touch the Views. Google has a pretty good post about using AsyncTask, including which methods run in the task, and which ones run in the UI thread. Do your computations in doInBackground, and call publishProgress whenever there is some quanta of data to give to the UI to render. Then render that data in the onProgressUpdate function. Note that the parameters for both functions are quite arbitrary, and you can define them as you wish.

edit: Upon re-reading your question, I wonder if using a separate thread is the way to go, since you are taking input from the user as you are making your computations. It's possible that there could be a significant lag between the slider bar movement and the rendering, especially if the computation thread gets starved. If the computations are intense enough to warrant a separate thread, you may want to consider tossing up a progress bar during the computations, rather than confuse a user by having the rendering lag too far behind their movement of the slider bar. Either that, or you'll have to add in some logic to cancel the computation thread if a change is detected and the current render is incomplete, then fire it off again with the new parameters. For more information about cancelling AsyncTasks, read the introduction section(s) of the documentation for AsyncTask.

edit2: When I implemented my AsycTask, I defined an Object that contained all the elements I'd need: Views, Cursors, Exceptions, etc., and used that as a parameter for passing back and forth. I'm implying the same concept with TouchViewData, since the thread can't touch the View. Just pack it up with the data you need, and let the thread go crazy on it.

public class MyAsyncTask extends AsyncTask<TouchViewData, Object, void> {

    /*
     * These run on the UI thread, and can access the Views
     */
    protected void onProgressUpdate(Object... values) {
      // Here's where the magic happens!
      //   Update your views, open dialogs, Toast the user, whatever!
    }

    protected void onPreExecute() {
      // Prep anything you need for the thread
    }

    protected void onPostExecute() {
      // Finalize any rendering or cleanup
    }

    protected void onCancelled() {
      // Got cancelled! Time to clean up
    }

    /*
     * This runs in a separate thread, and can not change the View at all
     */
    public void doInBackground(TouchViewData... params) {
      while(stillCalculating && ! isCancelled()) {
        // Do your calculations, then...
        publishProgress(...); // pass some data to the UI thread to render
      }
      return;
    }

}

In your Activity:

MyAppTask calculator = new MyAppTask();
calculator.execute(touchViewInstanceData, someObject);

...

// if you need to:
calculator.cancel();


来源: stackexchange

问:
When are beans created and are same beans used in different beans?
The question is a little bit confusing, but there are two parts only :

In a Spring web application, when are the beans configured in its
XML files instantiated ?

When we use ref to configure a bean
as a property of the "outer" bean, is a new bean "object" created?
or it uses the already present bean object (maybe created by some
other ref or <bean>) ?

答:
Ans 1 : In applicationContext.xml(IoC Container), the beans are configured and instantiated at the same time and they are singleton in nature.

Example :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- Spring Application Context File -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Custom bean -->
    <bean id="demo" class="com.example.Demo" />
</beans>
</code>```

Ans 2 : When you use ref, it uses the already present bean configured in the applicationContext.xml.

Example :

```<code><bean id="demo" class="com.example.Demo" />

<bean id="demo_2" class="com.example.Demo_2" >
    <property name="demo" ref="demo">
</bean>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ans 1 : In applicationContext.xml(IoC Container), the beans are configured and instantiated at the same time and they are singleton in nature.

Example :

<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring Application Context File -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Custom bean -->
    <bean id="demo" class="com.example.Demo" />
</beans>

Ans 2 : When you use ref, it uses the already present bean configured in the applicationContext.xml.

Example :

<bean id="demo" class="com.example.Demo" />

<bean id="demo_2" class="com.example.Demo_2" >
    <property name="demo" ref="demo">
</bean>


问:
Flutter : Could not find the correct Provider
I am tying to implement Firebase Authentication in my flutter app, with the help of provider. First, I am checking whether the user is already signed in, if yes, i AM sending him to the home screen. Else I am sending him to the Login screen.

Please check my code below.

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:customer/services/auth.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
        return ChangeNotifierProvider(
            child: MaterialApp(
                title: 'Customer App',

                home: AuthWrapper(),
                routes: {
                    '/account': (context) => AccountPage(),
                },
            ), create: (BuildContext context) {
                AuthService();
            },
        );
    }
}
</code>```

auth.dart

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthService with ChangeNotifier{

  final FirebaseAuth _auth = FirebaseAuth.instance;
  FirebaseUser _user=null;

//Sign in with username and password
  Future signInWithEmail(String email, String password) async {
    FirebaseUser user;

    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
          user = result.user;

      if (user != null) {
        print("Sign in success: " + user.email);
        _user = user;
      } else {
        print("sign in failed");
        _user = null;
      }
    } catch (e) {
      print(e.toString());
    }
    finally{
      notifyListeners();
    }
  }

//Get the current user
  FirebaseUser getCurrentUser()  {
    return _user;
  }

}
</code>```

auth_wrapper.dart

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:customer/pages/home.dart';
import 'package:customer/pages/login.dart';
import 'package:customer/services/auth.dart';
import 'package:provider/provider.dart';

class AuthWrapper extends StatelessWidget {
  AuthWrapper() {}

  @override
  Widget build(BuildContext context) {
    var currentUser =Provider.of<AuthService>(context, listen: false).getCurrentUser();

    if (currentUser == null) {
      return LoginPage();
    } else {
      return HomePage();
    }
  }
}
</code>```

Unfortunately, when I run this app, i get the following error.

```<code>I/flutter ( 3364): The following ProviderNotFoundException was thrown building AuthWrapper(dirty):
I/flutter ( 3364): Error: Could not find the correct Provider<AuthService> above this AuthWrapper Widget
I/flutter ( 3364):
I/flutter ( 3364): To fix, please:
I/flutter ( 3364):
I/flutter ( 3364):   * Ensure the Provider<AuthService> is an ancestor to this AuthWrapper Widget
I/flutter ( 3364):   * Provide types to Provider<AuthService>
I/flutter ( 3364):   * Provide types to Consumer<AuthService>
I/flutter ( 3364):   * Provide types to Provider.of<AuthService>()
I/flutter ( 3364):   * Ensure the correct `context` is being used.
I/flutter ( 3364):
I/flutter ( 3364): If none of these solutions work, please file a bug at:
I/flutter ( 3364): https://github.com/rrousselGit/provider/issues
I/flutter ( 3364):
I/flutter ( 3364): The relevant error-causing widget was:
[38;5;248mI/flutter ( 3364):   AuthWrapper[39;49m
I/flutter ( 3364):
I/flutter ( 3364): When the exception was thrown, this was the stack:
[38;5;248mI/flutter ( 3364): #0      Provider.of[39;49m
[38;5;248mI/flutter ( 3364): #1      AuthWrapper.build[39;49m
[38;5;244mI/flutter ( 3364): #2      StatelessElement.build[39;49m
[38;5;244mI/flutter ( 3364): #3      ComponentElement.performRebuild[39;49m
[38;5;244mI/flutter ( 3364): #4      Element.rebuild[39;49m
[38;5;244mI/flutter ( 3364): #5      ComponentElement._firstBuild[39;49m
[38;5;244mI/flutter ( 3364): #6      ComponentElement.mount[39;49m
[38;5;244mI/flutter ( 3364): #7      Element.inflateWidget[39;49m
[38;5;244mI/flutter ( 3364): #8      Element.updateChild[39;49m
[38;5;244mI/flutter ( 3364): #9      SingleChildRenderObjectElement.mount[3
</code>```

I am newly trying out the provider patter, whats really going on here?

I also has a second question. Well, provider is a pattern. But in flutter we know things get little out of context so, does that mean all business logic (REST API Related) need to take place in provider ? Or else, only use in places where you need the observer pattern behaviour?

答:
I think value provider could be best solution for your case. Following minimal code help you to understand more.

I think it is totally dependent on you, if you think data is not that much big then you can avoid using provider because it create lot’s of other boilerplate code. However i also suggest you to use flutter_bloc package.

```<code>void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        home: FireBaseWrapper(),
      ),
    );
  }
}

class FireBaseWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _user = Provider.of<User>(context);
    print(_user);
    if (_user != null)
      return FireBase();
    else
      return Register();
  }
}

    class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  User firebaseUserToUser(FirebaseUser _user) {
    return _user != null ? User(userId: _user.uid) : null;
  }

  //stream of User
  Stream<User> get user {
    return _auth.onAuthStateChanged.map(firebaseUserToUser);
  }

  // firebase sign in Anonymously
  Future signInAnonymously() async {
    try {
      AuthResult _authResult = await _auth.signInAnonymously();
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  Future signInWithIdPassword({String email, String password}) async {
    try {
      AuthResult _authResult = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  Future signUpWithIdPassword({String email, String password}) async {
    try {
      AuthResult _authResult = await _auth.createUserWithEmailAndPassword(
          email: email.trim(), password: password);
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      return null;
    }
  }
}
</code>```

Body:
I am tying to implement Firebase Authentication in my flutter app, with the help of provider. First, I am checking whether the user is already signed in, if yes, i AM sending him to the home screen. Else I am sending him to the Login screen.

Please check my code below.

main.dart

import 'package:flutter/material.dart';
import 'package:customer/services/auth.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
        return ChangeNotifierProvider(
            child: MaterialApp(
                title: 'Customer App',

                home: AuthWrapper(),
                routes: {
                    '/account': (context) => AccountPage(),
                },
            ), create: (BuildContext context) {
                AuthService();
            },
        );
    }
}

auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthService with ChangeNotifier{

  final FirebaseAuth _auth = FirebaseAuth.instance;
  FirebaseUser _user=null;

//Sign in with username and password
  Future signInWithEmail(String email, String password) async {
    FirebaseUser user;

    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
          user = result.user;

      if (user != null) {
        print("Sign in success: " + user.email);
        _user = user;
      } else {
        print("sign in failed");
        _user = null;
      }
    } catch (e) {
      print(e.toString());
    }
    finally{
      notifyListeners();
    }
  }

//Get the current user
  FirebaseUser getCurrentUser()  {
    return _user;
  }

}

auth_wrapper.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:customer/pages/home.dart';
import 'package:customer/pages/login.dart';
import 'package:customer/services/auth.dart';
import 'package:provider/provider.dart';

class AuthWrapper extends StatelessWidget {
  AuthWrapper() {}

  @override
  Widget build(BuildContext context) {
    var currentUser =Provider.of<AuthService>(context, listen: false).getCurrentUser();

    if (currentUser == null) {
      return LoginPage();
    } else {
      return HomePage();
    }
  }
}

Unfortunately, when I run this app, i get the following error.

I/flutter ( 3364): The following ProviderNotFoundException was thrown building AuthWrapper(dirty):
I/flutter ( 3364): Error: Could not find the correct Provider<AuthService> above this AuthWrapper Widget
I/flutter ( 3364):
I/flutter ( 3364): To fix, please:
I/flutter ( 3364):
I/flutter ( 3364):   * Ensure the Provider<AuthService> is an ancestor to this AuthWrapper Widget
I/flutter ( 3364):   * Provide types to Provider<AuthService>
I/flutter ( 3364):   * Provide types to Consumer<AuthService>
I/flutter ( 3364):   * Provide types to Provider.of<AuthService>()
I/flutter ( 3364):   * Ensure the correct `context` is being used.
I/flutter ( 3364):
I/flutter ( 3364): If none of these solutions work, please file a bug at:
I/flutter ( 3364): https://github.com/rrousselGit/provider/issues
I/flutter ( 3364):
I/flutter ( 3364): The relevant error-causing widget was:
[38;5;248mI/flutter ( 3364):   AuthWrapper[39;49m
I/flutter ( 3364):
I/flutter ( 3364): When the exception was thrown, this was the stack:
[38;5;248mI/flutter ( 3364): #0      Provider.of[39;49m
[38;5;248mI/flutter ( 3364): #1      AuthWrapper.build[39;49m
[38;5;244mI/flutter ( 3364): #2      StatelessElement.build[39;49m
[38;5;244mI/flutter ( 3364): #3      ComponentElement.performRebuild[39;49m
[38;5;244mI/flutter ( 3364): #4      Element.rebuild[39;49m
[38;5;244mI/flutter ( 3364): #5      ComponentElement._firstBuild[39;49m
[38;5;244mI/flutter ( 3364): #6      ComponentElement.mount[39;49m
[38;5;244mI/flutter ( 3364): #7      Element.inflateWidget[39;49m
[38;5;244mI/flutter ( 3364): #8      Element.updateChild[39;49m
[38;5;244mI/flutter ( 3364): #9      SingleChildRenderObjectElement.mount[3

I am newly trying out the provider patter, whats really going on here?

I also has a second question. Well, provider is a pattern. But in flutter we know things get little out of context so, does that mean all business logic (REST API Related) need to take place in provider ? Or else, only use in places where you need the observer pattern behaviour?

Body:
I think value provider could be best solution for your case. Following minimal code help you to understand more.

I think it is totally dependent on you, if you think data is not that much big then you can avoid using provider because it create lot’s of other boilerplate code. However i also suggest you to use flutter_bloc package.

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        home: FireBaseWrapper(),
      ),
    );
  }
}

class FireBaseWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _user = Provider.of<User>(context);
    print(_user);
    if (_user != null)
      return FireBase();
    else
      return Register();
  }
}

    class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  User firebaseUserToUser(FirebaseUser _user) {
    return _user != null ? User(userId: _user.uid) : null;
  }

  //stream of User
  Stream<User> get user {
    return _auth.onAuthStateChanged.map(firebaseUserToUser);
  }

  // firebase sign in Anonymously
  Future signInAnonymously() async {
    try {
      AuthResult _authResult = await _auth.signInAnonymously();
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  Future signInWithIdPassword({String email, String password}) async {
    try {
      AuthResult _authResult = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  Future signUpWithIdPassword({String email, String password}) async {
    try {
      AuthResult _authResult = await _auth.createUserWithEmailAndPassword(
          email: email.trim(), password: password);
      FirebaseUser _user = _authResult.user;
      return firebaseUserToUser(_user);
    } catch (e) {
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      return null;
    }
  }
}


问:
How to execute multiple commands in the while loop condition?
I want to create a directory with increasing numbers every time I run the script. My current solution is:

```<code>COUNTER=1
while mkdir $COUNTER; (( $? != 0 ))
do
     COUNTER=$((COUNTER + 1))
done
</code>```

Is separating the commands in the while condition with a ;(semicolon) the best practice?

答:
You don't need to test the exit status, just check if the directory exists already and increment. Here is one way

```<code>#!/usr/bin/env bash

counter=1
while [[ -e $counter ]]; do
  ((counter++))
done

if ! mkdir "$counter"; then  ##: mkdir failed
  echo failed                ##: execute this code
fi
</code>```

POSIX sh shell.

```<code>#!/usr/bin/env sh

counter=1
while [ -e "$counter" ]; do
  counter=$((counter+1))
done

if ! mkdir "$counter"; then  ##: If mkdir failed
  echo failed                ##: Execute this code
fi
</code>```

The bang ! negates the exit status of mkdir.

See help test | grep '^[[:blank:]]*!'

Well if you're just going to negate the exit status of mkdir inside the while loop then you might as well use until, which is the opposite of while

```<code>counter=1
until mkdir "$COUNTER"; do
  :
  COUNTER=$((COUNTER + 1))
done
</code>```

Body:
I want to create a directory with increasing numbers every time I run the script. My current solution is:

COUNTER=1
while mkdir $COUNTER; (( $? != 0 ))
do
     COUNTER=$((COUNTER + 1))
done

Is separating the commands in the while condition with a ;(semicolon) the best practice?

Body:
You don't need to test the exit status, just check if the directory exists already and increment. Here is one way

#!/usr/bin/env bash

counter=1
while [[ -e $counter ]]; do
  ((counter++))
done

if ! mkdir "$counter"; then  ##: mkdir failed
  echo failed                ##: execute this code
fi

POSIX sh shell.

#!/usr/bin/env sh

counter=1
while [ -e "$counter" ]; do
  counter=$((counter+1))
done

if ! mkdir "$counter"; then  ##: If mkdir failed
  echo failed                ##: Execute this code
fi

The bang ! negates the exit status of mkdir.

See help test | grep '^[[:blank:]]*!'

Well if you're just going to negate the exit status of mkdir inside the while loop then you might as well use until, which is the opposite of while

counter=1
until mkdir "$COUNTER"; do
  :
  COUNTER=$((COUNTER + 1))
done


问:
Function returning the following days and months in python3
I am writing a webscraper and the URL is based on the dates:

```<code>checkin_month=2&checkin_monthday=21&checkin_year=2020&checkout_month=2&checkout_monthday=22
</code>```

There are 4 variables: checkin day and month, and checkout day and month. Checkout day will be always be = checkin day + 1. But when the newmonth is ending, checkout day is 1 and checkout month = checkin month +1.
Is there any function or library I can use to somehow implement it or do I have to write my own code to solve this?

答:
You can use:
from datetime import timedelta

then :

```<code>yourDate += timedelta(days=1)
</code>```

This previous code increments your date by one day. But, to increment the date, your date must be of type datetime.

Below, the documentation of thhis class.
    class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

You can see a tutorial to manipulate date here : https://www.dataquest.io/blog/python-datetime-tutorial/

Body:
I am writing a webscraper and the URL is based on the dates:

checkin_month=2&checkin_monthday=21&checkin_year=2020&checkout_month=2&checkout_monthday=22

There are 4 variables: checkin day and month, and checkout day and month. Checkout day will be always be = checkin day + 1. But when the newmonth is ending, checkout day is 1 and checkout month = checkin month +1.
Is there any function or library I can use to somehow implement it or do I have to write my own code to solve this?

Body:
You can use:
from datetime import timedelta

then :

yourDate += timedelta(days=1)

This previous code increments your date by one day. But, to increment the date, your date must be of type datetime.

Below, the documentation of thhis class.
    class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

You can see a tutorial to manipulate date here : https://www.dataquest.io/blog/python-datetime-tutorial/


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答: Where clause is not allowed in Insert query. Form your code I guess that you need to use Update query.</p>

ContentLicense: CC BY-SA 3.0

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}


问:
build.gradle.kts & multi-module-project: how to add other project so that transitive dependencies are available too
Having the following multi-module-setup:

```<code>multi
├── projA
│   └── build.gradle.kts
├── projB
│   └── build.gradle.kts
├── build.gradle.kts
└── settings.gradle.kts
</code>```

with the following content (abbreviated):

settings.gradle.kts

```<code>rootProject.name = "multi"
include("projA", "projB")
</code>```

projA\build.gradle.kts

```<code>dependencies {
    implementation("important-library:1.0")
}
</code>```

projB\build.gradle.kts

```<code>dependencies {
    implementation(project(":projA"))
}
</code>```

Why don't I have access to that importantlibrary:1.0 from projB?

What works: if I have a class within projA that uses the library, it works perfectly even if that class is called from a class within projB (so indirect access works). Directly accessing any class from importantlibrary:1.0 within projB doesn't work (unresolved reference).

What am I missing here? Or what needs to be set up so that it works?

Gradle version: 5.6.1

答:
I think a good way to achieve what you want would be to use api instead of implementation. implementation is meant to only keep the dependency inside the module, while api is meant to export them along with the module. The dependencies for projA would then become:

```<code>dependencies {
    api("important-library:1.0")
}
</code>```

This is the link to the official documentation: https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation

Body:
Having the following multi-module-setup:

multi
├── projA
│   └── build.gradle.kts
├── projB
│   └── build.gradle.kts
├── build.gradle.kts
└── settings.gradle.kts

with the following content (abbreviated):

settings.gradle.kts

rootProject.name = "multi"
include("projA", "projB")

projA\build.gradle.kts

dependencies {
    implementation("important-library:1.0")
}

projB\build.gradle.kts

dependencies {
    implementation(project(":projA"))
}

Why don't I have access to that importantlibrary:1.0 from projB?

What works: if I have a class within projA that uses the library, it works perfectly even if that class is called from a class within projB (so indirect access works). Directly accessing any class from importantlibrary:1.0 within projB doesn't work (unresolved reference).

What am I missing here? Or what needs to be set up so that it works?

Gradle version: 5.6.1

Body:
I think a good way to achieve what you want would be to use api instead of implementation. implementation is meant to only keep the dependency inside the module, while api is meant to export them along with the module. The dependencies for projA would then become:

dependencies {
    api("important-library:1.0")
}

This is the link to the official documentation: https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation


问:
Anyway to split files to diff folder?
I have over 100,000 files in a folder name: A, all are picture files either jpeg, or jpg extension with random file names, like abc.jpg, xcc.jpg, bbb.jpeg

Is there any way to move the all the 100k files to folder in the following structure:

Any order of the images don't matter, just need 5000 pic in each folder under B

```<code>Folder B -> Folder 1 (5000 of the jpg files)
            Folder 2 (next 5000 of the jpg files)
            .
            Folder n (last 5000 remaining of files)
</code>```

Batch files or powershell doesn't matter as long run in windows or cmd, I just can't think of any way to spilt files to 5000 per folder.

Any help is appreciated... Thanks

答:
Below code assume there are folders folder_a and folder_b. Your images are in folder_a and the code will move these images to folder_b\folder_1\..., folder_b\folder_2\..., folder_b\folder_3\... etc. Change these directory names based on your actual requirement. Run it in folder_a and it will do the work.

```<code>$split_at = 5000
# First, create the directories to store the images
$image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}

# Then move the images in batch to the destination directories
$folder_n = 1
while(Test-Path .\*) {
    Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
    $folder_n++
}
</code>```

Benchmarks

I benchmarked my code as well as Manuel Batsching's. It turns out that my code is faster. Below is the benchmarking code and the result. Here I created 2999 image files each round and move them from folder_a to folder_b (which is at the same level in the file system).

```<code>Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}

Measure-Command {
    $split_at = 43
    # First, create the directories to store the images
    $image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
    1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}

    # Then move the images in batch to the destination directories
    $folder_n = 1
    while(Test-Path .\*) {
        Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
        $folder_n++
    }
}

Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}

Measure-Command {
    $i = 1
    while (($files = Get-ChildItem *.jpg, *.jpeg).Count -gt 0)
    {
        $folderPath = "..\folder_b\folder_$($i)"
        New-Item -Type Directory $folderPath
        $files | Select-Object -First 43 | Move-Item -Destination $folderPath
        $i += 1
    }
}
</code>```

Result (My code):

```<code>Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 7
Milliseconds      : 632
Ticks             : 76323557
TotalDays         : 8.83374502314815E-05
TotalHours        : 0.00212009880555556
TotalMinutes      : 0.127205928333333
TotalSeconds      : 7.6323557
TotalMilliseconds : 7632.3557
</code>```

Result (Manuel Batsching):

```<code>Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 13
Milliseconds      : 961
Ticks             : 139616227
TotalDays         : 0.000161592855324074
TotalHours        : 0.00387822852777778
TotalMinutes      : 0.232693711666667
TotalSeconds      : 13.9616227
TotalMilliseconds : 13961.6227
</code>```

Title: Anyway to split files to diff folder?

Body:
I have over 100,000 files in a folder name: A, all are picture files either jpeg, or jpg extension with random file names, like abc.jpg, xcc.jpg, bbb.jpeg

Is there any way to move the all the 100k files to folder in the following structure:

Any order of the images don't matter, just need 5000 pic in each folder under B

Folder B -> Folder 1 (5000 of the jpg files)
            Folder 2 (next 5000 of the jpg files)
            .
            Folder n (last 5000 remaining of files)

Batch files or powershell doesn't matter as long run in windows or cmd, I just can't think of any way to spilt files to 5000 per folder.

Any help is appreciated... Thanks

Body:
Below code assume there are folders folder_a and folder_b. Your images are in folder_a and the code will move these images to folder_b\folder_1\..., folder_b\folder_2\..., folder_b\folder_3\... etc. Change these directory names based on your actual requirement. Run it in folder_a and it will do the work.

$split_at = 5000
# First, create the directories to store the images
$image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}

# Then move the images in batch to the destination directories
$folder_n = 1
while(Test-Path .\*) {
    Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
    $folder_n++
}

Benchmarks

I benchmarked my code as well as Manuel Batsching's. It turns out that my code is faster. Below is the benchmarking code and the result. Here I created 2999 image files each round and move them from folder_a to folder_b (which is at the same level in the file system).

Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}

Measure-Command {
    $split_at = 43
    # First, create the directories to store the images
    $image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
    1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}

    # Then move the images in batch to the destination directories
    $folder_n = 1
    while(Test-Path .\*) {
        Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
        $folder_n++
    }
}

Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}

Measure-Command {
    $i = 1
    while (($files = Get-ChildItem *.jpg, *.jpeg).Count -gt 0)
    {
        $folderPath = "..\folder_b\folder_$($i)"
        New-Item -Type Directory $folderPath
        $files | Select-Object -First 43 | Move-Item -Destination $folderPath
        $i += 1
    }
}

Result (My code):

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 7
Milliseconds      : 632
Ticks             : 76323557
TotalDays         : 8.83374502314815E-05
TotalHours        : 0.00212009880555556
TotalMinutes      : 0.127205928333333
TotalSeconds      : 7.6323557
TotalMilliseconds : 7632.3557

Result (Manuel Batsching):

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 13
Milliseconds      : 961
Ticks             : 139616227
TotalDays         : 0.000161592855324074
TotalHours        : 0.00387822852777778
TotalMinutes      : 0.232693711666667
TotalSeconds      : 13.9616227
TotalMilliseconds : 13961.6227


问:
Is it possible to merge a table in MSSQL with a view based on the same table?
Something like this

```<code>create view V1 as
select * from (T1 union T2) join T3 where "some condition on T3"

Then later in the process:
merge T2 using V1
when not matched by Target then insert
when not matched by Source then delete
</code>```

Is MS SQL server smart enough to handle this?

答:
It is possible to use a view (which references the target table) in a merge statement:</p>

```<code>create table t1
(
    id int,
    colA int
)
go

create table t2
(
    id int,
    colB int
)
go

create view dbo.testview
as
select id, colB
from t2
except
select id, colA
from t1
go

insert into t2(id, colB) values (1, 2)
go

--populate t1 with the values of t2 (that do not exist yet in t1)
merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then
insert(id, colA)
values(id, colB);
go
select *
from t2;
select *
from t1;
go

insert into t2(id, colB) values (1, 2)

merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then
insert(id, colA)
values(id, colB);
go

select *
from t2;
select *
from t1;
go

drop view testview;
drop table t1;
drop table t2;
go
</code>```

Body:
Something like this

create view V1 as
select * from (T1 union T2) join T3 where "some condition on T3"

Then later in the process:
merge T2 using V1
when not matched by Target then insert
when not matched by Source then delete

Is MS SQL server smart enough to handle this?

Body:
It is possible to use a view (which references the target table) in a merge statement:

create table t1
(
    id int,
    colA int
)
go

create table t2
(
    id int,
    colB int
)
go

create view dbo.testview
as
select id, colB
from t2
except
select id, colA
from t1
go

insert into t2(id, colB) values (1, 2)
go

--populate t1 with the values of t2 (that do not exist yet in t1)
merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then
insert(id, colA)
values(id, colB);
go
select *
from t2;
select *
from t1;
go

insert into t2(id, colB) values (1, 2)

merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then
insert(id, colA)
values(id, colB);
go

select *
from t2;
select *
from t1;
go

drop view testview;
drop table t1;
drop table t2;
go


问:
Merge two objects(optimizing)
I have n objects(with some nested structure). In the end, I'm expecting to get one merged object with all fields.

```<code>const result = {
  firstParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  secondParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  thirdParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      uuid1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  }
}

const newObj1 = {
  firstParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  secondParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  thirdParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  }
}

const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  })
  console.timeEnd("test merge")

  return result;
}

merge(result, newObj1);
</code>```

This solution gives me an expected result(I'm getting an obj2, obj3 ... objn and every iteration I'm merging it to result), but when I'm getting more than 500 or 1000 newObj it works pretty slow. Is there any way to optimize it?

答:
The problem is that you are always doing rest operations with ... here

```<code>const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  });
</code>```

Imagine an object of 10 000 elements destructured into elements and then another array created in its place. The larger the array, the more memory write will happen and the slower the code will get. Instead, you should create an array only once and then add elements into it, like:

```<code>const merge = (result, newObj) => {
  //we assume that result already of the format of:
  //{x: {/*...*/}, y: {/*...*/}, z: {/*...*/}}
  console.time("test merge");
  for (let outerKey in newObj) { //firstParam, secondParam, thirdParam
    for (let innerKey in newObj[outerKey]) { //x, y, z
      for (let valueKey in newObj[outerKey][innerKey]) {
        result[outerKey][innerKey][valueKey] = newObj[outerKey][innerKey][valueKey];
      }
    }
  }
};
</code>```

Title: Merge two objects(optimizing)

Body:
I have n objects(with some nested structure). In the end, I'm expecting to get one merged object with all fields.

const result = {
  firstParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  secondParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  },
  thirdParam: {
    x: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    y: {
      uuid1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    },
    z: {
      id1: ["somedata1", "somedata2"],
      id3: ["somedata1", "somedata2"],
    }
  }
}

const newObj1 = {
  firstParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  secondParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  },
  thirdParam: {
    x: {
      id2: ["somedata1", "somedata2"]
    },
    y: {
      id2: ["somedata1", "somedata2"]
    },
    z: {
      id2: ["somedata1", "somedata2"]
    }
  }
}

const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  })
  console.timeEnd("test merge")

  return result;
}

merge(result, newObj1);

This solution gives me an expected result(I'm getting an obj2, obj3 ... objn and every iteration I'm merging it to result), but when I'm getting more than 500 or 1000 newObj it works pretty slow. Is there any way to optimize it?

Body:
The problem is that you are always doing rest operations with ... here

const merge = (result, newObj) => {
  console.time("test merge")
  Object.keys(result).forEach(key => {
    result[key] = {
      x: {
        ...result[key].x,
        ...newObj[key].x
      },
      y: {
        ...result[key].y,
        ...newObj[key].y
      },
      z: {
        ...result[key].z,
        ...newObj[key].z
      }
    }
  });

Imagine an object of 10 000 elements destructured into elements and then another array created in its place. The larger the array, the more memory write will happen and the slower the code will get. Instead, you should create an array only once and then add elements into it, like:

const merge = (result, newObj) => {
  //we assume that result already of the format of:
  //{x: {/*...*/}, y: {/*...*/}, z: {/*...*/}}
  console.time("test merge");
  for (let outerKey in newObj) { //firstParam, secondParam, thirdParam
    for (let innerKey in newObj[outerKey]) { //x, y, z
      for (let valueKey in newObj[outerKey][innerKey]) {
        result[outerKey][innerKey][valueKey] = newObj[outerKey][innerKey][valueKey];
      }
    }
  }
};


问:
Notification is not displayed in notification drawer if app is in foreground
I am sending a notification into my app using Firebase cloud messaging and it's working fine. However, when I send a notification and if my app is in the foreground, the notification will not show in the notification tray. The notification only shows in the notification tray if my app is in the background. </p>

<p>Below is my code: </p>

```<code>public class Notifications extends FirebaseMessagingService {

    @ServerTimestamp
    Date time;
    private FirebaseFirestore mFirestore;
    private boolean isNotificationMatching = false;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        super.onMessageReceived(remoteMessage);

        mFirestore = FirebaseFirestore.getInstance();

        if (remoteMessage.getData() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                sendNotificationAPI26(remoteMessage);

            else
                sendNotification(remoteMessage);
        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {

        isNotificationMatching = false;
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_logo)
                .setContentText(description)
                .setAutoCancel(true)
                .setSound(defaultSoundUri);
        builder.setContentIntent(pendingIntent);

        NotificationManager noti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        noti.notify(new Random().nextInt(), builder.build());
    }

    private void postDataToFirebaseServer(Map<String, String> data) {

        Map<String, Object> postDataMap = new HashMap<>();
        postDataMap.put("title", data.get("title"));

        postDataMap.put("timestamp", FieldValue.serverTimestamp());

        mFirestore.collection("notifications").add(postDataMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
//                Toast.makeText(getA.this, "Success", Toast.LENGTH_SHORT);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                String error = e.getMessage();
//                Toast.makeText(Testing.this, "Failed", Toast.LENGTH_SHORT);
            }
        });

    }

    private void sendNotificationAPI26(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

        NotificationHelper helper;
        Notification.Builder builder;

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        helper = new NotificationHelper(this);
        builder = helper.getLootBoxNotification(title, defaultSoundUri);
        helper.getManager().notify(new Random().nextInt(), builder.build());
        builder.setContentIntent(pendingIntent);

    }
}
</code>```

答:
This is your code

```<code>NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_logo)
                .setContentText(description)
                .setAutoCancel(true)
                .setSound(defaultSoundUri);
        builder.setContentIntent(pendingIntent);
</code>```

Here you have set is as

```<code>setAutoCancel(true);
</code>```

This method will cancel all the notification while your app is in foreground.
Set it to false.

Body:
I am sending a notification into my app using Firebase cloud messaging and it's working fine. However, when I send a notification and if my app is in the foreground, the notification will not show in the notification tray. The notification only shows in the notification tray if my app is in the background.

Below is my code:

public class Notifications extends FirebaseMessagingService {

    @ServerTimestamp
    Date time;
    private FirebaseFirestore mFirestore;
    private boolean isNotificationMatching = false;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        super.onMessageReceived(remoteMessage);

        mFirestore = FirebaseFirestore.getInstance();

        if (remoteMessage.getData() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                sendNotificationAPI26(remoteMessage);

            else
                sendNotification(remoteMessage);
        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {

        isNotificationMatching = false;
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_logo)
                .setContentText(description)
                .setAutoCancel(true)
                .setSound(defaultSoundUri);
        builder.setContentIntent(pendingIntent);

        NotificationManager noti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        noti.notify(new Random().nextInt(), builder.build());
    }

    private void postDataToFirebaseServer(Map<String, String> data) {

        Map<String, Object> postDataMap = new HashMap<>();
        postDataMap.put("title", data.get("title"));

        postDataMap.put("timestamp", FieldValue.serverTimestamp());

        mFirestore.collection("notifications").add(postDataMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
//                Toast.makeText(getA.this, "Success", Toast.LENGTH_SHORT);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                String error = e.getMessage();
//                Toast.makeText(Testing.this, "Failed", Toast.LENGTH_SHORT);
            }
        });

    }

    private void sendNotificationAPI26(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

        NotificationHelper helper;
        Notification.Builder builder;

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        helper = new NotificationHelper(this);
        builder = helper.getLootBoxNotification(title, defaultSoundUri);
        helper.getManager().notify(new Random().nextInt(), builder.build());
        builder.setContentIntent(pendingIntent);

    }
}

Body:
This is your code

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_logo)
                .setContentText(description)
                .setAutoCancel(true)
                .setSound(defaultSoundUri);
        builder.setContentIntent(pendingIntent);

Here you have set is as

setAutoCancel(true);

This method will cancel all the notification while your app is in foreground.
Set it to false.


问:
Javascript regex to check if a value begins with a number followed by anything else
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

```<code>var validaddress = /^[0-9][A-Za-z0-9]+$/;
</code>```

But this isn't the right way. Im new to this, help anyone?

答:
I would get rid of the $.  Also, a '.' would suffice for "any character".  This one works for me:</p>

```<code>var validaddress = ^[0-9].+;
</code>```

Body:
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

var validaddress = /^[0-9][A-Za-z0-9]+$/;

But this isn't the right way. Im new to this, help anyone?

Body:
I would get rid of the $.  Also, a '.' would suffice for "any character".  This one works for me:

var validaddress = ^[0-9].+;


问:
how is flatMap working with custom monads
I am new in scala and confused with Monads' implementation. In the below program when "a <- g(3)" is executed the value of 'a' is 23 and not Writer, why? what is happening behind the scene?</p>

```<code>case class Writer(value:Int, log:String) {
  def map(f:Int=>Int): Writer = {
    Writer(f(value), log)
  }
  def flatMap(f:Int=>Writer): Writer = {
    val temp = f(value)
    Writer(temp.value, log+"...."+temp.log)
  }
}

object Test extends App {

  def f(value: Int):Writer = {
    Writer(40+value, s"f has $value")
  }

  def g(value: Int):Writer = {
    Writer(20+value, s"g has $value")
  }

  val result1 = for {
    a <- g(3)
    b <- f(a)
  } yield b

  println(result1)

  val result2 = g(3) flatMap {
    a => f(a).map(b=>b)
  }

  println(result2)
}
</code>```

答:
There's a generic interface for monads provided by cats library:

https://typelevel.org/cats/typeclasses/monad.html

In this doc page you can find how to efficiently and correctly create your own monad.
Besides, cats feature their own Writer monad, example usage:

https://medium.com/@spearsear/simple-use-of-cats-writer-monad-4a1694556112

Body:
I am new in scala and confused with Monads' implementation. In the below program when "a <- g(3)" is executed the value of 'a' is 23 and not Writer, why? what is happening behind the scene?

case class Writer(value:Int, log:String) {
  def map(f:Int=>Int): Writer = {
    Writer(f(value), log)
  }
  def flatMap(f:Int=>Writer): Writer = {
    val temp = f(value)
    Writer(temp.value, log+"...."+temp.log)
  }
}

object Test extends App {

  def f(value: Int):Writer = {
    Writer(40+value, s"f has $value")
  }

  def g(value: Int):Writer = {
    Writer(20+value, s"g has $value")
  }

  val result1 = for {
    a <- g(3)
    b <- f(a)
  } yield b

  println(result1)

  val result2 = g(3) flatMap {
    a => f(a).map(b=>b)
  }

  println(result2)
}


问:
vue js jest.spyOn mounted function call not working in unit test on class component
I am new to unit testing and I am trying to test a function being called when the component is mounted. Below is the component code I am testing:

```<code><template>
  <div>
    <div class="grid">
      <Card
        class="grid_layout_col"
        @showItemDetail="showDetails(index)"
        @openEditModal="editItem(index)"
      />
    </div>
    <!-- fab -->
    <Fab ref="fabBtn" @addItem="showModal" />
  </div>
</template>

<script lang="ts">
// @ is an alias to /src
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import router from "../router";
import { store, actions, mutations } from "@/store/store";
import Card from "@/components/Card.vue";
import Fab from "@/components/Fab.vue";

@Component({
  components: {
    Card,
    Fab
  }
})
export default class Home extends Vue {
  itemData: Array<object>;

  constructor() {
    super();
    this.itemData = [];
  }

  convertBlobURL(imageData: string) {}

  showDetails(val: number) {}

  addItem() {}

  editItem(val: string) {}

  showModal() {}

  resetHeader() {}

   mounted() {
    // load the card data
    actions.loadData();

  }
}
</code>```

Here is the code for the actions:

```<code> export const actions = {
  loadData(){
    store.loadData();
  },
  getDelStoreLength(): number {
    return store.delStore.length;
  },
  getStoreLength(): number {
    return store.dataStore.data.length;
  }
};
</code>```

The problem I am facing is when I run the jest test below:

```<code>import { shallowMount, mount } from "@vue/test-utils";
import Home from "@/views/Home.vue";

//
const factory = (propsData: object) => {
  return shallowMount(Home, {
    propsData: {
      ...propsData
    },
    stubs: {

    },
    mocks: {

    }
  });
};
it("should call actions.loadData function on mounted", () => {
  const wrapper = factory({});
  let spyIt = jest.spyOn(Home as any, 'actions.loadData');
  expect(spyIt).toHaveBeenCalled();
});
</code>```

I get the below:

Cannot spy the actions.loadData property because it is not a function; undefined given instead

Does anyone know what this is and how to fix it?

答:
As it was already noted, actions isn't a property of Home component, so it cannot be spied on it. Even if it were, it couldn't be spied as jest.spyOn(Home as any, 'actions.loadData') because component properties aren't exposed on component object itself and it's incorrect to refer to nested properties with 'actions.loadData' string.

It should be:

```<code>import { actions } from "@/store/store";
  ...
  let spyIt = jest.spyOn(actions, 'loadData').mockImplementation(() => {});
  // mount Home
  expect(spyIt).toHaveBeenCalled();
</code>```

Body:
I am new to unit testing and I am trying to test a function being called when the component is mounted. Below is the component code I am testing:

<template>

      <Card
        class="grid_layout_col"
        @showItemDetail="showDetails(index)"
        @openEditModal="editItem(index)"
      />

    <Fab ref="fabBtn" @addItem="showModal" />

</template>

Body:
As it was already noted, actions isn't a property of Home component, so it cannot be spied on it. Even if it were, it couldn't be spied as jest.spyOn(Home as any, 'actions.loadData') because component properties aren't exposed on component object itself and it's incorrect to refer to nested properties with 'actions.loadData' string.

It should be:

import { actions } from "@/store/store";
  ...
  let spyIt = jest.spyOn(actions, 'loadData').mockImplementation(() => {});
  // mount Home
  expect(spyIt).toHaveBeenCalled();


问:
How to transform template to template pre C++11
Triggered by this question I wrote a template that allows to transform a template into a template with different parameters:

```<code>template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B> using type = T<A,B,true>;
};
</code>```

Background: The aim was to pass a template<int A, char B, bool C> class A2{}; as template template parameter to a template<template<int A, char B> typename T> class A1 {};. I learned about templates with C++11. It was quite a shift in thinking about code once I got used to writing types/functions that take types and "return" types instead of writing functions that take values and return values. It never occurred to me that it is also surprisingly simple to write templates that given a template "return" a different template. The thing is I have not the slightest clue how to write the above or similar without alias templates that are only available since C++11. What was possible always afaik is the following. Given

```<code>template <int A,char B, bool C> struct Foo{};
</code>```

I can "bind" a bool parameter to Foo via:

```<code>template <int A,char B>
struct Add_true_to_Foo {
     typedef Foo<A,B> type;
};
</code>```

But now Add_true_to_Foo::type is not a template and I have not the slightest clue without C++11 how to write a Add_true that would not only work for Foo but also for

```<code>template <int A,char B, bool C> struct Bar{};
</code>```

Maybe I am missing something obvious. My quesiton is

Is it possible to write an equivalent to the above Add_true before C++11?

答:
In C++03 we didn't have template aliases, but the same could be achieved with structure templates like this:

```<code>template<template<int A, char B> class T> class A1
{
    typedef typename T<1, 'a'>::type actual_A2;
};

template<int A, char B, bool C> class A2 {};

template< template<int A, char B, bool C> class T >
struct Add_true
{
    template<int A, char B>
    struct apply
    {
        typedef T<A, B, true> type;
    };
};
typedef Add_true<A2> A2_with_true;

A1< A2_with_true::apply > a1;
</code>```

Note that you need to change how A1 works as it must use a nested type typedef to obtain the actual A2 specialization.

Body:
Triggered by this question I wrote a template that allows to transform a template into a template with different parameters:

template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B> using type = T;
};

Background: The aim was to pass a template<int A, char B, bool C> class A2{}; as template template parameter to a template<template<int A, char B> typename T> class A1 {};. I learned about templates with C++11. It was quite a shift in thinking about code once I got used to writing types/functions that take types and "return" types instead of writing functions that take values and return values. It never occurred to me that it is also surprisingly simple to write templates that given a template "return" a different template. The thing is I have not the slightest clue how to write the above or similar without alias templates that are only available since C++11. What was possible always afaik is the following. Given

template <int A,char B, bool C> struct Foo{};

I can "bind" a bool parameter to Foo via:

template <int A,char B>
struct Add_true_to_Foo {
     typedef Foo type;
};

But now Add_true_to_Foo::type is not a template and I have not the slightest clue without C++11 how to write a Add_true that would not only work for Foo but also for

template <int A,char B, bool C> struct Bar{};

Maybe I am missing something obvious. My quesiton is

Is it possible to write an equivalent to the above Add_true before C++11?

Body:
In C++03 we didn't have template aliases, but the same could be achieved with structure templates like this:

template<template<int A, char B> class T> class A1
{
    typedef typename T<1, 'a'>::type actual_A2;
};

template<int A, char B, bool C> class A2 {};

template< template<int A, char B, bool C> class T >
struct Add_true
{
    template<int A, char B>
    struct apply
    {
        typedef T<A, B, true> type;
    };
};
typedef Add_true<A2> A2_with_true;

A1< A2_with_true::apply > a1;

Note that you need to change how A1 works as it must use a nested type typedef to obtain the actual A2 specialization.


问:
How to get discriminated union behavior with overloading
I have function overloading

```<code>function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(values: (IFirst | ISecond), type: (MyEnum.FIRST | MyEnum.SECOND)): number {
  if(type === MyEnum.FIRST) {
    values.
  }
  ...
}
</code>```

Why my values inside if statement is conjunction of IFirst and ISecond ?

How to get discriminated union behavior here? Without adding type string to interfaces, but with type argument.

I want my values to be IFirst in if statement.

答:
Variables (or parameters) in this case never narrow one another, they can only narrow themselves.

You can get the discriminated union behavior with a tuple, and you can use tuples in rest parameters to spread the tuple to the parameters. The biggest disadvantage of this is you will have to access the tuple items with numbers.

```<code>function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(...params: [IFirst, MyEnum.FIRST] | [ISecond, MyEnum.SECOND]): number {
  if(params[1] === MyEnum.FIRST) {
      return params[0].first;
  } else {
      return params[0].second;
  }
}
</code>```

Playground Link

Body:
I have function overloading

function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(values: (IFirst | ISecond), type: (MyEnum.FIRST | MyEnum.SECOND)): number {
  if(type === MyEnum.FIRST) {
    values.
  }
  ...
}

Why my values inside if statement is conjunction of IFirst and ISecond ?

How to get discriminated union behavior here? Without adding type string to interfaces, but with type argument.

I want my values to be IFirst in if statement.

Body:
Variables (or parameters) in this case never narrow one another, they can only narrow themselves.

You can get the discriminated union behavior with a tuple, and you can use tuples in rest parameters to spread the tuple to the parameters. The biggest disadvantage of this is you will have to access the tuple items with numbers.

function MyFunc(values: IFirst, type: MyEnum.FIRST): number
function MyFunc(values: ISecond, type: MyEnum.SECOND): number
function MyFunc(...params: [IFirst, MyEnum.FIRST] | [ISecond, MyEnum.SECOND]): number {
  if(params[1] === MyEnum.FIRST) {
      return params[0].first;
  } else {
      return params[0].second;
  }
}

<a href="https://www.typescriptlang.org/play/?ssl=15&ssc=1&pln=5&pc=1#code/KYOwrgtgBAsgngUXNA3lAYgSQEoGUAqANFLggMIDyAcgCJQC+AsAFACWIALsAE4BmAhgGNgUTOlbcAzhyhpeE6QC4oyAEY8GLdlz5CRmXMEEB7EABNZUSUdNnlajU2YsWvMCEEdWp2HHTvBAAoAN34AGzBgSWUxBQ5iDjgAB2BleCRIADosPHwASntIdW5XAK8feH8PEPDI6NFDE3ME5NTfDIhM0kpaApUinlKPcpBfKqDMyaT+bn4IeoBtWKl49uRsnAIAXSgAHyglxttidPXu6hotvoduWRYoKFZeQOnZ+YWARh2AXl+1rJyBDyd2YDzBUG4wA4YG4o1ec0kCwADFtMvIVgBue4MKDAMLWEHgh6Q6GwqDw94ozLWJpmLGgzTMJwsIA" rel="nofollow noreferrer">Playground Link


问:
How to get git-status of a single subfolder?
When I do git status in a subfolder of my repository it includes the status of parent folders also.

Is there a way to constrain git-status to just a particular folder?

答:
It is possible to restrict git status to the current directory (without child folders) by giving a pathspec using the magic word glob and *::

git status ':(glob)*'
```

ContentLicense: CC BY-SA 2.5


问:
how to remove /?fbclid=... in nuxt url
hello there i like to remove the facebook analytic forced url parameter /?fbclid= https://www.example.com/?fbclid=..., from my host url, when redirected from facebook by clicking the url, the problem is the nuxt-link-exact-active class is not applied if redirected with this parameter.
Thanks

答:
In simple cases like  https://www.example.com/?fbclid=... where fbclid is the only parameter, it should be a trivial Javascript like that:

```<code> <script>
  // ideally this is on top of page; works on bottom as well

  if(/^\?fbclid=/.test(location.search))
     location.replace(location.href.replace(/\?fbclid.+/, ""));

 </script>
</code>```

This checks if ?fbclid=... is a URL search parameter and navigates to the same location with that part removed.

It may also be fine to remove any search parameter and not checking for fbclid.

```<code> <script>
   if(location.search) location.replace(location.href.replace(/\?.+/, ""));
 </script>
</code>```

Title: how to remove /?fbclid=... in nuxt url

Body:
In simple cases like  https://www.example.com/?fbclid=... where fbclid is the only parameter, it should be a trivial Javascript like that:

 <script>
  // ideally this is on top of page; works on bottom as well

  if(/^\?fbclid=/.test(location.search))
     location.replace(location.href.replace(/\?fbclid.+/, ""));

 </script>

This checks if ?fbclid=... is a URL search parameter and navigates to the same location with that part removed.

It may also be fine to remove any search parameter and not checking for fbclid.

 <script>
   if(location.search) location.replace(location.href.replace(/\?.+/, ""));
 </script>


问:
Console.log of function returning object
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

```<code> testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }
</code>```

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

```<code> expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },
</code>```

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd

答: You can try console.dir() instead of console.log()

Body:
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

 testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

 expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd


问:
Talend studio isNumeric()
I am learning talend open studio and I want to put this line of code :

boolean numeric = isNumeric(input_row.id);

In tjavaroW, but when I run the job it throws me an error:

isNumeric is an undefined method

. Please can you tell me how to solve this problem?

Thanks a lot.

答:
In Talend you must indicate the Library you are using.
For instance : StringUtils.isNumeric.</p>

Title: Talend studio isNumeric()


问:
How do I get user IP address in Django?
How do I get user's IP in Django?

I have a view like this:

```<code># Create your views
from django.contrib.gis.utils import GeoIP
from django.template import  RequestContext
from django.shortcuts import render_to_response

def home(request):
  g = GeoIP()
  client_ip = request.META['REMOTE_ADDR']
  lat,long = g.lat_lon(client_ip)
  return render_to_response('home_page_tmp.html',locals())
</code>```

But I get this error:

```<code>KeyError at /mypage/
    'REMOTE_ADDR'
    Request Method: GET
    Request URL:    http://mywebsite.example/mypage/
    Django Version: 1.2.4
    Exception Type: KeyError
    Exception Value:
    'REMOTE_ADDR'
    Exception Location: /mysite/homepage/views.py in home, line 9
    Python Executable:  /usr/bin/python
    Python Version: 2.6.6
    Python Path:    ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
    Server time:    Sun, 2 Jan 2011 20:42:50 -0600
</code>```

答:
No More confusion In the recent versions of Django it is mentioned clearly that
the Ip address of the client is available at

```<code>request.META.get("REMOTE_ADDR")
</code>```

for more info check the Django Docs

Title: How do I get user IP address in Django?

Body:
How do I get user's IP in Django?

I have a view like this:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template import  RequestContext
from django.shortcuts import render_to_response

def home(request):
  g = GeoIP()
  client_ip = request.META['REMOTE_ADDR']
  lat,long = g.lat_lon(client_ip)
  return render_to_response('home_page_tmp.html',locals())

But I get this error:

KeyError at /mypage/
    'REMOTE_ADDR'
    Request Method: GET
    Request URL:    http://mywebsite.example/mypage/
    Django Version: 1.2.4
    Exception Type: KeyError
    Exception Value:
    'REMOTE_ADDR'
    Exception Location: /mysite/homepage/views.py in home, line 9
    Python Executable:  /usr/bin/python
    Python Version: 2.6.6
    Python Path:    ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
    Server time:    Sun, 2 Jan 2011 20:42:50 -0600

Body:
No More confusion In the recent versions of Django it is mentioned clearly that
the Ip address of the client is available at

request.META.get("REMOTE_ADDR")

for more info check the Django Docs


问:
Saving string to SQLite many times consumes a ridiculous amount of disk space?
Through my front-end I allow users to edit posts with an auto-save-function. Every update of the post is saved to the DB. On edit the instance from the last save is updated via a PUT request.

The amount of space this is consuming however is quite ridiculous. Disregarding, if the updated string gets longer or shorter the space only goes up. My local SQLite file has now more than 500MB.

The relevant view in django is verbose but pretty standard I'd say:

```<code>class PostDetail(APIView):
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly,
        IsOwnerOrReadOnly,
        IsOwnerOrPublishedOnly]

    def get_queryset(self):
        queryset = Post.objects.all()
        is_published = self.request.query_params.get('is_published', None)
        if is_published and is_published == 'false':
            queryset.filter(is_published=False)
        if is_published and is_published == 'true':
            queryset.filter(is_published=True)
        return queryset

    def get_object(self):
        obj = get_object_or_404(self.get_queryset(), uuid=self.kwargs.get('post_uuid', None))
        self.check_object_permissions(self.request, obj)
        return obj

    def put(
        self,
        request,
        post_uuid,
        format=None):
        post = self.get_object()
        serializer = PostUpdateSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
</code>```

I can't really wrap my head around how to debug this? This is why I'm turning to SO. Any tips?

答:
The for the sake of documenting this:

My problem was, that I was using a profiling tool called django-silk. This was saving every SQL query and DB request as well as a profiling record. This consumes a ridiculous amount of disk space.

To analyse the database I had to switch to postgres.

Body:
Through my front-end I allow users to edit posts with an auto-save-function. Every update of the post is saved to the DB. On edit the instance from the last save is updated via a PUT request.

The amount of space this is consuming however is quite ridiculous. Disregarding, if the updated string gets longer or shorter the space only goes up. My local SQLite file has now more than 500MB.

The relevant view in django is verbose but pretty standard I'd say:

class PostDetail(APIView):
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly,
        IsOwnerOrReadOnly,
        IsOwnerOrPublishedOnly]

    def get_queryset(self):
        queryset = Post.objects.all()
        is_published = self.request.query_params.get('is_published', None)
        if is_published and is_published == 'false':
            queryset.filter(is_published=False)
        if is_published and is_published == 'true':
            queryset.filter(is_published=True)
        return queryset

    def get_object(self):
        obj = get_object_or_404(self.get_queryset(), uuid=self.kwargs.get('post_uuid', None))
        self.check_object_permissions(self.request, obj)
        return obj

    def put(
        self,
        request,
        post_uuid,
        format=None):
        post = self.get_object()
        serializer = PostUpdateSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

I can't really wrap my head around how to debug this? This is why I'm turning to SO. Any tips?