问:
Running Facebook Graph API queries
I want to run the following search query using Facebook Graph API

"pages liked by people who like microsoft"

I can run this query from within facebook. Is it possible to retrieve the same information using the Graph API?

Thank You.

答:
I agree with everybody that there is no direct way of checking whether a particular user has liked a certain page or not using FB Graph API.

But i believe there is a workaround for this and you can try to hit the below URL in your browser

```<code>https://www.facebook.com/search/<page_id>/likers?ref=about
</code>```

It will return all the people information who have liked the page provided. I am not sure would this return all the results or just some of them. But i believe you can try this.

You can then do some web scraping which will help you indentify whether 'person A' has liked a page say 'abc'.

Now you can hit the below endpoint to retreive all the likes this 'person a' has liked

```<code>FB.api('/person_id_obtained_from_above/likes')
</code>```

But please note that you need user_likes permission to retrieve someone else's likes

Let me know if this worked for you.

Title: Running Facebook Graph API queries

Body:
I agree with everybody that there is no direct way of checking whether a particular user has liked a certain page or not using FB Graph API.

But i believe there is a workaround for this and you can try to hit the below URL in your browser

https://www.facebook.com/search/<page_id>/likers?ref=about

It will return all the people information who have liked the page provided. I am not sure would this return all the results or just some of them. But i believe you can try this.

You can then do some web scraping which will help you indentify whether 'person A' has liked a page say 'abc'.

Now you can hit the below endpoint to retreive all the likes this 'person a' has liked

FB.api('/person_id_obtained_from_above/likes')

But please note that you need user_likes permission to retrieve someone else's likes

Let me know if this worked for you.


来源: stackexchange

问:
Opening another app
How can i open APK file recently downloaded from my application?

I tried:

```<code>Intent it = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
startActivity(it);
</code>```

But this didn't work at all it wanted to open it by PDF reader.

```<code>public void install(File file){
    if(file.exists()){
    Intent i = new Intent();
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(i);}
}
</code>```

With this code i have package error while opening this app.

答:
I think your code will run only < N.

For that you have to implement FileProvider,

ContentLicense: CC BY-SA 3.0

Title: Opening another app

Body:
How can i open APK file recently downloaded from my application?

I tried:

Intent it = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
startActivity(it);

But this didn't work at all it wanted to open it by PDF reader.

public void install(File file){
    if(file.exists()){
    Intent i = new Intent();
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(i);}
}

With this code i have package error while opening this app.


问:
iOS Enterprise: Re-certify existing IPA with new certificate
We are enrolled in the iOS Enterprise Program. The provisioning profile used for our released apps is about to expire, so I got a new certificate and provisioning profile.

I need to re-distribute some of our apps with the new provisioning profile, without building them anew. How?

(I vaguely remember seeing a utility program that did exactly this: You choose an IPA and a provisioning profile, and it would create a new IPA using the new profile and certificate. What was the tool’s name, and where can I get it?)

答:
You can do manual way if you just resigning app from same account with following steps.

All this is using shell script and super easy provided you know how to use shell commands.

Rename IPA to zip

unzip this file to temp folder

Remove the old _CodeSignature folder from all targets (if you have multiple targets like main,watch, watch extn, siri, widget, message, etc)

bring all the targets prov-profiles in one folder and replace all the embedded.provisioningprofile files for each target with the new ones

remove the archived....xccent file as this is old one (optional)

code sign with the entitlements.plist created for all the entitlements if any used by the app.

Zip the folder back after code sign all okay with no errors

Rename the zip to IPA

Note: To validate the IPA before upload to apple you can just use the altool from inbuild XCode App Loader to check the new IPA.

Reference: The steps for commands is also explained here:
http://www.enterpriseios.com/forum/topic/Resigning_3rd_party_apps

If you want to get rid of manual sign use the fastlane tool as its quite simple and easy to configure.https://fastlane.tools/


问:
Pinch to zoom, double tap to zoom + swipe gestures
EDITED: NOW The entire class is posted, not just the inner custom listener

For a couple weeks now I kept this problem in my mind and still have no answer. I want to make a "Photo view activity" where the user is brought to see a photo on the entire screen. The users must be able to double tap to zoom, pinch to zoom and also to be able to exit the activity when they swipe left/right. For now I am able to do the following:
swipe to exit
pinch/double tap to zoom(Photo attacher)

However, if I try to use both at the same time the system will think that I am trying to zoom and won't trigger listeners for  swipes.Since the photo attacher is trivial, here is some code for the swipe part: A inner class

```<code>public class PhotoShowActivity extends Activity{
//  Toolbar bar;
PhotoView photoToShow;
PhotoViewAttacher attacher = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_show);
    //set up bar
   // bar = (Toolbar) findViewById(R.id.toolbar_with_back_key);
  //  bar.setTitle("");
    //setSupportActionBar(bar);
   // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  //  getSupportActionBar().setDisplayShowHomeEnabled(true);
    photoToShow = (PhotoView) findViewById(R.id.photo_show);
    Intent i = getIntent();
    try
    {
        File receive = (File) i.getSerializableExtra("image");
     //  getSupportActionBar().setTitle(i.getStringExtra("title"));
        Glide.with(this).load(receive).into(photoToShow);

    }catch(Exception e){finish();}
    attacher = new PhotoViewAttacher(photoToShow);
    photoToShow.setOnTouchListener(new OnSwipeTouchListener(PhotoShowActivity.this)
    {
        public void onSwipeRight() {
            PhotoShowActivity.this.finish();
        }
        public void onSwipeLeft() {
                    PhotoShowActivity.this.finish();
        }
        public void onSwipeTop() {
            //       PhotoShowActivity.this.finish();
        }
        public void onSwipeBottom() {
            //      PhotoShowActivity.this.finish();
        }
    });

}

public class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (attacher.getScale() == 1.0) {
            gestureDetector.onTouchEvent(event);
        }
        return true;
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                }
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}
</code>```

}

Here we have the listener being bind to the image view

```<code>imageView.setOnTouchListener(new OnSwipeTouchListener(PhotoShowActivity.this){
        public void onSwipeRight() {
            PhotoShowActivity.this.finish();
        }
        public void onSwipeLeft() {
                    PhotoShowActivity.this.finish();
        }
        public void onSwipeTop() {
            //       PhotoShowActivity.this.finish();
        }
        public void onSwipeBottom() {
            //      PhotoShowActivity.this.finish();
        }
    });
</code>```

Any ideas on how I can combine zoom and swipes ?

答:
All you need to do is to check whether your ImageView is zoomed or not. If it is zoomed in then your swipe left and right functionality should not work. PhotoView library provides functionality to check zooming level of ImageView. I have faced the same issue and I have figured out. You can find below snippet for your reference,

```<code>   @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (imgPdfView.getCurrentZoom() == 1) {
            mGestureDetector.onTouchEvent(motionEvent);
        }
        return true;
    }
</code>```

If imgPdfView.getCurrentZoom()==1, It means your ImageView is in normal state. So now you can swipe left or swipe right for the further functionality.

Body:
EDITED: NOW The entire class is posted, not just the inner custom listener

For a couple weeks now I kept this problem in my mind and still have no answer. I want to make a "Photo view activity" where the user is brought to see a photo on the entire screen. The users must be able to double tap to zoom, pinch to zoom and also to be able to exit the activity when they swipe left/right. For now I am able to do the following:
swipe to exit
pinch/double tap to zoom(Photo attacher)

However, if I try to use both at the same time the system will think that I am trying to zoom and won't trigger listeners for  swipes.Since the photo attacher is trivial, here is some code for the swipe part: A inner class

public class PhotoShowActivity extends Activity{
//  Toolbar bar;
PhotoView photoToShow;
PhotoViewAttacher attacher = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_show);
    //set up bar
   // bar = (Toolbar) findViewById(R.id.toolbar_with_back_key);
  //  bar.setTitle("");
    //setSupportActionBar(bar);
   // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  //  getSupportActionBar().setDisplayShowHomeEnabled(true);
    photoToShow = (PhotoView) findViewById(R.id.photo_show);
    Intent i = getIntent();
    try
    {
        File receive = (File) i.getSerializableExtra("image");
     //  getSupportActionBar().setTitle(i.getStringExtra("title"));
        Glide.with(this).load(receive).into(photoToShow);

    }catch(Exception e){finish();}
    attacher = new PhotoViewAttacher(photoToShow);
    photoToShow.setOnTouchListener(new OnSwipeTouchListener(PhotoShowActivity.this)
    {
        public void onSwipeRight() {
            PhotoShowActivity.this.finish();
        }
        public void onSwipeLeft() {
                    PhotoShowActivity.this.finish();
        }
        public void onSwipeTop() {
            //       PhotoShowActivity.this.finish();
        }
        public void onSwipeBottom() {
            //      PhotoShowActivity.this.finish();
        }
    });

}

public class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (attacher.getScale() == 1.0) {
            gestureDetector.onTouchEvent(event);
        }
        return true;
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                }
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

}

Here we have the listener being bind to the image view

imageView.setOnTouchListener(new OnSwipeTouchListener(PhotoShowActivity.this){
        public void onSwipeRight() {
            PhotoShowActivity.this.finish();
        }
        public void onSwipeLeft() {
                    PhotoShowActivity.this.finish();
        }
        public void onSwipeTop() {
            //       PhotoShowActivity.this.finish();
        }
        public void onSwipeBottom() {
            //      PhotoShowActivity.this.finish();
        }
    });

Any ideas on how I can combine zoom and swipes ?

Body:
All you need to do is to check whether your ImageView is zoomed or not. If it is zoomed in then your swipe left and right functionality should not work. PhotoView library provides functionality to check zooming level of ImageView. I have faced the same issue and I have figured out. You can find below snippet for your reference,

   @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (imgPdfView.getCurrentZoom() == 1) {
            mGestureDetector.onTouchEvent(motionEvent);
        }
        return true;
    }

If imgPdfView.getCurrentZoom()==1, It means your ImageView is in normal state. So now you can swipe left or swipe right for the further functionality.


问:
Finding "^M" using Python re
I have a file that has occurences of the characters "^M". I want to remove all such occurences.

For this I tried using the following bit of code -

```<code>re.sub('^M', '', line)
</code>```

Even on multiple attempts i am unable to remove it.

Can anyone please tell me whats wrong with what I am doing and suggest something

答:
^ is a meta-character in regular expressions, and it should be escaped, i.e.

```<code>re.sub('\\^M', '', line)  # 2 backslashes because the backslash needs to be escaped
</code>```

or

```<code>re.sub(r'\^M')            # no escape needed because of a raw string.
</code>```

But then, this is a fixed string, so you should use str.replace, i.e.

```<code>line.replace('^M', '')
</code>```

But then, not always does the ^ and M mean that there is ^ and M, as the ^M can also be used to mean the ASCII carriage return (U+0013, or Control-M); which in a Python string is \r:

```<code>line.replace('\r', '')
</code>```

... but then there is already a utility that will strip these Windows line endings from a file: dos2unix.

Title: Finding "^M" using Python re

Body:
I have a file that has occurences of the characters "^M". I want to remove all such occurences.

For this I tried using the following bit of code -

re.sub('^M', '', line)

Even on multiple attempts i am unable to remove it.

Can anyone please tell me whats wrong with what I am doing and suggest something

Body:
^ is a meta-character in regular expressions, and it should be escaped, i.e.

re.sub('\\^M', '', line)  # 2 backslashes because the backslash needs to be escaped

or

re.sub(r'\^M')            # no escape needed because of a raw string.

But then, this is a fixed string, so you should use str.replace, i.e.

line.replace('^M', '')

But then, not always does the ^ and M mean that there is ^ and M, as the ^M can also be used to mean the ASCII carriage return (U+0013, or Control-M); which in a Python string is \r:

line.replace('\r', '')

... but then there is already a utility that will strip these Windows line endings from a file: dos2unix.


问:
How to test a method with a parameter using RSpec?
I have the following RSpec:

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        my_param = [{"job1" => "run"}, {"job2" => "run again"}]

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end
</code>```

The method:

```<code>Class Job
  def run_job(my_param)
    # puts "#{my_param}"
    my_param.each do|f|
      # do something
    end
  end
end
</code>```

when I run the test I receive the following error

```<code> NoMethodError:
   undefined method `each' for nil:NilClass
</code>```

I print out my_param in the console and see same object that was passed to the test, [{"job1" => "run"}, {"job2" => "run again"}]. I have no idea why my_param is nil when calling .each. What did I do wrong? Any insight is appreciated.

答:
One way would be defining in the before block and forming it the instance variable as;

```<code>before { @my_param = [{"job1" => "run"}, {"job2" => "run again"}] }
</code>```

or

but the best way would be to use let:

```<code>describe Job do
  let(:job) { Job.new }
  let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }
  describe 'run_job' do
    context 'success' do

      it 'should pass' do
        test_result = job.run_job(my_param)
        expect(test_result[0]["job1"]).to eq("run")
      end
    end
  end
end
</code>```

Body:
I have the following RSpec:

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        my_param = [{"job1" => "run"}, {"job2" => "run again"}]

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end

The method:

Class Job
  def run_job(my_param)
    # puts "#{my_param}"
    my_param.each do|f|
      # do something
    end
  end
end

when I run the test I receive the following error

 NoMethodError:
   undefined method `each' for nil:NilClass

I print out my_param in the console and see same object that was passed to the test, [{"job1" => "run"}, {"job2" => "run again"}]. I have no idea why my_param is nil when calling .each. What did I do wrong? Any insight is appreciated.

Body:
One way would be defining in the before block and forming it the instance variable as;

before { @my_param = [{"job1" => "run"}, {"job2" => "run again"}] }

or

but the best way would be to use let:

describe Job do
  let(:job) { Job.new }
  let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }
  describe 'run_job' do
    context 'success' do

      it 'should pass' do
        test_result = job.run_job(my_param)
        expect(test_result[0]["job1"]).to eq("run")
      end
    end
  end
end


问:
Android PayUMoney integration error "some error occured"
I am trying to integrate PayUMoney payment gateway in my android app, I am not sure what is happening with it. Even If I have generated hash from server and followed exactly the same procedure provided on PayUMoney website

I am getting TOAST message some error occured. Event landing page is not loaded, as soon as I move from checkout page to payU spinner rotates a while and after that I get TOAST message and I land back to my checkout page.

PayUMoney Code

```<code> String serverCalculatedHash = getHashFromServer();

     PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder();
                            builder.setAmount(Double.parseDouble(paymentAmount))
                                    .setTxnId(transactionId)
                                    .setPhone(phoneNumber)
                                    .setProductName(productName)
                                    .setFirstName(firstName)
                                    .setEmail(emailId)
                                    .setsUrl("https://www.payumoney.com/mobileapp/payumoney/success.php")
                                    .setfUrl("https://www.payumoney.com/mobileapp/payumoney/failure.php")
                                    .setUdf1(udf1)
                                    .setUdf2(udf2)
                                    .setUdf3(udf3)
                                    .setUdf4(udf4)
                                    .setUdf5(udf5)
                                    .setUdf6("")
                                    .setUdf7("")
                                    .setUdf8("")
                                    .setUdf9("")
                                    .setUdf10("")
                                    .setIsDebug(true)
                                    .setKey(merchentKey)
                                    .setMerchantId(merchentId);

 PayUmoneySdkInitializer.PaymentParam paymentParam = builder.build();
                            paymentParam.setMerchantHash(serverCalculatedHash);
 PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, CheckoutActivity.this, R.style.AppTheme_default, true);
</code>```

Console Log

09-16 21:07:21.488 20712-20712/in.co.sd.app D/hash:
  cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
  09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: key - mJ5aor0Z
  09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: merchantId -
  5710201 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: txnid -
  1505576241249 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  amount - 10.0 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  SURL - https://www.payumoney.com/mobileapp/payumoney/success.php 09-16
  21:07:21.489 20712-20712/in.co.sd.app D/param :: FURL -
  https://www.payumoney.com/mobileapp/payumoney/failure.php 09-16
  21:07:21.489 20712-20712/in.co.sd.app D/param :: productInfo - product
  name 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: email -
  xyz@gmail.com 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  firstName - MyName 09-16 21:07:21.489 20712-20712/in.co.sd.app
  D/param :: phone - 9999014250 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf1 - udf1 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf2 - udf2 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf3 - udf3 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf4 - udf4 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf5 - udf5 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf6 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf7 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf8 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf9 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf10 -  09-16 21:07:21.526
  20712-20712/in.co.sd.app I/WebViewFactory: Loading
  com.google.android.webview version 60.0.3112.116 (code 311211650)
  09-16 21:07:21.569 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.569 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.572 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.572 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.579 20712-20712/in.co.sd.app I/cr_LibraryLoader: Time
  to load native libraries: 1 ms (timestamps 6391-6392) 09-16
  21:07:21.596 20712-20712/in.co.sd.app I/chromium:
  [INFO:library_loader_hooks.cc(144)] Chromium logging enabled: level =
  0, default verbosity = 0 09-16 21:07:21.596 20712-20712/in.co.sd.app
  I/cr_LibraryLoader: Expected native library version number
  "60.0.3112.116", actual native library version number "60.0.3112.116"
  09-16 21:07:21.622 20712-20712/in.co.sd.app I/cr_BrowserStartup:
  Initializing chromium process, singleProcess=true 09-16 21:07:21.858
  20712-20712/in.co.sd.app D/EgretLoader: EgretLoader(Context context)
  09-16 21:07:21.858 20712-20712/in.co.sd.app D/EgretLoader: The context
  is not activity 09-16 21:07:21.921 20712-20712/in.co.sd.app
  D/payumoneySDK - login:
  {"event_id":"1","device_id":"739bbf12ec1be70e","uuid":"0b500414-dff6-4f21-bfdf-aed66a78d150","d_ua":"Mozilla/5.0
  (Linux; Android 6.0.1; Redmi Note 3 Build/MMB29M; wv)
  AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0
  Chrome/60.0.3102.110 Mobile
  Safari/537.36","u_lat":"","u_lon":"","u_acu":"","app_id":"in.co.sd.app","package_name":"in.co.sd.app","app_version_name":"1.0","app_version_code":"1","d_locale":"en","d_ccid":"in","d_lang":"English","d_name":"Xiaomi","d_model":"Redmi
  Note
  3","d_os":"Android","d_osv":"6.0.1","sdk_version":"7","sdk_build":"7.0.0","d_mfg":"Xiaomi","d_nw_type":"WIFI","d_ss":"4","d_scrn_sz":"5.7437176737064215","d_scrn_res":"1080
  * 1920","m_id":"5773251","m_key":"mJ5aor0Z","ip":"10.107.124.9","app_name":"Service
  Service","d_ts":"1505576241915","env":"DEBUG"} 09-16 21:07:22.076
  20712-20712/in.co.sd.app I/Timeline: Timeline: Activity_launch_request
  time:58596890 09-16 21:07:22.183 20712-20712/in.co.sd.app
  V/BoostFramework: BoostFramework() : mPerf =
  com.qualcomm.qti.Performance@f0846b7 09-16 21:07:22.183
  20712-20712/in.co.sd.app V/BoostFramework: BoostFramework() : mPerf =
  com.qualcomm.qti.Performance@49c0e24 09-16 21:07:22.216
  20712-20712/in.co.sd.app D/ActivityThreadInjector:
  clearCachedDrawables. 09-16 21:07:22.255 20712-11058/in.co.sd.app
  W/System: Ignoring header UserSessionCookiePageUrl because its value
  was null. 09-16 21:07:23.193 20712-20718/in.co.sd.app W/art:
  Suspending all threads took: 5.983ms 09-16 21:07:23.195
  20712-20712/in.co.sd.app I/Difference: [ main: SdkSession.java: 365:
  onResponse() ] --> URL=/payment/app/v1/addPaymentTime=978 09-16
  21:07:23.325 20712-20784/in.co.sd.app V/RenderScript: 0x557e7de550
  Launching thread(s), CPUs 6

答:
I think I am late to answer, but still,
I faced similar issue, Key and Salt are not correct.
you need to contact payUMoney support, they will provide you new Key,, Salt and MID.
Also they will provide you php code to generate serverHash,

If you want to test your Key and salt, download this sample app(https://github.com/payu-intrepos/payumoney-new-sample-app)
from payumoney and configure AppEnvironment class with your parameters, hope this helps!

Body:
I am trying to integrate PayUMoney payment gateway in my android app, I am not sure what is happening with it. Even If I have generated hash from server and followed exactly the same procedure provided on PayUMoney website

I am getting TOAST message some error occured. Event landing page is not loaded, as soon as I move from checkout page to payU spinner rotates a while and after that I get TOAST message and I land back to my checkout page.

PayUMoney Code

 String serverCalculatedHash = getHashFromServer();

     PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder();
                            builder.setAmount(Double.parseDouble(paymentAmount))
                                    .setTxnId(transactionId)
                                    .setPhone(phoneNumber)
                                    .setProductName(productName)
                                    .setFirstName(firstName)
                                    .setEmail(emailId)
                                    .setsUrl("https://www.payumoney.com/mobileapp/payumoney/success.php")
                                    .setfUrl("https://www.payumoney.com/mobileapp/payumoney/failure.php")
                                    .setUdf1(udf1)
                                    .setUdf2(udf2)
                                    .setUdf3(udf3)
                                    .setUdf4(udf4)
                                    .setUdf5(udf5)
                                    .setUdf6("")
                                    .setUdf7("")
                                    .setUdf8("")
                                    .setUdf9("")
                                    .setUdf10("")
                                    .setIsDebug(true)
                                    .setKey(merchentKey)
                                    .setMerchantId(merchentId);

 PayUmoneySdkInitializer.PaymentParam paymentParam = builder.build();
                            paymentParam.setMerchantHash(serverCalculatedHash);
 PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, CheckoutActivity.this, R.style.AppTheme_default, true);

Console Log

09-16 21:07:21.488 20712-20712/in.co.sd.app D/hash:
  cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
  09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: key - mJ5aor0Z
  09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: merchantId -
  5710201 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: txnid -
  1505576241249 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  amount - 10.0 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  SURL - https://www.payumoney.com/mobileapp/payumoney/success.php 09-16
  21:07:21.489 20712-20712/in.co.sd.app D/param :: FURL -
  https://www.payumoney.com/mobileapp/payumoney/failure.php 09-16
  21:07:21.489 20712-20712/in.co.sd.app D/param :: productInfo - product
  name 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param :: email -
  xyz@gmail.com 09-16 21:07:21.489 20712-20712/in.co.sd.app D/param ::
  firstName - MyName 09-16 21:07:21.489 20712-20712/in.co.sd.app
  D/param :: phone - 9999014250 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf1 - udf1 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf2 - udf2 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf3 - udf3 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf4 - udf4 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf5 - udf5 09-16 21:07:21.489
  20712-20712/in.co.sd.app D/param :: udf6 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf7 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf8 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf9 -  09-16 21:07:21.490
  20712-20712/in.co.sd.app D/param :: udf10 -  09-16 21:07:21.526
  20712-20712/in.co.sd.app I/WebViewFactory: Loading
  com.google.android.webview version 60.0.3112.116 (code 311211650)
  09-16 21:07:21.569 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.569 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.572 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.572 20712-20712/in.co.sd.app I/art: Rejecting re-init
  on previously-failed class
  java.lang.Class
  09-16 21:07:21.579 20712-20712/in.co.sd.app I/cr_LibraryLoader: Time
  to load native libraries: 1 ms (timestamps 6391-6392) 09-16
  21:07:21.596 20712-20712/in.co.sd.app I/chromium:
  [INFO:library_loader_hooks.cc(144)] Chromium logging enabled: level =
  0, default verbosity = 0 09-16 21:07:21.596 20712-20712/in.co.sd.app
  I/cr_LibraryLoader: Expected native library version number
  "60.0.3112.116", actual native library version number "60.0.3112.116"
  09-16 21:07:21.622 20712-20712/in.co.sd.app I/cr_BrowserStartup:
  Initializing chromium process, singleProcess=true 09-16 21:07:21.858
  20712-20712/in.co.sd.app D/EgretLoader: EgretLoader(Context context)
  09-16 21:07:21.858 20712-20712/in.co.sd.app D/EgretLoader: The context
  is not activity 09-16 21:07:21.921 20712-20712/in.co.sd.app
  D/payumoneySDK - login:
  {"event_id":"1","device_id":"739bbf12ec1be70e","uuid":"0b500414-dff6-4f21-bfdf-aed66a78d150","d_ua":"Mozilla/5.0
  (Linux; Android 6.0.1; Redmi Note 3 Build/MMB29M; wv)
  AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0
  Chrome/60.0.3102.110 Mobile
  Safari/537.36","u_lat":"","u_lon":"","u_acu":"","app_id":"in.co.sd.app","package_name":"in.co.sd.app","app_version_name":"1.0","app_version_code":"1","d_locale":"en","d_ccid":"in","d_lang":"English","d_name":"Xiaomi","d_model":"Redmi
  Note
  3","d_os":"Android","d_osv":"6.0.1","sdk_version":"7","sdk_build":"7.0.0","d_mfg":"Xiaomi","d_nw_type":"WIFI","d_ss":"4","d_scrn_sz":"5.7437176737064215","d_scrn_res":"1080
  * 1920","m_id":"5773251","m_key":"mJ5aor0Z","ip":"10.107.124.9","app_name":"Service
  Service","d_ts":"1505576241915","env":"DEBUG"} 09-16 21:07:22.076
  20712-20712/in.co.sd.app I/Timeline: Timeline: Activity_launch_request
  time:58596890 09-16 21:07:22.183 20712-20712/in.co.sd.app
  V/BoostFramework: BoostFramework() : mPerf =
  com.qualcomm.qti.Performance@f0846b7 09-16 21:07:22.183
  20712-20712/in.co.sd.app V/BoostFramework: BoostFramework() : mPerf =
  com.qualcomm.qti.Performance@49c0e24 09-16 21:07:22.216
  20712-20712/in.co.sd.app D/ActivityThreadInjector:
  clearCachedDrawables. 09-16 21:07:22.255 20712-11058/in.co.sd.app
  W/System: Ignoring header UserSessionCookiePageUrl because its value
  was null. 09-16 21:07:23.193 20712-20718/in.co.sd.app W/art:
  Suspending all threads took: 5.983ms 09-16 21:07:23.195
  20712-20712/in.co.sd.app I/Difference: [ main: SdkSession.java: 365:
  onResponse() ] --> URL=/payment/app/v1/addPaymentTime=978 09-16
  21:07:23.325 20712-20784/in.co.sd.app V/RenderScript: 0x557e7de550
  Launching thread(s), CPUs 6


问:
Getting router params into Vuex actions
I would like to pass router params into Vuex actions, without having to fetch them for every single action in a large form like so:

```<code>edit_sport_type({ rootState, state, commit }, event) {
  const sportName = rootState.route.params.sportName <-------
  const payload = {sportName, event}                 <-------
  commit(types.EDIT_SPORT_TYPE, payload)
},
</code>```

Or like so,

```<code>edit_sport_type({ state, commit, getters }, event) {
  const payload = {sportName, getters.getSportName}  <-------
  commit(types.EDIT_SPORT_TYPE, payload)
},
</code>```

Or even worse: grabbing params from component props and passing them to dispatch, for every dispatch.

Is there a way to abstract this for a large set of actions?

Or perhaps an alternative approach within mutations themselves?

答:
To get params from vuex store action, import your vue-router's instance, then access params of the router instance from your vuex store via the router.currentRoute object.

Sample implementation below:

router at src/router/index.js:

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router
</code>```

import the router at vuex store:

import router from '@/router'

then access params at vuex action function, in this case "id", like below:

```<code>router.currentRoute.params.id
</code>```

Title: Getting router params into Vuex actions

Body:
I would like to pass router params into Vuex actions, without having to fetch them for every single action in a large form like so:

edit_sport_type({ rootState, state, commit }, event) {
  const sportName = rootState.route.params.sportName <-------
  const payload = {sportName, event}                 <-------
  commit(types.EDIT_SPORT_TYPE, payload)
},

Or like so,

edit_sport_type({ state, commit, getters }, event) {
  const payload = {sportName, getters.getSportName}  <-------
  commit(types.EDIT_SPORT_TYPE, payload)
},

Or even worse: grabbing params from component props and passing them to dispatch, for every dispatch.

Is there a way to abstract this for a large set of actions?

Or perhaps an alternative approach within mutations themselves?

Body:
To get params from vuex store action, import your vue-router's instance, then access params of the router instance from your vuex store via the router.currentRoute object.

Sample implementation below:

router at src/router/index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

import the router at vuex store:

import router from '@/router'

then access params at vuex action function, in this case "id", like below:

router.currentRoute.params.id

ContentLicense: CC BY-SA 4.0


问:
jquery scroll events fire in delay when the page completed loading
I'm creating a theme for prestashop 1.7, but I don't really think that relates to the issue i'm having. (update: i think it may relate to how prestashop operates because as a stand-alone it works properly)

prestashop 1.7 comes with jquery 2.2.4.

I want to a have a floating cart icon for the user that will stick to the left:0 top:50%, and when the user scrolls the page to will animate it's re-position.

so I have this initial css for my floating cart:

```<code>div#floating_cart {
  position: absolute;
  top: 50%;
  left: 1%;
}
</code>```

and this is the javascript code to catch the scroll:

```<code>   $(window).scroll(function () {
        $('#floating_cart').animate({top:Math.floor($(window).scrollTop() +(window.innerHeight/2))},100,"swing");
    });
</code>```

the problem is  that after the page loads and i try to scroll, only after 4-5 seconds the cart starts all the re-positioning animation it has in his stack.

any ideas how to resolve this delay ?

update

if I only set position:fixed, the cart stays at the chosen position without any problems. but I want it to animate a bit.

so I tried using the following code:

```<code>$(function() {

    $(window).on("load", function () {
        $(window).scroll(function () {
            $('#floating_cart').css('position', 'absolute');
            $('#floating_cart').stop();
            $('#floating_cart').animate({top: Math.floor($(window).scrollTop() + (window.innerHeight / 2))}, 300, "swing");
        });
    });
});
</code>```

and the results are exactly the same.

so I changed the css of floating cart:

```<code>div#floating_cart {
  position: fixed;
  top: 49%;
  left: 1%;
}
</code>```

and I add a 8 seconds delay before attaching to the scroll, and setting the position to absolute instead of fixed.

```<code>$(function() {

    $(window).on("load", function () {
        setTimeout(function() {
            $(window).scroll(function () {
                $('#floating_cart').css('position', 'absolute');
                $('#floating_cart').stop();
                $('#floating_cart').animate({top: Math.floor($(window).scrollTop() + (window.innerHeight / 2))}, 300, "swing");
            });
        },8000);

    });
});
</code>```

now I'm thinking it may relate to how prestashop loads stuff.
how can I investigate this issue further? code is compressed when I load the page so it's hard to debug

答:
Maybe it is not working because you don’t have all the ressources avaible when the page is loading. Try to check if the inclusion of jquery isn’t with the async attribute.

You can also record the scripts when the page is loading via the web ressource inspector in most web browsers

Body:
I'm creating a theme for prestashop 1.7, but I don't really think that relates to the issue i'm having. (update: i think it may relate to how prestashop operates because as a stand-alone it works properly)

prestashop 1.7 comes with jquery 2.2.4.

I want to a have a floating cart icon for the user that will stick to the left:0 top:50%, and when the user scrolls the page to will animate it's re-position.

so I have this initial css for my floating cart:

div#floating_cart {
  position: absolute;
  top: 50%;
  left: 1%;
}

and this is the javascript code to catch the scroll:

   $(window).scroll(function () {
        $('#floating_cart').animate({top:Math.floor($(window).scrollTop() +(window.innerHeight/2))},100,"swing");
    });

the problem is  that after the page loads and i try to scroll, only after 4-5 seconds the cart starts all the re-positioning animation it has in his stack.

any ideas how to resolve this delay ?

update

if I only set position:fixed, the cart stays at the chosen position without any problems. but I want it to animate a bit.

so I tried using the following code:

$(function() {

    $(window).on("load", function () {
        $(window).scroll(function () {
            $('#floating_cart').css('position', 'absolute');
            $('#floating_cart').stop();
            $('#floating_cart').animate({top: Math.floor($(window).scrollTop() + (window.innerHeight / 2))}, 300, "swing");
        });
    });
});

and the results are exactly the same.

so I changed the css of floating cart:

div#floating_cart {
  position: fixed;
  top: 49%;
  left: 1%;
}

and I add a 8 seconds delay before attaching to the scroll, and setting the position to absolute instead of fixed.

$(function() {

    $(window).on("load", function () {
        setTimeout(function() {
            $(window).scroll(function () {
                $('#floating_cart').css('position', 'absolute');
                $('#floating_cart').stop();
                $('#floating_cart').animate({top: Math.floor($(window).scrollTop() + (window.innerHeight / 2))}, 300, "swing");
            });
        },8000);

    });
});

now I'm thinking it may relate to how prestashop loads stuff.
how can I investigate this issue further? code is compressed when I load the page so it's hard to debug


问:
Wordpress dFactory Cookie Notice Plugin
With regard to the GDPR, in german DSGVO, I would like to use the Plugin Cookie Notice from dFactory for my Wordpress website. There is the possibility that non-functional cookies, for example Google Analytics, will no longer be stored if you refuse the use of cookies.

Documentation of Cookie Notice by dFactory

Can any of you tell me which code to write? Unfortunately, I could not find any instructions on the internet. Maybe someone has already implemented something like that.

Thank you in advance.

答:
I was able to find a solution after trying multiple things. I just had to put the javascript code from google analytics between a php if condition like this:

```<code><?php if (cn_cookies_accepted()) { ?>
<script type="text/javascript">
 (function(i,s,o,g,r,a,m).{i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-#', 'auto');
  ga('set', 'forceSSL', true);
  ga('set', 'anonymizeIp', true);
  ga('send', 'pageview');
</script>
<?php } ?>
</code>```

Title: Wordpress dFactory Cookie Notice Plugin

Body:
I was able to find a solution after trying multiple things. I just had to put the javascript code from google analytics between a php if condition like this:

<?php if (cn_cookies_accepted()) { ?>
<script type="text/javascript">
 (function(i,s,o,g,r,a,m).{i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-#', 'auto');
  ga('set', 'forceSSL', true);
  ga('set', 'anonymizeIp', true);
  ga('send', 'pageview');
</script>
<?php } ?>


问:
Oracle Lob segment does not belong to a specific table or does not have table
I've been trying to locate the table that belongs to a specific big lob segment. However, the results always specify that this lob segment does not belong to any table (no rows selected)

```<code>SQL> select owner, table_name, column_name
  2  from dba_lobs
  3  where segment_name = 'SYS_LOB0000551103C00007$$';
no rows selected
</code>```

Is there any way to find the table that where the lob belongs?

答:
The LOB segment might have been orphaned. When a LOB column is set unused, it is cleaned up from the dba_lobs view, but it can still be seen in dba_objects and dba_segments.

Use the following query to find the details the LOB segment.

```<code>select u.name, o.name TABLENAME, decode(bitand(c.property, 1), 1, ac.name, c.name) as column_name
from sys.obj$ o, sys.col$ c, sys.attrcol$ ac,sys.lob$ l,sys.obj$ lo,sys.obj$ io,
sys.user$ u,sys.ts$ ts
where o.owner# = u.user#
and o.obj# = c.obj#
and c.obj# = l.obj# and c.intcol# = l.intcol#
and l.lobj# = lo.obj# and l.ind# = io.obj# and l.ts# = ts.ts# and c.obj# =
ac.obj#(+)
and c.intcol# = ac.intcol#(+) and lo.name ='SYS_LOB0000551103C00007$$';
</code>```

Or, LOB segment might belong to a dropped table residing in the recycle bin. You can use the same query to find the table.

Body:
I've been trying to locate the table that belongs to a specific big lob segment. However, the results always specify that this lob segment does not belong to any table (no rows selected)

SQL> select owner, table_name, column_name
  2  from dba_lobs
  3  where segment_name = 'SYS_LOB0000551103C00007$$';
no rows selected

Is there any way to find the table that where the lob belongs?

Body:
The LOB segment might have been orphaned. When a LOB column is set unused, it is cleaned up from the dba_lobs view, but it can still be seen in dba_objects and dba_segments.

Use the following query to find the details the LOB segment.

select u.name, o.name TABLENAME, decode(bitand(c.property, 1), 1, ac.name, c.name) as column_name
from sys.obj$ o, sys.col$ c, sys.attrcol$ ac,sys.lob$ l,sys.obj$ lo,sys.obj$ io,
sys.user$ u,sys.ts$ ts
where o.owner# = u.user#
and o.obj# = c.obj#
and c.obj# = l.obj# and c.intcol# = l.intcol#
and l.lobj# = lo.obj# and l.ind# = io.obj# and l.ts# = ts.ts# and c.obj# =
ac.obj#(+)
and c.intcol# = ac.intcol#(+) and lo.name ='SYS_LOB0000551103C00007$$';

Or, LOB segment might belong to a dropped table residing in the recycle bin. You can use the same query to find the table.


问:
How do I use a certain version (or higher) of a perl module in my perl script?
I'm using Term::ANSIColor in my Perl script to do colorization of terminal output, and I am using the colorstrip function, which was only added in Term::ANSIColor version 2.01, according to the changelog. So, is there a way to make my script automatically die with an appropriate error message if it doesn't find at least that version of Term::ANSIcolor?

答:
Most modules define the package variable $VERSION.

```<code>use Term::ANSIColor;
die "Sorry, this program needs Term::ANSIColor >= v2.01!\n"
    unless $Term::ANSIColor::VERSION >= 2.01;
</code>```

This is also a good way to specify a maximum version of a module.

```<code>use Module::Foo;
die "You need an *older* version of Module::Foo that ",
    "still has the &barbaz method defined"
    if $Module::Foo::VERSION >= 0.47;
</code>```

Body:
Most modules define the package variable $VERSION.

use Term::ANSIColor;
die "Sorry, this program needs Term::ANSIColor >= v2.01!\n"
    unless $Term::ANSIColor::VERSION >= 2.01;

This is also a good way to specify a maximum version of a module.

use Module::Foo;
die "You need an *older* version of Module::Foo that ",
    "still has the &barbaz method defined"
    if $Module::Foo::VERSION >= 0.47;

ContentLicense: CC BY-SA 2.5


问:
Providing initialized members to base class constructor
Let's say I have flawed C++ code like this:

```<code>struct A final {
    A(); // Initializes somethingShared

    shared_ptr<Something> somethingShared;
};

struct B {
    B(const A& a);
};

struct C : B {
    C()
    : B(a) {} // Uh-oh

    A a;
};
</code>```

C should be-a B, so it inherits from it. But to initialize a B, we need an instance of A. C has to provide one, but how? In the above code, a is used uninitialized, because bases are initialized before members. I need to somehow initialize A before B.

If A wasn't final, I could inherit privately from A:

```<code>struct C : private A, public B {
    C()
    : B(*this) {}
};
</code>```

But because it's final, I do this:

```<code>namespace detail {
    struct C_Base {
    protected:
        A a;
    };
}

struct C : private detail::C_Base, public B {
    C()
    : B(detail::C_Base::a) {}
};
</code>```

Or I could use weird hacks like this:

```<code>struct C : B {
    C(const A a = A())
    : B(a),
      a(a) {}

    A a;
};
</code>```

Is there a better way to do this?

答:
You could do it with a private constructor and a pointer:

```<code>class C : B {
private:
    const std::unique_ptr<A> m_aPtr;
    C(A* a) : B(*a) , m_aPtr(a), m_a(*a){}
public:
    C() : C(new A()) {}

    A& m_a;
};
</code>```

This will ensure that

A is fully constructed before constructing B

A is only constructed once and not copied

m_aPtr will stay valid for the lifetime of the class (due to const) and will destroy A on class destruction properly (like an instanced member)

You can use m_a with the same syntax as an instanced member, because it's a reference. If it's ok for you, you could also leave m_a away and work only with the pointer m_aPtr.

Body:
Let's say I have flawed C++ code like this:

struct A final {
    A(); // Initializes somethingShared

    shared_ptr<Something> somethingShared;
};

struct B {
    B(const A& a);
};

struct C : B {
    C()
    : B(a) {} // Uh-oh

    A a;
};

C should be-a B, so it inherits from it. But to initialize a B, we need an instance of A. C has to provide one, but how? In the above code, a is used uninitialized, because bases are initialized before members. I need to somehow initialize A before B.

If A wasn't final, I could inherit privately from A:

struct C : private A, public B {
    C()
    : B(*this) {}
};

But because it's final, I do this:

namespace detail {
    struct C_Base {
    protected:
        A a;
    };
}

struct C : private detail::C_Base, public B {
    C()
    : B(detail::C_Base::a) {}
};

Or I could use weird hacks like this:

struct C : B {
    C(const A a = A())
    : B(a),
      a(a) {}

    A a;
};

Is there a better way to do this?

Body:
You could do it with a private constructor and a pointer:

class C : B {
private:
    const std::unique_ptr<A> m_aPtr;
    C(A* a) : B(*a) , m_aPtr(a), m_a(*a){}
public:
    C() : C(new A()) {}

    A& m_a;
};

This will ensure that

A is fully constructed before constructing B

A is only constructed once and not copied

m_aPtr will stay valid for the lifetime of the class (due to const) and will destroy A on class destruction properly (like an instanced member)

You can use m_a with the same syntax as an instanced member, because it's a reference. If it's ok for you, you could also leave m_a away and work only with the pointer m_aPtr.


问:
How to pre-fill a READ statement variable in Fortran?
I have a program that has a menu with multiple options (search record, add record, delete record, modify record). What I am trying to do is sort of an autofill function.

Ex: A record number is entered into the search option, but after searching through the database, that record is not found. You are then prompted with the option of searching for a different record number or adding a new record with the variable you just entered. If you choose to add, I want the program to call the add subroutine, and already autofill the read statement with the record you read in to you search subroutine.

This what my code looks like (the search subroutine uses a search function to lookup the record number in master.db, and the display subroutine prints out the results on the screen in a formatted array; both the search and display use a master module with the character and integer variables in the record defined):

```<code>SUBROUTINE search
IMPLICIT NONE
CHARACTER::readRecord*10, changeOpt*1
INTEGER::recNum, search

OPEN(20, FILE="master.db", FORM="FORMATTED", ACCESS="DIRECT", RECL=100)
DO
  CALL SYSTEM ("clear")
  WRITE(*,"(2/,20X,A25)")"* * * Search Record * * *"
  WRITE(*,100,ADVANCE="NO")"Please enter a record number or Q to exit:"
100 FORMAT(1/,20X,A42,1X)
  READ(*,200)readRecord
200 FORMAT(A10)

  IF(readSSN=="Q" .OR. readSSN=="q")RETURN
  recNum=search(readRecord)

  IF (recNum==0)THEN
    CALL SYSTEM("clear")
    WRITE(*,"(2/,20X,A26)")"* * * Display Record * * *"
    WRITE(*,300,ADVANCE="NO")"Record ", readRecord," not found. ","Would you like to add a new record (Y/N)?"
300 FORMAT(1/,20X,A7,A10,A12,1/,20X,A41,1X)
    READ*,changeOpt
  IF(changeOpt=="Y" .OR. changeOpt=="y") CALL add
    CYCLE
  ELSE
    CALL display
    WRITE(*,400,ADVANCE="NO")"Press ENTER to continue:"
400 FORMAT(1/,20X,A24,1X)
    READ*,
  END IF
END DO
CLOSE(20)
END SUBROUTINE search
</code>```

In the add subroutine, everything up to

```<code>recNum=search(readRecord)
</code>```

is identical to the search subroutine. What I want is a way to take the information entered to

```<code>READ(*,200)readRecord
</code>```

in the search subroutine, somehow temporarily save it, and then once the add subroutine is called, automatically enter it into the

```<code>READ(*,200)readRecord
</code>```

in the add subroutine, so that the user doesn't have to re-enter the record number they want to add.

A way I think this might be accomplished, but I don't know the syntax for would be:

```<code>! WRITE readRecord to some specific place in master.mod
! CALL add

! Once in add:
! At READ(*,200)readRecord, search police.mod to check if it
! has a readRecord already written in it.
! If it does, autofill READ(*,200)readRecord with the readRecord
! from police.mod.
! Then delete readRecord from police.mod (so that if you go directly
! into the add subroutine later, it doesn't autofill a record from a
! previous search).
! If there is no readRecord in police.mod then just prompt for user
! to enter readRecord like in the search subroutine.
</code>```

Any suggestions would be greatly appreciated.

答:
You do not say that clearly, but I assume that by "autofill the READ variable" you want that the string is pre-filled on the screen in the prompt and the user can edit it or just hit Enter.

That is not possible in Fortran with the readstatement. The statement does not work this way and has no such option.

You can achieve similar things with certain libraries. They are usually written in C. You won't be able to use the read statement in them though and they are usually written in C. For example the readline and ncurses libraries. See related
pre-fill stdin in C

What you can do in standard Fortran is to have an if condition and check if the user decided to enter an empty string and use some default previous value if that happened.

Body:
I have a program that has a menu with multiple options (search record, add record, delete record, modify record). What I am trying to do is sort of an autofill function.

Ex: A record number is entered into the search option, but after searching through the database, that record is not found. You are then prompted with the option of searching for a different record number or adding a new record with the variable you just entered. If you choose to add, I want the program to call the add subroutine, and already autofill the read statement with the record you read in to you search subroutine.

This what my code looks like (the search subroutine uses a search function to lookup the record number in master.db, and the display subroutine prints out the results on the screen in a formatted array; both the search and display use a master module with the character and integer variables in the record defined):

SUBROUTINE search
IMPLICIT NONE
CHARACTER::readRecord*10, changeOpt*1
INTEGER::recNum, search

OPEN(20, FILE="master.db", FORM="FORMATTED", ACCESS="DIRECT", RECL=100)
DO
  CALL SYSTEM ("clear")
  WRITE(*,"(2/,20X,A25)")"* * * Search Record * * *"
  WRITE(*,100,ADVANCE="NO")"Please enter a record number or Q to exit:"
100 FORMAT(1/,20X,A42,1X)
  READ(*,200)readRecord
200 FORMAT(A10)

  IF(readSSN=="Q" .OR. readSSN=="q")RETURN
  recNum=search(readRecord)

  IF (recNum==0)THEN
    CALL SYSTEM("clear")
    WRITE(*,"(2/,20X,A26)")"* * * Display Record * * *"
    WRITE(*,300,ADVANCE="NO")"Record ", readRecord," not found. ","Would you like to add a new record (Y/N)?"
300 FORMAT(1/,20X,A7,A10,A12,1/,20X,A41,1X)
    READ*,changeOpt
  IF(changeOpt=="Y" .OR. changeOpt=="y") CALL add
    CYCLE
  ELSE
    CALL display
    WRITE(*,400,ADVANCE="NO")"Press ENTER to continue:"
400 FORMAT(1/,20X,A24,1X)
    READ*,
  END IF
END DO
CLOSE(20)
END SUBROUTINE search

In the add subroutine, everything up to

recNum=search(readRecord)

is identical to the search subroutine. What I want is a way to take the information entered to

READ(*,200)readRecord

in the search subroutine, somehow temporarily save it, and then once the add subroutine is called, automatically enter it into the

READ(*,200)readRecord

in the add subroutine, so that the user doesn't have to re-enter the record number they want to add.

A way I think this might be accomplished, but I don't know the syntax for would be:

! WRITE readRecord to some specific place in master.mod
! CALL add

! Once in add:
! At READ(*,200)readRecord, search police.mod to check if it
! has a readRecord already written in it.
! If it does, autofill READ(*,200)readRecord with the readRecord
! from police.mod.
! Then delete readRecord from police.mod (so that if you go directly
! into the add subroutine later, it doesn't autofill a record from a
! previous search).
! If there is no readRecord in police.mod then just prompt for user
! to enter readRecord like in the search subroutine.

Any suggestions would be greatly appreciated.


答:
my_param should be defined inside the it block or you should use let to define my_param

Inside it block

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        it 'should pass' do
            my_param = [{"job1" => "run"}, {"job2" => "run again"}]

            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end
</code>```

Using let

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end
</code>```

Using before block

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        before(:all) do
          @my_param = [{"job1" => "run"}, {"job2" => "run again"}]
        end

        it 'should pass' do
            test_result = job.run_job(@my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end
</code>```

Title: How to test a method with a parameter using RSpec?

Body:
my_param should be defined inside the it block or you should use let to define my_param

Inside it block

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        it 'should pass' do
            my_param = [{"job1" => "run"}, {"job2" => "run again"}]

            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end

Using let

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end

Using before block

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        before(:all) do
          @my_param = [{"job1" => "run"}, {"job2" => "run again"}]
        end

        it 'should pass' do
            test_result = job.run_job(@my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end


问:
Why isn't my client socket inputstream receiving message sent from server socket outputstream
This is the SocketServer code that generates a server thread

```<code>public class ProcessorCorresponder {
protected final static Logger logger = LogManager.getLogger( ProcessorCorresponder.class );

private static int port = Integer.parseInt(PropertiesLoader.getProperty("appserver.port") == null ? "666" : PropertiesLoader.getProperty("appserver.port"));
private static int maxConnections = Integer.parseInt(PropertiesLoader.getProperty("appserver.maxconnections") == null ? "666" : PropertiesLoader.getProperty("appserver.maxconnections"));

public static void main(String[] args) {
    logger.info("Starting server .. "
            + "[port->" + port
            + ",databaseName->" + databaseName + "]");

    try (ServerSocket listener = new ServerSocket();) {
    listener.setReuseAddress(true);
    listener.bind(new InetSocketAddress(port));
    Socket server;

    int i = 0;

    while((i++ < maxConnections) || (maxConnections == 0)) {
        server = listener.accept();

        logger.debug(
                "New Thread listening on " + server.getLocalAddress().toString() + ":" + server.getLocalPort()
                + ", initiated from IP => " +  server.getInetAddress().toString() + ":" + server.getPort()
                );

        MySocketServer socSrv = new MySocketServer (server);

        Thread t = new Thread( socSrv );
        t.start();
    }
    } catch (Exception ex) {
        logger.error("Error in ProcessorInterface", ex);
    }
}
}
</code>```

Server code: This is a thread to handle one connection, there is a program that monitors a serversocket and spins off request threads as needed.

```<code>public class MySocketServer implements Runnable {
protected final static Logger logger = LogManager.getLogger(MySocketServer.class);

private final Socket server;

// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;

private StringBuffer buffHeartbeatMessage = new StringBuffer().append((char) 0).append((char) 0).append((char) 0)
        .append((char) 0).append((char) 0).append((char) 0);
private Heartbeat heartbeat = new Heartbeat(/* 60 */3000, buffHeartbeatMessage.toString());

public MySocketServer(Socket server) {
    this.server = server;
}

@Override
public void run() {
    try (BufferedReader in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
            BufferedOutputStream out = new HeartbeatBufferedOutputStream(this.server.getOutputStream(),
                    heartbeat)) {

        final StreamListener listener = new StreamListener(in);
        listener.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                if (event.getID() == ActionEvent.ACTION_PERFORMED) {
                    if (event.getActionCommand().equals(StreamListener.ERROR)) {
                        logger.error("Problem listening to stream.");
                        listener.setShouldContinue(false);
                        stopRunning();
                    } else {
                        String messageIn = event.getActionCommand();
                        if (messageIn == null) { // End of Stream;
                            stopRunning();
                        } else { // hey, we can do what we were meant for
                            logger.debug("Request received from client");

                            // doing stuff here
                            ...
                            // done doing stuff

                            logger.debug("Sending Client Response");

                            try {
                                sendResponse(opResponse, out);
                            } catch (Exception ex) {
                                logger.error("Error sending response to OP.", ex);
                            }
                        }
                    }
                }
            }
        });
        listener.start();

        while (shouldContinue) {
            // loop here until shouldContinue = false;
            // this should be set to false in the ActionListener above
        }

        heartbeat.setShouldStop(true);
        return;
    } catch (Exception ex) {
        logger.error("Error in ESPSocketServer", ex);
        return;
    }

}

private void stopRunning() {
    shouldContinue = false;
}

private void sendResponse(ClientResponse opResponse, BufferedOutputStream out) throws Exception {
    logger.debug("Before write");
    out.write(opResponse.getResponse().getBytes());
    logger.debug("After write. Before flush");
    out.flush();
    logger.debug("After flush");
    // this log message is in my logs, so I know the message was sent
}
}
</code>```

My StreamListener class.

```<code>public class StreamListener extends Thread {
protected final static Logger logger = LogManager.getLogger(StreamListener.class);

public final static String ERROR = "ERROR";

private BufferedReader reader = null;
private List<ActionListener> actionListeners = new ArrayList<>();
private boolean shouldContinue = true;

public StreamListener(BufferedReader reader) {
    this.reader = reader;
}

@Override
public void run() {
    while (shouldContinue) {
        String message;
        try {
            // client blocks here and never receives message
            message = reader.readLine();
            ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, message);
            fireActionPerformed(event);
        } catch (IOException e) {
            e.printStackTrace();
            ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ERROR);
            fireActionPerformed(event);
        }
    }
}

public void setShouldContinue(boolean shouldContinue) {
    this.shouldContinue = shouldContinue;
}

public boolean getShouldContinue() {
    return shouldContinue;
}

public boolean addActionListener(ActionListener listener) {
    return actionListeners.add(listener);
}

public boolean removeActionListener(ActionListener listener) {
    return actionListeners.remove(listener);
}

private void fireActionPerformed(ActionEvent event) {
    for (ActionListener listener : actionListeners) {
        listener.actionPerformed(event);
    }
}
}
</code>```

My Heartbeat class

```<code>public class Heartbeat extends Thread {
private BufferedOutputStream bos = null;
private int beatDelayMS = 0;
private String message = null;
private boolean shouldStop = false;

public Heartbeat(int beatDelayMS, String message) {
    this.beatDelayMS = beatDelayMS;
    this.message = message;
    setDaemon(true);
}

@Override
public void run() {
    if (bos == null) { return; }

    while(!shouldStop) {
        try {
            sleep(beatDelayMS);
            try {
                bos.write(message.getBytes());
                bos.flush();
            } catch (IOException ex) {
            //  fall thru
            }
        } catch (InterruptedException ex) {
            if (shouldStop) {
                return;
            }
        }
    }
}

public void setBufferedOutputStream(BufferedOutputStream bos) {
    this.bos = bos;
}

public BufferedOutputStream getBufferedOutputStream() {
    return bos;
}

public void setShouldStop(boolean shouldStop) {
    this.shouldStop = shouldStop;
}

public boolean getShouldStop() {
    return shouldStop;
}
}
</code>```

My HeartbeatBufferedOutputStream

```<code>public class HeartbeatBufferedOutputStream extends BufferedOutputStream {
private Heartbeat heartbeat = null;

public HeartbeatBufferedOutputStream(OutputStream out, Heartbeat heartbeat) {
    super(out);
    this.heartbeat = heartbeat;
    this.heartbeat.setBufferedOutputStream(this);
    heartbeat.start();
}

@Override
public synchronized void flush() throws IOException {
    super.flush();
    heartbeat.interrupt();
}
}
</code>```

And finally here is the "Client" class

```<code>public class Mockup extends Thread {
protected final static Logger logger = LogManager.getLogger(Mockup.class);

// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;

public static void main(String[] args) {
    new Mockup().start();
}

@Override
public void run() {
    try (Socket socket = new Socket("localhost", 16100);
            BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {

        final StreamListener listener = new StreamListener(in);
        listener.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                if (event.getID() == ActionEvent.ACTION_PERFORMED) {
                    if (event.getActionCommand().equals(StreamListener.ERROR)) {
                        logger.error("Problem listening to stream.");
                        listener.setShouldContinue(false);
                        stopRunning();
                    } else {
                        String messageIn = event.getActionCommand();
                        if (messageIn == null) { // End of Stream;
                            stopRunning();
                        } else { // hey, we can do what we were meant for
                            // convert the messageIn to an OrderPower request, this parses the information
                            logger.info("Received message from server. [" + messageIn + "].");
                        }
                    }
                }
            }
        });
        listener.start();

        StringBuffer buff = new StringBuffer("Some message to send to server");

        logger.info("Sending message to server [" + buff.toString() + "]");
        out.write(buff.toString().getBytes());

        out.flush();

        boolean started = false;
        while (shouldContinue) {
            if (!started) {
                logger.debug("In loop");
                started = true;
            }
            // loop here until shouldContinue = false;
            // this should be set to false in the ActionListener above
        }

        logger.info("Exiting Mockup");

        return;
    } catch (Exception ex) {
        logger.error("Error running MockupRunner", ex);
    }
}

private void stopRunning() {
    shouldContinue = false;
}
}
</code>```

I have confirmed from logging messages that the Server sends a message to the BufferedOutputStream, and is flushed, but the Client logs indicate that it is blocked on the reader.readLine() and never gets the message.

答: You are reading lines but you are never writing lines. Add a line terminator to what you send.</p>

Body:
This is the SocketServer code that generates a server thread

public class ProcessorCorresponder {
protected final static Logger logger = LogManager.getLogger( ProcessorCorresponder.class );

private static int port = Integer.parseInt(PropertiesLoader.getProperty("appserver.port") == null ? "666" : PropertiesLoader.getProperty("appserver.port"));
private static int maxConnections = Integer.parseInt(PropertiesLoader.getProperty("appserver.maxconnections") == null ? "666" : PropertiesLoader.getProperty("appserver.maxconnections"));

public static void main(String[] args) {
    logger.info("Starting server .. "
            + "[port->" + port
            + ",databaseName->" + databaseName + "]");

    try (ServerSocket listener = new ServerSocket();) {
    listener.setReuseAddress(true);
    listener.bind(new InetSocketAddress(port));
    Socket server;

    int i = 0;

    while((i++ < maxConnections) || (maxConnections == 0)) {
        server = listener.accept();

        logger.debug(
                "New Thread listening on " + server.getLocalAddress().toString() + ":" + server.getLocalPort()
                + ", initiated from IP => " +  server.getInetAddress().toString() + ":" + server.getPort()
                );

        MySocketServer socSrv = new MySocketServer (server);

        Thread t = new Thread( socSrv );
        t.start();
    }
    } catch (Exception ex) {
        logger.error("Error in ProcessorInterface", ex);
    }
}
}

Server code: This is a thread to handle one connection, there is a program that monitors a serversocket and spins off request threads as needed.

public class MySocketServer implements Runnable {
protected final static Logger logger = LogManager.getLogger(MySocketServer.class);

private final Socket server;

// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;

private StringBuffer buffHeartbeatMessage = new StringBuffer().append((char) 0).append((char) 0).append((char) 0)
        .append((char) 0).append((char) 0).append((char) 0);
private Heartbeat heartbeat = new Heartbeat(/* 60 */3000, buffHeartbeatMessage.toString());

public MySocketServer(Socket server) {
    this.server = server;
}

@Override
public void run() {
    try (BufferedReader in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
            BufferedOutputStream out = new HeartbeatBufferedOutputStream(this.server.getOutputStream(),
                    heartbeat)) {

        final StreamListener listener = new StreamListener(in);
        listener.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                if (event.getID() == ActionEvent.ACTION_PERFORMED) {
                    if (event.getActionCommand().equals(StreamListener.ERROR)) {
                        logger.error("Problem listening to stream.");
                        listener.setShouldContinue(false);
                        stopRunning();
                    } else {
                        String messageIn = event.getActionCommand();
                        if (messageIn == null) { // End of Stream;
                            stopRunning();
                        } else { // hey, we can do what we were meant for
                            logger.debug("Request received from client");

                            // doing stuff here
                            ...
                            // done doing stuff

                            logger.debug("Sending Client Response");

                            try {
                                sendResponse(opResponse, out);
                            } catch (Exception ex) {
                                logger.error("Error sending response to OP.", ex);
                            }
                        }
                    }
                }
            }
        });
        listener.start();

        while (shouldContinue) {
            // loop here until shouldContinue = false;
            // this should be set to false in the ActionListener above
        }

        heartbeat.setShouldStop(true);
        return;
    } catch (Exception ex) {
        logger.error("Error in ESPSocketServer", ex);
        return;
    }

}

private void stopRunning() {
    shouldContinue = false;
}

private void sendResponse(ClientResponse opResponse, BufferedOutputStream out) throws Exception {
    logger.debug("Before write");
    out.write(opResponse.getResponse().getBytes());
    logger.debug("After write. Before flush");
    out.flush();
    logger.debug("After flush");
    // this log message is in my logs, so I know the message was sent
}
}

My StreamListener class.

public class StreamListener extends Thread {
protected final static Logger logger = LogManager.getLogger(StreamListener.class);

public final static String ERROR = "ERROR";

private BufferedReader reader = null;
private List<ActionListener> actionListeners = new ArrayList<>();
private boolean shouldContinue = true;

public StreamListener(BufferedReader reader) {
    this.reader = reader;
}

@Override
public void run() {
    while (shouldContinue) {
        String message;
        try {
            // client blocks here and never receives message
            message = reader.readLine();
            ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, message);
            fireActionPerformed(event);
        } catch (IOException e) {
            e.printStackTrace();
            ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ERROR);
            fireActionPerformed(event);
        }
    }
}

public void setShouldContinue(boolean shouldContinue) {
    this.shouldContinue = shouldContinue;
}

public boolean getShouldContinue() {
    return shouldContinue;
}

public boolean addActionListener(ActionListener listener) {
    return actionListeners.add(listener);
}

public boolean removeActionListener(ActionListener listener) {
    return actionListeners.remove(listener);
}

private void fireActionPerformed(ActionEvent event) {
    for (ActionListener listener : actionListeners) {
        listener.actionPerformed(event);
    }
}
}

My Heartbeat class

public class Heartbeat extends Thread {
private BufferedOutputStream bos = null;
private int beatDelayMS = 0;
private String message = null;
private boolean shouldStop = false;

public Heartbeat(int beatDelayMS, String message) {
    this.beatDelayMS = beatDelayMS;
    this.message = message;
    setDaemon(true);
}

@Override
public void run() {
    if (bos == null) { return; }

    while(!shouldStop) {
        try {
            sleep(beatDelayMS);
            try {
                bos.write(message.getBytes());
                bos.flush();
            } catch (IOException ex) {
            //  fall thru
            }
        } catch (InterruptedException ex) {
            if (shouldStop) {
                return;
            }
        }
    }
}

public void setBufferedOutputStream(BufferedOutputStream bos) {
    this.bos = bos;
}

public BufferedOutputStream getBufferedOutputStream() {
    return bos;
}

public void setShouldStop(boolean shouldStop) {
    this.shouldStop = shouldStop;
}

public boolean getShouldStop() {
    return shouldStop;
}
}

My HeartbeatBufferedOutputStream

public class HeartbeatBufferedOutputStream extends BufferedOutputStream {
private Heartbeat heartbeat = null;

public HeartbeatBufferedOutputStream(OutputStream out, Heartbeat heartbeat) {
    super(out);
    this.heartbeat = heartbeat;
    this.heartbeat.setBufferedOutputStream(this);
    heartbeat.start();
}

@Override
public synchronized void flush() throws IOException {
    super.flush();
    heartbeat.interrupt();
}
}

And finally here is the "Client" class

public class Mockup extends Thread {
protected final static Logger logger = LogManager.getLogger(Mockup.class);

// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;

public static void main(String[] args) {
    new Mockup().start();
}

@Override
public void run() {
    try (Socket socket = new Socket("localhost", 16100);
            BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {

        final StreamListener listener = new StreamListener(in);
        listener.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                if (event.getID() == ActionEvent.ACTION_PERFORMED) {
                    if (event.getActionCommand().equals(StreamListener.ERROR)) {
                        logger.error("Problem listening to stream.");
                        listener.setShouldContinue(false);
                        stopRunning();
                    } else {
                        String messageIn = event.getActionCommand();
                        if (messageIn == null) { // End of Stream;
                            stopRunning();
                        } else { // hey, we can do what we were meant for
                            // convert the messageIn to an OrderPower request, this parses the information
                            logger.info("Received message from server. [" + messageIn + "].");
                        }
                    }
                }
            }
        });
        listener.start();

        StringBuffer buff = new StringBuffer("Some message to send to server");

        logger.info("Sending message to server [" + buff.toString() + "]");
        out.write(buff.toString().getBytes());

        out.flush();

        boolean started = false;
        while (shouldContinue) {
            if (!started) {
                logger.debug("In loop");
                started = true;
            }
            // loop here until shouldContinue = false;
            // this should be set to false in the ActionListener above
        }

        logger.info("Exiting Mockup");

        return;
    } catch (Exception ex) {
        logger.error("Error running MockupRunner", ex);
    }
}

private void stopRunning() {
    shouldContinue = false;
}
}

I have confirmed from logging messages that the Server sends a message to the BufferedOutputStream, and is flushed, but the Client logs indicate that it is blocked on the reader.readLine() and never gets the message.


问:
how to get table cell value while Parsing with XPath, and the cell contain value like <19.00 OR >23.99
actually i need to parse a HTML table and that table contains HTML character, you can see in image.

i need each cell data with that special character also. Right now when i am parsing the table with XPath its ignore that cell and returns that cell value as empty.

Both Image attached here.

```<code>$table_head = $summary_nodes->childNodes->item(0);
$table_body = $summary_nodes->childNodes->item(1);
$head = [];
$body = [];
// print_r($table_head);
foreach($table_head->childNodes as $h_index => $h_node){
    $head_temp = [];
    foreach($h_node->childNodes as $cell_index => $cell){
        $head_temp[] = trim($cell->nodeValue);
    }
    $head[] = $head_temp;
}
foreach($table_body->childNodes as $b_index => $b_node){
    $body_temp = [];
    // print_r($b_node);
    foreach($b_node->childNodes as $cell_index => $cell){
        print_r($cell);
        $body_temp[] = trim($cell->nodeValue);
    }
    $body[] = $body_temp;
}
return ['table_ready'=>array_merge([$head[count($head)-1]], $body), 'headers'=> $head];
</code>```

答: Hello friends I got answer for this, actually what is happening we are adding HTML entity inside our real data that's why while passing it's conflicting with HTML content and while parsing parser remove automatically that HTML entities so we have to make sure our real data does not have any HTML entities if we are using or if we need any entity which is similar to HTML entity please try to use they are HTML entity code.</p>

Body:
actually i need to parse a HTML table and that table contains HTML character, you can see in image.

i need each cell data with that special character also. Right now when i am parsing the table with XPath its ignore that cell and returns that cell value as empty.

Both Image attached here.

$table_head = $summary_nodes->childNodes->item(0);
$table_body = $summary_nodes->childNodes->item(1);
$head = [];
$body = [];
// print_r($table_head);
foreach($table_head->childNodes as $h_index => $h_node){
    $head_temp = [];
    foreach($h_node->childNodes as $cell_index => $cell){
        $head_temp[] = trim($cell->nodeValue);
    }
    $head[] = $head_temp;
}
foreach($table_body->childNodes as $b_index => $b_node){
    $body_temp = [];
    // print_r($b_node);
    foreach($b_node->childNodes as $cell_index => $cell){
        print_r($cell);
        $body_temp[] = trim($cell->nodeValue);
    }
    $body[] = $body_temp;
}
return ['table_ready'=>array_merge([$head[count($head)-1]], $body), 'headers'=> $head];


问:
How to solve this SQL query
There are 3 tables: item, grp and grp_rel.

item table:

```<code>item_id     title
</code>```

grp table:

```<code>grp_id      title
</code>```

grp_rel table:

```<code>grp_id      item_id
</code>```

Data in table (item table): item title is varchar(255), not unique

```<code>1       item-a
2       item-b
3       title-c
4       item-d
5       title-c
6       value-e
7       value-e
</code>```

Data in table (grp table): grp title is varchar(255), not unique.

```<code>1   title
2   value
</code>```

Data in table (grp_rel table):

```<code>1   3
1   5
2   6
2   7
</code>```

Expected sql result is (order by item title):

```<code>item_id     grp_id  title       grp_title
1           NULL    item-a      NULL
2           NULL    item-b      NULL
3           1       title-c     title
4           NULL    item-d      NULL
6           2       value-e     value
</code>```

答:
Simple left join will do the job for you.

```<code>SELECT
      I.item_id,
      G.grp_id,
      I.title,
      G.title
FROM
      item I
LEFT JOIN
      grp_rel GR
      ON GR.item_id = I.item_id
LEFT JOIN
      grp G
      ON G.grp_id = GR.grp_id
ORDER BY
      I.title
</code>```

SQL Fiddle

Title: How to solve this SQL query

Body:
There are 3 tables: item, grp and grp_rel.

item table:

item_id     title

grp table:

grp_id      title

grp_rel table:

grp_id      item_id

Data in table (item table): item title is varchar(255), not unique

1       item-a
2       item-b
3       title-c
4       item-d
5       title-c
6       value-e
7       value-e

Data in table (grp table): grp title is varchar(255), not unique.

1   title
2   value

Data in table (grp_rel table):

1   3
1   5
2   6
2   7

Expected sql result is (order by item title):

item_id     grp_id  title       grp_title
1           NULL    item-a      NULL
2           NULL    item-b      NULL
3           1       title-c     title
4           NULL    item-d      NULL
6           2       value-e     value

Body:
Simple left join will do the job for you.

SELECT
      I.item_id,
      G.grp_id,
      I.title,
      G.title
FROM
      item I
LEFT JOIN
      grp_rel GR
      ON GR.item_id = I.item_id
LEFT JOIN
      grp G
      ON G.grp_id = GR.grp_id
ORDER BY
      I.title

SQL Fiddle


问:
How to show a tooltip on button click using Angular1
I have designed a tooltip using only html and css.I cannot use bootstarp.Below is my code for tooltip.

```<code><div class="box">
  <h3>Tooltip</h3>
</div>

    h3 {
        text-align:center;
        line-height:33px;
    }

    div.box {
        height:100px;
        width:200px;
        background-color:#eee;
        border:1px solid #aaa;
        position:relative;
        top:50px;
        left:50px;
        border-radius:7px;
    }

    .box:before {
        position:absolute;
        right:-20px;
        top:5px;
        content:'';
        height:0;
        width:0;
        border:10px solid transparent;
        z-index:1;
    }

    .box:after{
        position:absolute;
        right:-17px;
        top:25px;
        content:'';
        height:0;
        width:0;
        border-top: 8px solid transparent;
        border-left: 8px solid #aaa;
        border-right: 8px solid transparent;
        border-bottom: 8px solid transparent;
        z-index:1;
    }
</code>```

The tooltip is working.But i want this tooltip to come on button click that is on ng-click as i am using Angular1.
Can anyone please help me how to do this.I am very new to Angular1.

答:
first add a ng-show to your tooltip

```<code><div class="box" ng-show="displayTooltip">
  <h3>Tooltip</h3>
</div>
</code>```

and add ng-click to your button to make displayTooltip true

```<code>ng-click="displayTooltip = true"
</code>```

if you want to make tooltip invisible on button click use

```<code>ng-click="displayTooltip = !displayTooltip"
</code>```

or if you want to make it invisible on mouseleavevent use

```<code>ng-mouseleave="displayTooltip = false"
</code>```

Body:
I have designed a tooltip using only html and css.I cannot use bootstarp.Below is my code for tooltip.

Tooltip

    h3 {
        text-align:center;
        line-height:33px;
    }

    div.box {
        height:100px;
        width:200px;
        background-color:#eee;
        border:1px solid #aaa;
        position:relative;
        top:50px;
        left:50px;
        border-radius:7px;
    }

    .box:before {
        position:absolute;
        right:-20px;
        top:5px;
        content:'';
        height:0;
        width:0;
        border:10px solid transparent;
        z-index:1;
    }

    .box:after{
        position:absolute;
        right:-17px;
        top:25px;
        content:'';
        height:0;
        width:0;
        border-top: 8px solid transparent;
        border-left: 8px solid #aaa;
        border-right: 8px solid transparent;
        border-bottom: 8px solid transparent;
        z-index:1;
    }

The tooltip is working.But i want this tooltip to come on button click that is on ng-click as i am using Angular1.
Can anyone please help me how to do this.I am very new to Angular1.

Body:
first add a ng-show to your tooltip

<div class="box" ng-show="displayTooltip">
  <h3>Tooltip</h3>
</div>

and add ng-click to your button to make displayTooltip true

ng-click="displayTooltip = true"

if you want to make tooltip invisible on button click use

ng-click="displayTooltip = !displayTooltip"

or if you want to make it invisible on mouseleavevent use

ng-mouseleave="displayTooltip = false"


问:
How can I move file into Recycle Bin / trash on different platforms using PyQt4?
I would like to add the next feature to my cross-platform PyQt4 application: when user selects some file and select "remove" action on it that file will be moved to Recycle Bin folder instead of being permantly removed. I think I can find Windows-specific solution using Win32 API or something similar, but I'd like to know does similar operation could be executed on Ubuntu/Linux and MaxOSX as well via PyQt4 methods.</p>

答:
The best OSX solution I know uses Applescript. I did not, however, invent it, so I shall simply link to it here.

It would be nice to have a module that packaged up the Win32/KDE/OSX solutions into one, i feel, and imported the correct one on demand. Is that how you solved your problem in the end?


问:
Auth guard not working in angular 5
Here is my static login service

```<code>login(email: string, password: string) {
debugger;
const user = {
  username: email,
  password: password,

};
if (email === "admin" && password === "admin") {
  localStorage.setItem("currentUser", JSON.stringify(user));
}
if (localStorage.getItem("currentUser")) {
  // logged in so return true
  return user;
} else {
  return false;
}
}
</code>```

My authguard service

```<code>  export class AuthGuard implements CanActivate {
  constructor(private router: Router) {

  }
        isAuthenticated(): boolean{
      if (localStorage.getItem("currentUser")) {
        return true;
      }
      else{
        return false;
      }
    }

    canActivate(): boolean {
      if (!this.isAuthenticated()) {
        this.router.navigate(['login']);
        return false;
      }
      return true;
    }
}
</code>```

my app.routing.ts

```<code>const appRoutes: Routes = [
  { path: "home", component: HomeComponent ,canActivate: [AuthGuard]},
  { path: "login", component: AuthComponent },
  { path: "", component: AuthComponent },
  { path: "employees", component: EmpComponent,canActivate: [AuthGuard] },
  // otherwise redirect to home
  { path: "**", redirectTo: "/" }
];
</code>```

app.module.ts

```<code>@NgModule({
  declarations: [AppComponent, HeaderComponent, FooterComponent],
  imports: [
    BrowserModule,
    FormsModule,
    SharedModule,
    HomeModule,
    AuthModule,
    EmpModule,
    routing,
    Ng4LoadingSpinnerModule,
    AlertModule.forRoot()
  ],
  providers: [AuthGuard, AuthenticationService],
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
  bootstrap: [AppComponent]
})
</code>```

I just tested this by entering a route directly in browser url for example /home which has canactivate enabled in its route config but when i do so the home contents are displayed instead of redirecting to the login page.Need too know what's wrong here any help will be really appreciated thanks in advance :)

答: There is no issue with your current code, if you have routing for each component separately, remove them and have them only in the app.module.ts

Title: Auth guard not working in angular 5

Body:
Here is my static login service

login(email: string, password: string) {
debugger;
const user = {
  username: email,
  password: password,

};
if (email === "admin" && password === "admin") {
  localStorage.setItem("currentUser", JSON.stringify(user));
}
if (localStorage.getItem("currentUser")) {
  // logged in so return true
  return user;
} else {
  return false;
}
}

My authguard service

  export class AuthGuard implements CanActivate {
  constructor(private router: Router) {

  }
        isAuthenticated(): boolean{
      if (localStorage.getItem("currentUser")) {
        return true;
      }
      else{
        return false;
      }
    }

    canActivate(): boolean {
      if (!this.isAuthenticated()) {
        this.router.navigate(['login']);
        return false;
      }
      return true;
    }
}

my app.routing.ts

const appRoutes: Routes = [
  { path: "home", component: HomeComponent ,canActivate: [AuthGuard]},
  { path: "login", component: AuthComponent },
  { path: "", component: AuthComponent },
  { path: "employees", component: EmpComponent,canActivate: [AuthGuard] },
  // otherwise redirect to home
  { path: "**", redirectTo: "/" }
];

app.module.ts

@NgModule({
  declarations: [AppComponent, HeaderComponent, FooterComponent],
  imports: [
    BrowserModule,
    FormsModule,
    SharedModule,
    HomeModule,
    AuthModule,
    EmpModule,
    routing,
    Ng4LoadingSpinnerModule,
    AlertModule.forRoot()
  ],
  providers: [AuthGuard, AuthenticationService],
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
  bootstrap: [AppComponent]
})

I just tested this by entering a route directly in browser url for example /home which has canactivate enabled in its route config but when i do so the home contents are displayed instead of redirecting to the login page.Need too know what's wrong here any help will be really appreciated thanks in advance :)