问:
How to pass body in post request fetch api call in React Native
My url if opened on browser gives the following error:(attached image)

Body of my api call looks like below :

```<code>{
      "entityId": 4071,
      "listViewId": 0,
      "asLookup": false,
      "retrieveAllFields": true,
      "fullTextSearch": "",
      "query": [

      ],
      "pagination": {
        "pageNumber": 0,
        "recordsCountPerPage": 0
      },
      "sorting": {
        "fieldId": 0,
        "direction": 0
      }
    }
</code>```

I am calling api in react native using fetch below :

```<code> try {
            let response = await fetch('url', {
                method: 'POST',
                headers: {
                    'tenantid': '1',
                    'Content-Type': 'application/json',
                    'language': '0',

                },
                body: JSON.stringify({

                    entityId: 4071,
                    listViewId: 0,
                    asLookup: false,
                    retrieveAllFields: true,
                    fullTextSearch: "",
                    query: [

                    ],
                    pagination: {
                        pageNumber: 0,
                        recordsCountPerPage: 0
                    },
                    sorting: {
                        fieldId: 0,
                        direction: 0
                    }

                })
            })
      let json = await response.json();
      console.log("This is response" + json)
      this.setState({records: json.results, isFetching:false});
    }catch(error){
      this.setState({errorMessage:error})
      console.log("This is error"+error)
    }
</code>```

This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!

答:
did you use the correct url ?

it should looks like something like this

```<code>fetch('https://mywebsite.com/endpoint/', {
       method: 'POST',
       headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
       },
      body: JSON.stringify({
                firstParam: 'yourValue',
                secondParam: 'yourOtherValue'})
      }).then((response) => response.json())
      .then((responseJson) => {
                console.log(responseJson);
     });
</code>```

maybe you should look on the documentations
https://reactnative.dev/docs/network

Body:
My url if opened on browser gives the following error:(attached image)

Body of my api call looks like below :

{
      "entityId": 4071,
      "listViewId": 0,
      "asLookup": false,
      "retrieveAllFields": true,
      "fullTextSearch": "",
      "query": [

      ],
      "pagination": {
        "pageNumber": 0,
        "recordsCountPerPage": 0
      },
      "sorting": {
        "fieldId": 0,
        "direction": 0
      }
    }

I am calling api in react native using fetch below :

 try {
            let response = await fetch('url', {
                method: 'POST',
                headers: {
                    'tenantid': '1',
                    'Content-Type': 'application/json',
                    'language': '0',

                },
                body: JSON.stringify({

                    entityId: 4071,
                    listViewId: 0,
                    asLookup: false,
                    retrieveAllFields: true,
                    fullTextSearch: "",
                    query: [

                    ],
                    pagination: {
                        pageNumber: 0,
                        recordsCountPerPage: 0
                    },
                    sorting: {
                        fieldId: 0,
                        direction: 0
                    }

                })
            })
      let json = await response.json();
      console.log("This is response" + json)
      this.setState({records: json.results, isFetching:false});
    }catch(error){
      this.setState({errorMessage:error})
      console.log("This is error"+error)
    }

This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!

Body:
did you use the correct url ?

it should looks like something like this

fetch('https://mywebsite.com/endpoint/', {
       method: 'POST',
       headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
       },
      body: JSON.stringify({
                firstParam: 'yourValue',
                secondParam: 'yourOtherValue'})
      }).then((response) => response.json())
      .then((responseJson) => {
                console.log(responseJson);
     });

maybe you should look on the documentations
https://reactnative.dev/docs/network


来源: stackexchange

问:
Covert ISO Date String to x days/minutes ago
I want to convert a timestamp (e.g. 2020-05-01T07:28:02.657Z) to a timestamp that is 1 day or 1 minute prior.

Can someone help me fix this JavaScript function to get the desired output

```<code>aDay = '2020-05-01T07:28:02.657Z'
function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
      return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
      return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
      return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
      return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
      return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
  }
  console.log(timeSince(new Date(Date.now()- aDay)));
</code>```

答:
I recommend using MomentJS (https://momentjs.com/), a simple date / time management library : </p>

```<code>const timeAgo = moment("2020-05-01T07:28:02.657Z").fromNow();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to convert a timestamp (e.g. 2020-05-01T07:28:02.657Z) to a timestamp that is 1 day or 1 minute prior.

Can someone help me fix this JavaScript function to get the desired output

aDay = '2020-05-01T07:28:02.657Z'
function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
      return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
      return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
      return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
      return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
      return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
  }
  console.log(timeSince(new Date(Date.now()- aDay)));

Body:
I recommend using MomentJS (https://momentjs.com/), a simple date / time management library :

const timeAgo = moment("2020-05-01T07:28:02.657Z").fromNow();


问:
Invalid character at window.onerror reported in Azure Application Insights; ASP.Net Web Application
We just enabled Azure Application Insights for our ASP.Net web application.  The site is hosted through Windows Server 2012 VM on IIS 8 in Azure.  We enabled client side telemetry to detect browser errors on the client side.  We've seen a bunch of these errors pop up:

```<code>"Invalid character"
"Invalid character at window.onerror"
Call Stack:
window.onerror@https://www.mywebsite.com/login/:79:32
</code>```

Our website doesn't get a ton of traffic but this error has been recorded over 400 times in the last 24 hours.

The last two characters :79:32 vary a bit between errors but they always end in :32.  I'm guessing these are ASCII characters, but I do not know why these errors showing up.  Also, the URL path isn't always the same which means it is happening on more than just our 'login' page.

Azure Insights DOES indicate that ALL clients experiencing this error are using Internet Explorer 11.

I verified that our web application doesn't call window.onerror anywhere.

So my question is, should I be concerned about this error?  Is it some kind of compatibility with IE11?

答:
You are right, it is just some kind of compatibility issue with IE11.

Window.onerror has been available in browsers for some time, even we can find it in browsers as old as IE6 and Firefox2. However, the problem is that every browser implements windows.onerror differently, particularly in how many arguments are sent to the onerror listener and the structure of those arguments, which cause a similar error with yours.

Please refer to the following link.

https://dzone.com/articles/capture-and-report-javascript-errors-with-windowon

Now that we have known that certain Javascript is not compatible with some kind of old browser, I think this is not the problem we concern about. It is just an error that occurred on the client-side, not affecting the operation of the application.

Body:
We just enabled Azure Application Insights for our ASP.Net web application.  The site is hosted through Windows Server 2012 VM on IIS 8 in Azure.  We enabled client side telemetry to detect browser errors on the client side.  We've seen a bunch of these errors pop up:

"Invalid character"
"Invalid character at window.onerror"
Call Stack:
window.onerror@https://www.mywebsite.com/login/:79:32

Our website doesn't get a ton of traffic but this error has been recorded over 400 times in the last 24 hours.

The last two characters :79:32 vary a bit between errors but they always end in :32.  I'm guessing these are ASCII characters, but I do not know why these errors showing up.  Also, the URL path isn't always the same which means it is happening on more than just our 'login' page.

Azure Insights DOES indicate that ALL clients experiencing this error are using Internet Explorer 11.

I verified that our web application doesn't call window.onerror anywhere.

So my question is, should I be concerned about this error?  Is it some kind of compatibility with IE11?


问:
Iterate over every possible n-sampling of a list
If I understand itertools "combinatoric iterators" doc correctly, the idea is to provide a set of standard functions for every common combinatory iteration.

But I miss one today. I need to iterate over every ordered combinations of items with repetitions.

combination_with_replacement('abcd', 4) yields

```<code>('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'a', 'c')
('a', 'a', 'a', 'd')
('a', 'a', 'b', 'b')
('a', 'a', 'b', 'c')
('a', 'a', 'b', 'd')
('a', 'a', 'c', 'c')
('a', 'a', 'c', 'd')
... etc
</code>```

but (even though the results are sorted tuples), these combinations are not ordered.

I expect more results from an ideal ordered_combination_with_replacement('abcd', 4) for I need to distinguish between

```<code>('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'b', 'a')
('a', 'b', 'a', 'a')
('b', 'a', 'a', 'a')
('a', 'a', 'a', 'c')
('a', 'a', 'c', 'a')
... etc
</code>```

In other words: order matters today.

Does itertool provide such an iteration? Why not, or why have I missed it?

What's a standard way to iterate over those?

Do I need to write this generic iterator myself?

答:
To wrap up some of the comments, there are (at least) two ways to do that:

```<code>itertools.combinations_with_replacement("abcd", 4)
</code>```

and

```<code>itertools.product("abcd", repeat=4)
</code>```

Both produce the required results of:

```<code>[('a', 'a', 'a', 'a'),
 ('a', 'a', 'a', 'b'),
 ('a', 'a', 'a', 'c'),
 ('a', 'a', 'a', 'd'),
 ('a', 'a', 'b', 'a'),
 ...
</code>```

Body:
If I understand itertools "combinatoric iterators" doc correctly, the idea is to provide a set of standard functions for every common combinatory iteration.

But I miss one today. I need to iterate over every ordered combinations of items with repetitions.

combination_with_replacement('abcd', 4) yields

('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'a', 'c')
('a', 'a', 'a', 'd')
('a', 'a', 'b', 'b')
('a', 'a', 'b', 'c')
('a', 'a', 'b', 'd')
('a', 'a', 'c', 'c')
('a', 'a', 'c', 'd')
... etc

but (even though the results are sorted tuples), these combinations are not ordered.

I expect more results from an ideal ordered_combination_with_replacement('abcd', 4) for I need to distinguish between

('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'b', 'a')
('a', 'b', 'a', 'a')
('b', 'a', 'a', 'a')
('a', 'a', 'a', 'c')
('a', 'a', 'c', 'a')
... etc

In other words: order matters today.

Does itertool provide such an iteration? Why not, or why have I missed it?

What's a standard way to iterate over those?

Do I need to write this generic iterator myself?

Body:
To wrap up some of the comments, there are (at least) two ways to do that:

itertools.combinations_with_replacement("abcd", 4)

and

itertools.product("abcd", repeat=4)

Both produce the required results of:

[('a', 'a', 'a', 'a'),
 ('a', 'a', 'a', 'b'),
 ('a', 'a', 'a', 'c'),
 ('a', 'a', 'a', 'd'),
 ('a', 'a', 'b', 'a'),
 ...


答:
aDay is a string but you're treating it like a Date. The format is about the only one that is supported by ECMA-262 and browsers in use, so you can use:

```<code>let aDay = new Date('2020-05-01T07:28:02.657Z');
</code>```

The timeSince function seems to want a Date, you're passing it a number that is the difference in time values between two dates, just pass it aDay as a Date:

function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

let aDay = '2020-05-01T07:28:02.657Z'
console.log(timeSince(new Date(aDay)));```

That kind of expression is typically called a "friendly date", however many users (me included) don't like them at all and much prefer to see the actual date.

Title: Covert ISO Date String to x days/minutes ago

Body:
aDay is a string but you're treating it like a Date. The format is about the only one that is supported by ECMA-262 and browsers in use, so you can use:

let aDay = new Date('2020-05-01T07:28:02.657Z');

The timeSince function seems to want a Date, you're passing it a number that is the difference in time values between two dates, just pass it aDay as a Date:

function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

let aDay = '2020-05-01T07:28:02.657Z'
console.log(timeSince(new Date(aDay)));

That kind of expression is typically called a "friendly date", however many users (me included) don't like them at all and much prefer to see the actual date.


问:
Access Storage.DIRECTORY_DOWNLOADS (Root/Download Folder To View a file)
This Method is Not Working To Read a Downloaded File

```<code>File localFile = new File(Storage.DIRECTORY_DOWNLOADS + downloadableFileName);
</code>```

Nor this also Working

```<code>File localFile = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + downloadableFileName);
</code>```

Files Are Downloaded to Root/Download folder Not to App Specific Folder

Can Any One Help

The Download Method is

```<code>    protected Void doInBackground(String... strings) {
        String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
        String filename = strings[1];
        String extStorageDirectory = Storage.DIRECTORY_DOWNLOADS;

        File folder = new File(extStorageDirectory);
        folder.mkdir();
        initClipboardDownloadListener(filename);
        Downloader request = Downloader.getInstance(getActivity())
                .setListener(downloadListener)
                .setUrl(fileUrl)
                .setToken(fileUrl)
                .setAllowedOverRoaming(true)
                .setVisibleInDownloadsUi(true)
                .setDescription("Downloading....")
                .setKeptAllDownload(true)
                .setScanningByMediaScanner(false)
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                .setDestinationDir(extStorageDirectory, filename)
                .setNotificationTitle(filename);
        request.setAllowedOverMetered(true);
        request.start();
        return null;
    }
</code>```

答:
Try this:</p>

```<code>...
String path = Environment.getExternalStorageDirectory().toString() +"/Download/" + fileName;
File file = new File(path);
...
</code>```

Body:
This Method is Not Working To Read a Downloaded File

File localFile = new File(Storage.DIRECTORY_DOWNLOADS + downloadableFileName);

Nor this also Working

File localFile = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + downloadableFileName);

Files Are Downloaded to Root/Download folder Not to App Specific Folder

Can Any One Help

The Download Method is

    protected Void doInBackground(String... strings) {
        String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
        String filename = strings[1];
        String extStorageDirectory = Storage.DIRECTORY_DOWNLOADS;

        File folder = new File(extStorageDirectory);
        folder.mkdir();
        initClipboardDownloadListener(filename);
        Downloader request = Downloader.getInstance(getActivity())
                .setListener(downloadListener)
                .setUrl(fileUrl)
                .setToken(fileUrl)
                .setAllowedOverRoaming(true)
                .setVisibleInDownloadsUi(true)
                .setDescription("Downloading....")
                .setKeptAllDownload(true)
                .setScanningByMediaScanner(false)
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                .setDestinationDir(extStorageDirectory, filename)
                .setNotificationTitle(filename);
        request.setAllowedOverMetered(true);
        request.start();
        return null;
    }

Body:
Try this:

...
String path = Environment.getExternalStorageDirectory().toString() +"/Download/" + fileName;
File file = new File(path);
...


问:
Location of Azure AD session tokens
I am reading on the Single Sign on using Azure AD.I wanted to know where the SSO Session tokens are being stored.
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes

The reason being is that I have a web application which uses SSO authentication on Azure AD. It never prompts for credentials even after clearing the local storage and cookies. So wanted to know where these session tokens are being stored.

答:
Sessions in Azure AD are usually stored in cookies that are stored in your browser for the Azure AD domain.

You can clear the single sign-on session by redirecting the user to log out at Azure AD's signout endpoint.
See: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request

Title: Location of Azure AD session tokens


问:
How to intentionally delete a boost::shared_ptr?
I have many boost::shared_ptr<MyClass> objects, and at some point I intentionally want to delete some of them to free some memory. (I know at that point that I will never need the pointed-to MyClass objects anymore.) How can I do that?

I guess you can't just call delete() with the raw pointer that I get with get().

I've seen a function get_deleter(shared_ptr<T> const & p) in boost::shared_ptr, but I'm not sure how to use it, and also it says experimental right next to it. (I think I have Boost 1.38.)

Maybe just assign a new empty boost::shared_ptr to the variable? That should throw away the old value and delete it.

答:
The whole point of boost::shared_ptr<T> is that the pointee object will be deleted exactly at the moment when no shared_ptr<T>s point at it -- that is, when the last shared_ptr<T> pointing at this object goes out of scope or is reassigned to point to a different object.  So, all you have to do to delete an object is make sure there are no shared_ptr<T>s pointing at it.  E.g. if you only have a single shared_ptr<T> called p pointing at an object, either let it fall out of scope, or call p.reset() (equivalent to p = NULL for a plain pointer), or assign it to point at something else.

If you have two shared_ptr<T>s pointing at the object, you'll need to reassign both of them.

EDIT: Thanks to dehmann for pointing out that p = NULL; is not actually valid code for a shared_ptr<T>... :)

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Paypal IPN INVALID message When has special chacracters
When I do a payment by credit card on paypal sandbox, I fill some special characters (ex: !@#@%^&) on address 1/address 2 text fields.
After payment, I get a IPN message, post back to PP and receive a INVALID message (HTTP error 200).

I set UTF-8 on profile/language on PP. But the problem is still there.

Remark: The payment process works fine if I pays by using PP account (means log in and click payment button).

答:
You have to be careful to send to Paypal the exact data you received in the IPN call, with the notable exception of the cmd parameter, which has to be set to _notify-validate.

Here is some PHP code that takes the raw POST data, parses it to an array, changes the cmd parameter, converts it back to POST data, and sends it to Paypal. Getting the raw POST data allows to bypass PHP's built-in parsing, which may apply messy things such as magic quotes, depending on your configuration.

```<code>$post = file_get_contents('php://input');
parse_str($post, $data);
$data['cmd'] = '_notify-validate';
$post = http_build_query($data);

$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$result = curl_exec($ch);
curl_close($ch);

if ($result == 'VERIFIED') {
    // process the payment
}
</code>```

Body:
You have to be careful to send to Paypal the exact data you received in the IPN call, with the notable exception of the cmd parameter, which has to be set to _notify-validate.

Here is some PHP code that takes the raw POST data, parses it to an array, changes the cmd parameter, converts it back to POST data, and sends it to Paypal. Getting the raw POST data allows to bypass PHP's built-in parsing, which may apply messy things such as magic quotes, depending on your configuration.

$post = file_get_contents('php://input');
parse_str($post, $data);
$data['cmd'] = '_notify-validate';
$post = http_build_query($data);

$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$result = curl_exec($ch);
curl_close($ch);

if ($result == 'VERIFIED') {
    // process the payment
}


问:
How to transfer data from one time open activity to next
I am new to android!.
I have made spinner in activity 1 (one time open Activity) and want to transfer selected value from spinner  by user to activity 2.I have used sharedPreference for one time open activity .Its only working 1st time but second time it cant transfer data.I am stuck here please help me </p>

```<code>    SharedPreferences Preferences=getSharedPreferences("PREFERENCE",MODE_PRIVATE);
    String FirstTime=Preferences.getString("FirstTimeInstall","");

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

            String parent=sp_parent.getSelectedItem().toString();
            String child=sp_child.getSelectedItem().toString();
            String college=sp_college.getSelectedItem().toString();

            Intent intent=new Intent(getApplicationContext(),Dashboard.class);
            intent.putExtra("parent",parent);
            intent.putExtra("child",child);
            intent.putExtra("college",college);
            startActivity(intent);
            finish();

        }
    });

            if (FirstTime.equals("Yes")){
            String parent=sp_parent.getSelectedItem().toString();
            String child=sp_child.getSelectedItem().toString();
            String college=sp_college.getSelectedItem().toString();

        Intent intent=new Intent(getApplicationContext(),Dashboard.class);
            intent.putExtra("parent",parent);
            intent.putExtra("child",child);
            intent.putExtra("college",college);
        startActivity(intent);
        finish();

    }else {
        SharedPreferences.Editor editor=Preferences.edit();
        editor.putString("FirstTimeInstall","Yes");
        editor.apply();
    }
</code>```

答:
When starting a new activity you can send data through intent.

```<code>Intent intent = new Intent( this, Activity2.class );
intent.putExtra( "key", "value" );
startActivity(intent)
</code>```

And in second activity do like this:

```<code>getIntent().getStringExtra( "key" );
</code>```

or if you are sending int for example

```<code>getIntent().getIntExtra( "key", 0 );
</code>```

Body:
I am new to android!.
I have made spinner in activity 1 (one time open Activity) and want to transfer selected value from spinner  by user to activity 2.I have used sharedPreference for one time open activity .Its only working 1st time but second time it cant transfer data.I am stuck here please help me

    SharedPreferences Preferences=getSharedPreferences("PREFERENCE",MODE_PRIVATE);
    String FirstTime=Preferences.getString("FirstTimeInstall","");

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

            String parent=sp_parent.getSelectedItem().toString();
            String child=sp_child.getSelectedItem().toString();
            String college=sp_college.getSelectedItem().toString();

            Intent intent=new Intent(getApplicationContext(),Dashboard.class);
            intent.putExtra("parent",parent);
            intent.putExtra("child",child);
            intent.putExtra("college",college);
            startActivity(intent);
            finish();

        }
    });

            if (FirstTime.equals("Yes")){
            String parent=sp_parent.getSelectedItem().toString();
            String child=sp_child.getSelectedItem().toString();
            String college=sp_college.getSelectedItem().toString();

        Intent intent=new Intent(getApplicationContext(),Dashboard.class);
            intent.putExtra("parent",parent);
            intent.putExtra("child",child);
            intent.putExtra("college",college);
        startActivity(intent);
        finish();

    }else {
        SharedPreferences.Editor editor=Preferences.edit();
        editor.putString("FirstTimeInstall","Yes");
        editor.apply();
    }

Body:
When starting a new activity you can send data through intent.

Intent intent = new Intent( this, Activity2.class );
intent.putExtra( "key", "value" );
startActivity(intent)

And in second activity do like this:

getIntent().getStringExtra( "key" );

or if you are sending int for example

getIntent().getIntExtra( "key", 0 );


问:
Apply Core Image Filter (CIBumpDistortion) to only one part of an image + change radius of selection and intensity of CIFilter
I would like to copy some of the features displayed here:

So I would like the user to apply a CIBumpDistortion filter to an image and let him choose

1) where exactly he wants to apply it by letting him just touch the respective location on the image

2a) the size of the circle selection (first slider in the image above)

2b) the intensity of the CIBumpDistortion Filter (second slider in the image above)

I read some previously asked questions, but they were not really helpful and some of the solutions sounded really far from userfriendly (e.g. cropping the needed part, then reapplying it to the old image). Hope I am not asking for too much at once. Objective-C would be preferred, but any help/hint would be much appreciated really! Thank you in advance!

答:
To show the bump:<br>
You have to pass the location (kCIInputCenterKey) on image with Radius Size (white Circle in your case) </p>

```<code>func appleBumpDistort(toImage currentImage: UIImage, radius : Float, intensity: Float) -> UIImage? {
    var context: CIContext = CIContext()
    let currentFilter = CIFilter(name: "CIBumpDistortion")
    let beginImage = CIImage(image: currentImage)
    currentFilter.setValue(beginImage, forKey: kCIInputImageKey)

    currentFilter.setValue(radius, forKey: kCIInputRadiusKey)
    currentFilter.setValue(intensity, forKey: kCIInputScaleKey)
    currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey)

    guard let image = currentFilter.outputImage else { return nil }

    if let cgimg = context.createCGImage(image, from: image.extent) {
        let processedImage = UIImage(cgImage: cgimg)
        return processedImage
    }
    return nil
}
</code>```

Body:
To show the bump:

You have to pass the location (kCIInputCenterKey) on image with Radius Size (white Circle in your case)

func appleBumpDistort(toImage currentImage: UIImage, radius : Float, intensity: Float) -> UIImage? {
    var context: CIContext = CIContext()
    let currentFilter = CIFilter(name: "CIBumpDistortion")
    let beginImage = CIImage(image: currentImage)
    currentFilter.setValue(beginImage, forKey: kCIInputImageKey)

    currentFilter.setValue(radius, forKey: kCIInputRadiusKey)
    currentFilter.setValue(intensity, forKey: kCIInputScaleKey)
    currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey)

    guard let image = currentFilter.outputImage else { return nil }

    if let cgimg = context.createCGImage(image, from: image.extent) {
        let processedImage = UIImage(cgImage: cgimg)
        return processedImage
    }
    return nil
}


问:
how to install curl for health check of spring boot jib docker image?
You define jib image in pom file, but I need curl command-line to be running on the container to do health check on aws ecs. How can I add curl into that image?</p>

答:
You can use your own Docker image with all the necessary tools in it. For example, you can use ibmjava:8-jre-alpine,
and for how to use it in jib, just run the goal with below specified parameter of that custom image.

```<code>mvn compile jib:build \
    -Djib.from.image=ibmjava:8-jre-alpine
</code>```

You can write your own Dockerfile to create any custom image in which you install all the cli-tools if it's not present in that base image. and then push it to container registry and then use it as mentioned-above.

Body:
You can use your own Docker image with all the necessary tools in it. For example, you can use ibmjava:8-jre-alpine,
and for how to use it in jib, just run the goal with below specified parameter of that custom image.

mvn compile jib:build \
    -Djib.from.image=ibmjava:8-jre-alpine

You can write your own Dockerfile to create any custom image in which you install all the cli-tools if it's not present in that base image. and then push it to container registry and then use it as mentioned-above.


问:
React Navigation 5 - How to navigate from headerRight?
i still trying to understand this react navigation 5.0.
Fyi i'm using expo, and right now no problem when navigate from one page to other,
problem is when i put navigation for the headerRight.
i put in headerRight in Stack.Navigator because i want this button to be accessible from other screen.

So basically the problem is,
i want to put logout button in headerRight,
but when i try to put navigation.navigate it sait undefined is not an object (evaluating '_this.props')

Then i try to call a function (handleClick),
problem is undefined is not an object too.

May i know what's wrong with my code?

Below is my full code :

import * as React from 'react';
import { Button, View, Text, TextInput, Image, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import LoginScreen from './src/pages/auth/Login';
import HomeScreen from './src/pages/auth/HomeScreen';

const Stack = createStackNavigator();

export default function App() {

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

  return (
    <NavigationContainer>
      <Stack.Navigator mode="modal" initialRouteName="Login" screenOptions={{
        headerStyle: {
          backgroundColor: '#f4511e',
        },
        headerRight: () => (
          <Button
            // only alert is ok, the other is error.
            // onPress={() => alert('Success Logout!')}
            onPress={this.handleClick}
            // onPress={this.props.navigation.navigate('Home')}
            title="Logout"
            color="#fff"
          />
        ),

        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
      }}>

        <Stack.Screen name="Login"
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            title: 'Home Menu',
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}```

Thanks before

答:
You should try this.

You receive the reference to the router (navigation) by converting the property screenOptions to a function.

```<code>screenOptions={({route, navigation}) => ({ // get reference to navigation
   headerRight: () => (
      <Button
        onPress={() => navigation.navigate('Home'); // call .navigate on navigation
      />
    )
  })}
</code>```

Body:
i still trying to understand this react navigation 5.0.
Fyi i'm using expo, and right now no problem when navigate from one page to other,
problem is when i put navigation for the headerRight.
i put in headerRight in Stack.Navigator because i want this button to be accessible from other screen.

So basically the problem is,
i want to put logout button in headerRight,
but when i try to put navigation.navigate it sait undefined is not an object (evaluating '_this.props')

Then i try to call a function (handleClick),
problem is undefined is not an object too.

May i know what's wrong with my code?

Below is my full code :

import * as React from 'react';
import { Button, View, Text, TextInput, Image, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import LoginScreen from './src/pages/auth/Login';
import HomeScreen from './src/pages/auth/HomeScreen';

const Stack = createStackNavigator();

export default function App() {

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

  return (
    <NavigationContainer>
      <Stack.Navigator mode="modal" initialRouteName="Login" screenOptions={{
        headerStyle: {
          backgroundColor: '#f4511e',
        },
        headerRight: () => (
          <Button
            // only alert is ok, the other is error.
            // onPress={() => alert('Success Logout!')}
            onPress={this.handleClick}
            // onPress={this.props.navigation.navigate('Home')}
            title="Logout"
            color="#fff"
          />
        ),

        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
      }}>

        <Stack.Screen name="Login"
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            title: 'Home Menu',
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Thanks before

Body:
You should try this.

You receive the reference to the router (navigation) by converting the property screenOptions to a function.

screenOptions={({route, navigation}) => ({ // get reference to navigation
   headerRight: () => (
      <Button
        onPress={() => navigation.navigate('Home'); // call .navigate on navigation
      />
    )
  })}


问:
Laravel login with username instead of email
How can I make login with username, instead of email?

It's my login.blade.php

```<code>@extends('layouts.main')
@section('errors')
@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
@section('content')
<form method="POST" action="/auth/login">
    {!! csrf_field() !!}

    <div>
        Email
        <input type="email" name="email" value="{{ old('email') }}">
    </div>

    <div>
        Password
        <input type="password" name="password" id="password">
    </div>

    <div>
        <input type="checkbox" name="remember"> Remember Me
    </div>

    <div>
        <button type="submit">Login</button>
    </div>
</form>
</body>
@stop
</code>```

答:
By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:</p>

```<code>public function username()
{
    return 'username';
}
</code>```

Body:
How can I make login with username, instead of email?

It's my login.blade.php

@extends('layouts.main')
@section('errors')
@if (count($errors) > 0)

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif
@section('content')
<form method="POST" action="/auth/login">
    {!! csrf_field() !!}

        Email
        <input type="email" name="email" value="{{ old('email') }}">

        Password
        <input type="password" name="password" id="password">

        <input type="checkbox" name="remember"> Remember Me

        <button type="submit">Login</button>

</form>

@stop

Body:
By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:

public function username()
{
    return 'username';
}


问:
Zabbix API to get the details of traffic used by the applications
I would like to get the details/usage of network traffic used by each application (not by host).

I tried and I was able to get the list of application running on a host, by using:

```<code>{
    "jsonrpc": "2.0",
    "method": "application.get",
    "params": {
        "output": "extend",
        "hostids": "10107"
    },
    "auth": "02axxxxxxx6e1023exxx252cd2xx70",
    "id": 1
}
</code>```

but I need the network traffic consumption details:

答:
There is no native way to do it.

The application.get api retrieves the application list from the template/host, Zabbix uses it as a grouping mechanism.

See Configuration -> Templates -> Pick one -> Applications

Body:
I would like to get the details/usage of network traffic used by each application (not by host).

I tried and I was able to get the list of application running on a host, by using:

{
    "jsonrpc": "2.0",
    "method": "application.get",
    "params": {
        "output": "extend",
        "hostids": "10107"
    },
    "auth": "02axxxxxxx6e1023exxx252cd2xx70",
    "id": 1
}

but I need the network traffic consumption details:


问:
mysql syntax ERROR 1064 while creating a trigger
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

```<code>mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;
</code>```

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3

答:
You should create trigger query same my code:

```<code>create trigger update_account
    after insert
    on bank
    for each row
begin
    update balance as a
    set a.balance=(IF(new.withdraw = 1, a.balance - new.withdraw, a.balance + new.withdraw))
    where a.accno = new.accno;
END;
</code>```

And if you have only two cases, you should IF, not need Case when

Body:
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3

Body:
You should create trigger query same my code:

create trigger update_account
    after insert
    on bank
    for each row
begin
    update balance as a
    set a.balance=(IF(new.withdraw = 1, a.balance - new.withdraw, a.balance + new.withdraw))
    where a.accno = new.accno;
END;

And if you have only two cases, you should IF, not need Case when


问:
Can Apache be setup as forward proxy and reverse proxy at the same time?
I want to achieve the following:

My app services user requests like so:
user request www.mysite.com -> Apache reverse proxy -> 192.168.1.1:8080/myApp

My app also makes requests but I want to route through a proxy:
192.168.1.1:8080/myApp -> Apache forward proxy -> www.google.com

Can I set this up on the same Apache server? If not, can I do it with two Apache servers on the same system?

答: One conf file contains ProxyRequest on which makes Apache work as Forward-proxy and put ProxyRemote to localhost:high-port, and another conf file contains VHOST block for each port with ProxyRequest off which make Apache as Reverse-proxy.


问:
how to use Table pagination material-ui react js
Hi I use react js and I'm new. I want to use Table pagination material-ui for a table that does not belong to material-ui.For example, I want 2 row per page.I use the reactStrap table. If possible, tell me how to do it.

```<code>  render() {
    const items = this.props.items.map(item => {
      return (
        <tr key={item.id}>
          <td>
            <div style={{ width: "110px" }}>
              <Button
                color="success"
                buttonLabel="Edit"
                item={item}
                updateState={this.props.updateState}
              >
                Edit
              </Button>

              <Button color="danger" onClick={() => this.deleteItem(item.id)}>
                Del
              </Button>
            </div>
          </td>
          <th scope="row">{item.id}</th>
          <td>{item.name}</td>
          <td>{item.username}</td>
          <td>{item.email}</td>
        </tr>
      );
    });

    return (
      <div
        style={{
          maxHeight: "600px",
          overflowY: "auto"
        }}
      >
        <Table responsive hover>
          <thead>
            <tr>
              <th>Action</th>
              <th>ID</th>
              <th>name</th>
              <th>username</th>
              <th>email</th>
            </tr>
          </thead>
          <tbody>{items}</tbody>
        </Table>
      </div>
    );
  }
}
</code>```

You can see my table in CodeSandbox.Thanks in advance for your answers

答:
I prepared an example Only for pagination. You need to work on api calling with the paging parameters. As your api is returning only 10 records, so I set rowsPerPage: 5 so that you can get the reflection of changing page. but default value should be rowsPerPage: 10

```<code>  state = {
    items: [],
    page: 0,
    rowsPerPage: 5
  };
</code>```

Update:

You need update the url with the state value like below:

```<code>let url = `https://reqres.in/api/users?page=${this.state.page +
      1}&per_page=${this.state.rowsPerPage}`;
</code>```

And then call api when you change the page. Please check the below link for code.

Here is the Code Sandbox

Body:
Hi I use react js and I'm new. I want to use Table pagination material-ui for a table that does not belong to material-ui.For example, I want 2 row per page.I use the reactStrap table. If possible, tell me how to do it.

  render() {
    const items = this.props.items.map(item => {
      return (

              <Button
                color="success"
                buttonLabel="Edit"
                item={item}
                updateState={this.props.updateState}
              >
                Edit
              </Button>

              <Button color="danger" onClick={() => this.deleteItem(item.id)}>
                Del
              </Button>

          {item.id}
          {item.name}
          {item.username}
          {item.email}

      );
    });

    return (

              Action
              ID
              name
              username
              email

{items}

    );
  }
}

You can see my table in CodeSandbox.Thanks in advance for your answers

Body:
I prepared an example Only for pagination. You need to work on api calling with the paging parameters. As your api is returning only 10 records, so I set rowsPerPage: 5 so that you can get the reflection of changing page. but default value should be rowsPerPage: 10

  state = {
    items: [],
    page: 0,
    rowsPerPage: 5
  };

Update:

You need update the url with the state value like below:

let url = `https://reqres.in/api/users?page=${this.state.page +
      1}&per_page=${this.state.rowsPerPage}`;

And then call api when you change the page. Please check the below link for code.

Here is the Code Sandbox


问:
can UNUserNotificationCenter add multiple requests?
I can add one request. But when i tried to ad two, only the latest is fired. The first just doesn't appear. Here is my method :

```<code>            var triggerDailyEnd = DateComponents()
            triggerDailyEnd.hour = hour
            triggerDailyEnd.minute = minutes
            triggerDailyEnd.weekday = i+1
            // this repeat every day
            let triggerEnd = UNCalendarNotificationTrigger(dateMatching: triggerDailyEnd, repeats: true)

            let identifierEnd = getNotificationId(i+1, hour, minutes,true)
            let requestEnd = UNNotificationRequest(identifier: identifierEnd, content: notifEnd, trigger: triggerEnd)

            notificationCenter.add(requestEnd)

            var triggerDailyStart = DateComponents()
            triggerDailyStart.hour = hour
            // correctly remove time
            triggerDailyStart.minute = minutes-Int(ProgrammationViewController.PREHEAT_TIME)
            triggerDailyStart.weekday = i+1
            // this repeat every day
            let triggerStart = UNCalendarNotificationTrigger(dateMatching: triggerDailyStart, repeats: true)

            let identifierStart = getNotificationId(i+1, hour, minutes,false)
            let requestStart = UNNotificationRequest(identifier: identifierStart, content: notifStart, trigger: triggerStart)

            notificationCenter.add(requestStart)
</code>```

the code is quite simple.When I add requestEnd after requestStart, the notification of requestEnd is fired and not requestStart.And vice versa. Strange ?

答: The identifier parameter to the request needs to be unique. If it's the same, the second request will overwrite the first.

Body:
I can add one request. But when i tried to ad two, only the latest is fired. The first just doesn't appear. Here is my method :

            var triggerDailyEnd = DateComponents()
            triggerDailyEnd.hour = hour
            triggerDailyEnd.minute = minutes
            triggerDailyEnd.weekday = i+1
            // this repeat every day
            let triggerEnd = UNCalendarNotificationTrigger(dateMatching: triggerDailyEnd, repeats: true)

            let identifierEnd = getNotificationId(i+1, hour, minutes,true)
            let requestEnd = UNNotificationRequest(identifier: identifierEnd, content: notifEnd, trigger: triggerEnd)

            notificationCenter.add(requestEnd)

            var triggerDailyStart = DateComponents()
            triggerDailyStart.hour = hour
            // correctly remove time
            triggerDailyStart.minute = minutes-Int(ProgrammationViewController.PREHEAT_TIME)
            triggerDailyStart.weekday = i+1
            // this repeat every day
            let triggerStart = UNCalendarNotificationTrigger(dateMatching: triggerDailyStart, repeats: true)

            let identifierStart = getNotificationId(i+1, hour, minutes,false)
            let requestStart = UNNotificationRequest(identifier: identifierStart, content: notifStart, trigger: triggerStart)

            notificationCenter.add(requestStart)

the code is quite simple.When I add requestEnd after requestStart, the notification of requestEnd is fired and not requestStart.And vice versa. Strange ?


问:
Would calling a mediator be correct in my Handler when crossing services/modules in a DDD monolith

Preface about the architecture

In a microservice, this could be a service according to clean-architecture:

BasketService

Api

Application  [CQRS]

Core

Infrastructure

CatalogService

Api

Application  [CQRS]

Core

Infrastructure

But since i'm applying DDD to a monolith, i can currently remove my Api layer and have less "projects"/module. So every module ( eg. basket and catalog) contains 3 projects currently:

Application

Core

Infrastructure

Both have a dependency on .Core

Problem description

My application has a BasketModule and a CatalogModule.
Would it be correct to get information from the CatalogModule ( which contains the products) with Mediator like this:

```<code>public Task<BasketDTO> Handle(GetBasketByBuyerIdCommand request, CancellationToken cancellationToken)
    {
        BasketDTO result;
        var basket = m_basketRepo.GetById(request.BuyerId);

        if (basket == null)
        {
            result = new BasketDTO()
            {
                BuyerId = request.BuyerId,
                Items = new List<BasketItem>()
            };
            return Task.FromResult(result);
        }

        //Could be automapper, but not now currently //ignore
        var products = new List<DTO.Product>();

        foreach (var item in basket.Items)
        {
          var product = m_mediator.Send(new GetProductByIdQuery(item.ProductId)).Result; //ignore the non-async. It's example code

            products.Add(new DTO.Product()
            {
                Id = product.Id,
                Price = product.Price,
                Title = product.Title
            });
        }

        result = new BasketDTO()
        {
            BuyerId = basket.BuyerId,
            Items = basket.Items
            .Select(dl => new DTO.BasketItem()
            {

                ProductId = dl.ProductId,
                Quantity = dl.Quantity,
                Product = products
                .Where(cl => cl.Id == dl.ProductId)
                .FirstOrDefault()
            }).ToList()
        };

        return Task.FromResult(result);
    }
}
</code>```

It is about the following line:

```<code> var product = await m_mediator.Send(new GetProductByIdQuery(item.ProductId));
</code>```

Is this correct to do? I'm not talking about the rest of the example code, but specifically about calling the mediator to get the product and having a dependency of the project "Basket.Application" on "Catalog.Application"

答:
To be honest, only you know the answer to your question. By the looks of it and despite the naming "GetBasketByBuyerIdCommand" it seems you're only running queries in your code. So that means you're only working on the "Q" of CQRS and on that perspective what you are doing is fine.

In my opinion, the answer to your question lies in the rest of your architecture and especially in what you're trying to achieve with it at this point. If you want your BasketModule and CatalogModule to be totally independent somewhere down the road, this type of choice taken now might have a great deal of impact in the future.

For example, if you, later on, want the two modules to be separated into two different microservices, you will have to come up with a different way of doing the query you described. How to handle this is a whole new conversation in its own respect.

Body:
Preface about the architecture

In a microservice, this could be a service according to clean-architecture:

BasketService

Api

Application  [CQRS]

Core

Infrastructure

CatalogService

Api

Application  [CQRS]

Core

Infrastructure

But since i'm applying DDD to a monolith, i can currently remove my Api layer and have less "projects"/module. So every module ( eg. basket and catalog) contains 3 projects currently:

Application

Core

Infrastructure

Both have a dependency on .Core

Problem description

My application has a BasketModule and a CatalogModule.
Would it be correct to get information from the CatalogModule ( which contains the products) with Mediator like this:

public Task<BasketDTO> Handle(GetBasketByBuyerIdCommand request, CancellationToken cancellationToken)
    {
        BasketDTO result;
        var basket = m_basketRepo.GetById(request.BuyerId);

        if (basket == null)
        {
            result = new BasketDTO()
            {
                BuyerId = request.BuyerId,
                Items = new List<BasketItem>()
            };
            return Task.FromResult(result);
        }

        //Could be automapper, but not now currently //ignore
        var products = new List<DTO.Product>();

        foreach (var item in basket.Items)
        {
          var product = m_mediator.Send(new GetProductByIdQuery(item.ProductId)).Result; //ignore the non-async. It's example code

            products.Add(new DTO.Product()
            {
                Id = product.Id,
                Price = product.Price,
                Title = product.Title
            });
        }

        result = new BasketDTO()
        {
            BuyerId = basket.BuyerId,
            Items = basket.Items
            .Select(dl => new DTO.BasketItem()
            {

                ProductId = dl.ProductId,
                Quantity = dl.Quantity,
                Product = products
                .Where(cl => cl.Id == dl.ProductId)
                .FirstOrDefault()
            }).ToList()
        };

        return Task.FromResult(result);
    }
}

It is about the following line:

 var product = await m_mediator.Send(new GetProductByIdQuery(item.ProductId));

Is this correct to do? I'm not talking about the rest of the example code, but specifically about calling the mediator to get the product and having a dependency of the project "Basket.Application" on "Catalog.Application"


答:
You need to combine a few different commands. To find the first row for each ID, use pandas groupby on multiple columns, ID and Date, like this:

```<code>df = pd.read_csv(input_file)
filtered_df = df.groupby(['ID', 'Date'])
</code>```

After that you can copy the original dataframe based on the Date and Time of the filtered_df

Title: Insert values of rows above python

Body:
I have a csv below:

ID    Date          Time       Flag
1     14/05/2018    00:01:00   NaN
1     14/05/2018    00:02:00   NaN
1     14/05/2018    00:03:00   NaN
1     14/05/2018    00:04:00   NaN
1     14/05/2018    00:05:00   NaN
1     14/05/2018    00:06:00   NaN
1     14/05/2018    00:07:00   NaN
1     14/05/2018    00:08:00   NaN
1     15/05/2018    00:01:00   1
1     15/05/2018    00:02:00   1
1     16/05/2018    00:01:00   1
1     16/05/2018    00:02:00   1

2     10/07/2018    00:03:00   NaN
2     10/07/2018    00:04:00   NaN
2     10/07/2018    00:05:00   NaN
2     10/07/2018    00:06:00   NaN
2     10/07/2018    00:07:00   NaN
2     10/07/2018    00:08:00   NaN
2     11/07/2018    00:01:00   1
2     11/07/2018    00:02:00   1
2     12/07/2018    00:01:00   1
2     12/07/2018    00:02:00   1

I want to update NaN for only 4 rows above the first row (of only the first day and first time of that day) with Flag=1 for each ID.

Expected csv:

1     14/05/2018    00:01:00   NaN
1     14/05/2018    00:02:00   NaN
1     14/05/2018    00:03:00   NaN
1     14/05/2018    00:04:00   NaN
1     14/05/2018    00:05:00   1
1     14/05/2018    00:06:00   1
1     14/05/2018    00:07:00   1
1     14/05/2018    00:08:00   1
1     15/05/2018    00:01:00   1
1     15/05/2018    00:02:00   1
1     16/05/2018    00:01:00   1
1     16/05/2018    00:02:00   1

2     10/07/2018    00:03:00   NaN
2     10/07/2018    00:04:00   NaN
2     10/07/2018    00:05:00   1
2     10/07/2018    00:06:00   1
2     10/07/2018    00:07:00   1
2     10/07/2018    00:08:00   1
2     11/07/2018    00:01:00   1
2     11/07/2018    00:02:00   1
2     12/07/2018    00:01:00   1
2     12/07/2018    00:02:00   1

How can I do that. Thanks.

Body:
You need to combine a few different commands. To find the first row for each ID, use pandas groupby on multiple columns, ID and Date, like this:

df = pd.read_csv(input_file)
filtered_df = df.groupby(['ID', 'Date'])

After that you can copy the original dataframe based on the Date and Time of the filtered_df


问:
Wide html responsive html table
My datatable has 30 - 40 columns. I need responsive table solution without horizontal scrollbar, where weighting of each columns is the same. Hiding last columns is OK.

Responsive datatables extension is good, but problem is, one of group data looks different as another. First are in one cell as list and another in common cells.

I think one solution is integration colvis extension with swipe table.

Next is scroll-horizontal, but responsiveness is worse.

Any other ideas?

Thanks.

答:
You can make any table scrollable purely with CSS.</p>

```<code>table {
    overflow: auto;
    display: block;
    width: 100%;
}
</code>```

Title: Wide html responsive html table

Body:
You can make any table scrollable purely with CSS.

table {
    overflow: auto;
    display: block;
    width: 100%;
}


问:
LinkedIn share requirements to display BIG image
My question is: why image is small and how to make it big?

I have implemented linkedIn share.
For that I have added meta tags: og:title og:image og:description og:url.

Everything is working but my image is small.

Small image example

Big image example

We have asked linkedIn about that and answer was to check image aspect ratio but it is fine. And image aspect ratio is not what cause the problem.

We have tested different images (sizes, dimension, simple images, colorful images, etc). Nothing helped.

Probably it is different origin issue. Try to make sure that your site and your images are served from same origin.

答:
Probably it is different origin issue. Try to make sure that your site and your images are served from same origin.

Like site url is some-site.com and image url is some-image-url.com. Try to change some-image-url.com to some-site.com/image


问:
I am trying to convert a varchar into a date, but I keep getting this error below
I am trying to convert varchar into a date in Informatica, but I keep getting this error below

invalid string for converting to Date

  ... t:TO_DATE(u:'2020-02-13T11:13:58.4861917-06:00',u:'MM/DD/YYYY HH24:MI:SS')

Could you please help me with the syntax?

答:
Above syntax will not work because the value in the data filed is not exactly a date. You have T character in between and the seconds are in decimals. You have to substring the value and convert it to date. Below is the syntax,

```<code>TO_DATE(substr(date_column, 0,10),'YYYY-MM-DD')
</code>```

Body:
Above syntax will not work because the value in the data filed is not exactly a date. You have T character in between and the seconds are in decimals. You have to substring the value and convert it to date. Below is the syntax,

TO_DATE(substr(date_column, 0,10),'YYYY-MM-DD')


问:
Equivalent of *Nix 'which' command in PowerShell?
How do I ask PowerShell where something is?

For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.

答:
If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:

function which($name) {
    if ($name) { $input = $name }
    Get-Command $input | Select-Object -ExpandProperty Path
}
```

<p>copy-paste the command to your profile (<code>notepad $profile</code>).</p>

<p>Examples:</p>

<pre class="lang-bsh prettyprint-override"><code>❯ echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe

❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe
</code>```

OwnerDisplayName: ChanChan

LastEditorDisplayName: Jay Bazuzi

Body:
If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:

function which($name) {
    if ($name) { $input = $name }
    Get-Command $input | Select-Object -ExpandProperty Path
}

copy-paste the command to your profile (notepad $profile).

Examples:

❯ echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe

❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

```<code>public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {
</code>```

So here on this code I am getting the error

```<code>this._section.GetType();
</code>```

How can this problem be fixed?

答:
I think you forget to set value for _section. You should have set it, for example, in updateViews.

I believe that you plan _section to be an instance of some subclass of SingleBanners, which to be determined at runtime. If the type of _section is clear at compile-time (like _section = new SingleBanners()), you would have used typeof(SingleBanners).

Body:
Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {

So here on this code I am getting the error

this._section.GetType();

How can this problem be fixed?


问:
How to read line of file until end using system calls in C?
I'm trying to read a file line by line by comparing the currently read character with \n (end of line symbol). The characters of that line are stored in a buffer.

I'm confused how to handle at the same time the buffer, where I keep the current line and the check with the end of line character. That's what I use the indexCurrentSymbol for, to always the the last symbol of the buffer and see if it's \n.

Please not that I'm supposed to achieve this with basic system calls (so no library functions that read a full line).

The input is

```<code>Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge
</code>```

I'm ignoring all error checks for files that might not be available on purpose to be able to focus on the task.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    char buf[100];
    int read_bytes = read(input, &buf, 1);
    int indexCurrentSymbol = 0;
    while (buf[indexCurrentSymbol] != '\n') {
        // read(input, buf, 1);    // Correction based on comment.
        read(input, &buf[indexCurrentSymbol], 1);
        indexCurrentSymbol++;
    }

    close(input);
    return 0;
}
</code>```

答:
Here is a modified program version that allows to read the whole file
(note that error processing is not enough and there is no check on buf maximum size):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {

    char buf[100];
    int indexCurrentSymbol = 0;
    int read_bytes;
    int line_read=0;
    int file_read=0;

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    if (input < 0)
    perror("open");

    buf[0] = '\0';
    while (file_read == 0) {

        read_bytes = read(input, &buf[indexCurrentSymbol], 1);
        if (read_bytes == -1)
           perror("read while: -1");
        if (read_bytes == 0)
            file_read = 1;

        if (buf[indexCurrentSymbol] == '\n')
             printf("current buf=\n%s\n", buf);

        indexCurrentSymbol++;
    }

    printf("final buf=\n%s\n", buf);
    close(input);
    return 0;
}
</code>```

With:

```<code>$ cat tread.dat
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge
</code>```

I get:

```<code>$ ./tread tread.dat
current buf=
Animal, Size

current buf=
Animal, Size
Dog, Big

current buf=
Animal, Size
Dog, Big
Duck, Small

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

final buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge
</code>```

Body:
I'm trying to read a file line by line by comparing the currently read character with \n (end of line symbol). The characters of that line are stored in a buffer.

I'm confused how to handle at the same time the buffer, where I keep the current line and the check with the end of line character. That's what I use the indexCurrentSymbol for, to always the the last symbol of the buffer and see if it's \n.

Please not that I'm supposed to achieve this with basic system calls (so no library functions that read a full line).

The input is

Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

I'm ignoring all error checks for files that might not be available on purpose to be able to focus on the task.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    char buf[100];
    int read_bytes = read(input, &buf, 1);
    int indexCurrentSymbol = 0;
    while (buf[indexCurrentSymbol] != '\n') {
        // read(input, buf, 1);    // Correction based on comment.
        read(input, &buf[indexCurrentSymbol], 1);
        indexCurrentSymbol++;
    }

    close(input);
    return 0;
}

Body:
Here is a modified program version that allows to read the whole file
(note that error processing is not enough and there is no check on buf maximum size):

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {

    char buf[100];
    int indexCurrentSymbol = 0;
    int read_bytes;
    int line_read=0;
    int file_read=0;

    // Open file to read line.
    int input = open(argv[1], O_RDONLY);
    if (input < 0)
    perror("open");

    buf[0] = '\0';
    while (file_read == 0) {

        read_bytes = read(input, &buf[indexCurrentSymbol], 1);
        if (read_bytes == -1)
           perror("read while: -1");
        if (read_bytes == 0)
            file_read = 1;

        if (buf[indexCurrentSymbol] == '\n')
             printf("current buf=\n%s\n", buf);

        indexCurrentSymbol++;
    }

    printf("final buf=\n%s\n", buf);
    close(input);
    return 0;
}

With:

$ cat tread.dat
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

I get:

$ ./tread tread.dat
current buf=
Animal, Size

current buf=
Animal, Size
Dog, Big

current buf=
Animal, Size
Dog, Big
Duck, Small

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny

current buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge

final buf=
Animal, Size
Dog, Big
Duck, Small
Mouse, Tiny
Horse, Huge


问:
Microsoft Edge Authentication popup
I have configured .net core 2.2 API to use windows and JWT authentication both:

```<code> "windowsAuthentication": true,
 "anonymousAuthentication": true,
</code>```

The application has angular as an SPA on the UI. Now the application works perfectly fine with chrome, however on edge, it keeps showing the credential popup and I am not able to remove it.
I have configured site also on the security tab for internet options as *.abc.com so that all such URLs are trusted.

The failed network call shows that edge removes the bearer token and replaces it with negotiate, which causes the 401 and then popup.

what will I be missing ?

答:
To anyone who has faced the same issue, in the end I have split the project in two projects, one with windows authentication, and other with JWT authentication only.

Only this solved the problem.

Title: Microsoft Edge Authentication popup

Body:
I have configured .net core 2.2 API to use windows and JWT authentication both:

 "windowsAuthentication": true,
 "anonymousAuthentication": true,

The application has angular as an SPA on the UI. Now the application works perfectly fine with chrome, however on edge, it keeps showing the credential popup and I am not able to remove it.
I have configured site also on the security tab for internet options as *.abc.com so that all such URLs are trusted.

The failed network call shows that edge removes the bearer token and replaces it with negotiate, which causes the 401 and then popup.

what will I be missing ?


问:
Cloud Endpoints Auth returning JWT Issuer is not configured when using Access Token from CICP/Firebase Auth
Right now my OpenAPI yaml looks like this:

And my Access Token coming out of my JWT in raw format looks like this:

The Google-Issuer and the JWT iss are the exact same, the JWT kid matches the key ids inside the link provided by the google-jwks_uri, and the google-audiences match the aud.So, really, I can't see why this wouldn't work, and yet when i call the api with the Bearer access token i receive a 401 and "Jwt issuer is not configured".

答:
@BryceSoker I ran into a similar problem and found that changing

x-google-issuer: "https://accounts.google.com"
to
x-google-issuer: "accounts.google.com"

to match the "iss": "accounts.google.com" in the ID token fixed the problem.


问:
naming and saving workspace variables to a file with a changing number in the name - Matlab
So the output of my code produce many variables in every loop in Matlab workspace. I want to save two of the variables (namely MO and Vr) to a file having a fixed name with a number which change in every loop. The number which changes in each loop is "NT+1".
First I change the name of the two desired variables with following code:

```<code>eval(sprintf('MO%d=MO;',NT+1));
eval(sprintf('Vr%d=Vr;',NT+1));
</code>```

Now I want to save the renamed MO and Vr variables in a .mat file having the NT+1 number at the end. For instance, if NT+1=60, I want the the two renamed variables (which are MO60 and Vr60) be saved in a file having the NT+1 number at the end: sim60.mat

```<code>save('sim%d.mat','MO%d','Vr%d',NT+1)
</code>```

hypothetical, the output of the above code should be a file named 'sim60.mat' having the two variables MO60 and Vr60.

How can I automatically perform such saving when the NT+1 changes in every loop and the name of MO and Vr also must be changed for the save command at each loop?

答:
You should not rename the workspace variables because you will need to use eval, which is almost always bad practice.

Go with

```<code>% create file name
flNm = num2str(i,'sim%d.mat');
% save file
save(flNm,'MO','Vr');
</code>```

if you now load the file, load it to a struct

```<code>flNm = num2str(i,'sim%d.mat');
Dat = load(flNm,'MO','Vr');
% access the variables
Dat.Mo
Dat.Vr
</code>```

usually one needs to load and save variables within a loop because the memory is too small to store them in a multidimensional array or a cell:

```<code>i_max = 10;
MO_all = NaN(3,3,i_max)
Vr_all = cell(i_max)
for i = 1:i_max
    % what happens in every loop
    MO = rand(3,3);
    Vr = rand(randi(10),randi(10)); % changing size
    % store for other loops
    MO_all(:,:,i) = MO;
    Vr_all{i} = Vr;
end
</code>```

The solution to you particular question is
(I do not recommend using this as it is not flexible, not robust and requires eval to create the variables in the first place!)

```<code>flNm = num2str(NT+1,'sim%d.mat');
vars2save = {num2str(NT+1,'MO%d'),num2str(NT+1,'Vr%d')};
save('sim%d.mat',vars2save {:})
</code>```

Body:
So the output of my code produce many variables in every loop in Matlab workspace. I want to save two of the variables (namely MO and Vr) to a file having a fixed name with a number which change in every loop. The number which changes in each loop is "NT+1".
First I change the name of the two desired variables with following code:

eval(sprintf('MO%d=MO;',NT+1));
eval(sprintf('Vr%d=Vr;',NT+1));

Now I want to save the renamed MO and Vr variables in a .mat file having the NT+1 number at the end. For instance, if NT+1=60, I want the the two renamed variables (which are MO60 and Vr60) be saved in a file having the NT+1 number at the end: sim60.mat

save('sim%d.mat','MO%d','Vr%d',NT+1)

hypothetical, the output of the above code should be a file named 'sim60.mat' having the two variables MO60 and Vr60.

How can I automatically perform such saving when the NT+1 changes in every loop and the name of MO and Vr also must be changed for the save command at each loop?

Body:
You should not rename the workspace variables because you will need to use eval, which is almost always bad practice.

Go with

% create file name
flNm = num2str(i,'sim%d.mat');
% save file
save(flNm,'MO','Vr');

if you now load the file, load it to a struct

flNm = num2str(i,'sim%d.mat');
Dat = load(flNm,'MO','Vr');
% access the variables
Dat.Mo
Dat.Vr

usually one needs to load and save variables within a loop because the memory is too small to store them in a multidimensional array or a cell:

i_max = 10;
MO_all = NaN(3,3,i_max)
Vr_all = cell(i_max)
for i = 1:i_max
    % what happens in every loop
    MO = rand(3,3);
    Vr = rand(randi(10),randi(10)); % changing size
    % store for other loops
    MO_all(:,:,i) = MO;
    Vr_all{i} = Vr;
end

The solution to you particular question is
(I do not recommend using this as it is not flexible, not robust and requires eval to create the variables in the first place!)

flNm = num2str(NT+1,'sim%d.mat');
vars2save = {num2str(NT+1,'MO%d'),num2str(NT+1,'Vr%d')};
save('sim%d.mat',vars2save {:})


问:
Only the last file is uploaded (Azure Blob)
I uploading the collection of files to blob as parallel (IFormFiles in C#).

I using semaphore and TPL to parallel uploading. (source)

But all files except the last are uploaded only at 64 Kb. The latest file is fully uploaded.

I don't know why chunk size 4Mb ignored and used 64Kb and why uploads only 1 chunk default size.

Here is a code:

```<code>public static async Task UploadBulkAsync(string storageConnectionString, string containerName, Dictionary<string, IFormFile> blobNameToFile)
    {
        var completed = 0;
        var semaphore = new SemaphoreSlim(AppGlobalSettings.BulkUploadAzureBlobThreadCount, AppGlobalSettings.BulkUploadAzureBlobThreadCount);
        var tasks = new List<Task>();

        var options = new BlobRequestOptions
        {
            ParallelOperationThreadCount = 20
        };

        var blobContainer = await GetContainerAsync(storageConnectionString, containerName);
        await blobContainer.SetPermissionsAsync(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });

        foreach (var one in blobNameToFile)
        {
            var name = one.Key;
            var file = one.Value;

            var blockBlob = blobContainer.GetBlockBlobReference(name);
            blockBlob.Properties.ContentType = file.ContentType;

            await semaphore.WaitAsync();

            tasks.Add(blockBlob.UploadFromStreamAsync(file.OpenReadStream(), null, options, null).ContinueWith(t =>
            {
                semaphore.Release();
                Interlocked.Increment(ref completed);
            }));
        }

        await Task.WhenAll(tasks);
    }
</code>```

答:
The problem was in the collection of IFormFile objects. You cannot open multiple IFormFile streams in the same request processing. They need to be processed sequentially.

link: Getting "The inner stream position has changed unexpectedly" in AWS Lambda

Body:
I uploading the collection of files to blob as parallel (IFormFiles in C#).

I using semaphore and TPL to parallel uploading. (source)

But all files except the last are uploaded only at 64 Kb. The latest file is fully uploaded.

I don't know why chunk size 4Mb ignored and used 64Kb and why uploads only 1 chunk default size.

Here is a code:

public static async Task UploadBulkAsync(string storageConnectionString, string containerName, Dictionary<string, IFormFile> blobNameToFile)
    {
        var completed = 0;
        var semaphore = new SemaphoreSlim(AppGlobalSettings.BulkUploadAzureBlobThreadCount, AppGlobalSettings.BulkUploadAzureBlobThreadCount);
        var tasks = new List<Task>();

        var options = new BlobRequestOptions
        {
            ParallelOperationThreadCount = 20
        };

        var blobContainer = await GetContainerAsync(storageConnectionString, containerName);
        await blobContainer.SetPermissionsAsync(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });

        foreach (var one in blobNameToFile)
        {
            var name = one.Key;
            var file = one.Value;

            var blockBlob = blobContainer.GetBlockBlobReference(name);
            blockBlob.Properties.ContentType = file.ContentType;

            await semaphore.WaitAsync();

            tasks.Add(blockBlob.UploadFromStreamAsync(file.OpenReadStream(), null, options, null).ContinueWith(t =>
            {
                semaphore.Release();
                Interlocked.Increment(ref completed);
            }));
        }

        await Task.WhenAll(tasks);
    }


问:
How to run multiple SQL queries?
I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?

```<code>Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.
</code>```

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.

答:
Why not create a PROCEDURE?

E.g.

```<code>CREATE OR REPLACE PROCEDURE foo
IS
BEGIN
  -- The create sentence goes here. For example:
  -- EXECUTE IMMEDIATE
  -- 'CREATE TABLE bar (...)';

  -- The update sentence goes here
  -- EXECUTE IMMEDIATE
  -- 'UPDATE bar SET ...';

  -- The drop/delete sentence goes here.
  -- EXECUTE IMMEDIATE
  -- 'DROP TABLE bar;'
END;
</code>```

You can test it with:

```<code>SET serveroutput ON;
exec foo;
</code>```

The PROCEDURE is stored on the database, so you can use it later on.

Hope this helps.

Title: How to run multiple SQL queries?

Body:
I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?

Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.

Body:
Why not create a PROCEDURE?

E.g.

CREATE OR REPLACE PROCEDURE foo
IS
BEGIN
  -- The create sentence goes here. For example:
  -- EXECUTE IMMEDIATE
  -- 'CREATE TABLE bar (...)';

  -- The update sentence goes here
  -- EXECUTE IMMEDIATE
  -- 'UPDATE bar SET ...';

  -- The drop/delete sentence goes here.
  -- EXECUTE IMMEDIATE
  -- 'DROP TABLE bar;'
END;

You can test it with:

SET serveroutput ON;
exec foo;

The PROCEDURE is stored on the database, so you can use it later on.

Hope this helps.


问:
iReport variable expression returns null
Here's the simple code in XML view of print form:

```<code><variable name="TITLE" class="java.lang.String">
     <variableExpression><![CDATA[$F{APP_NUMBER}.replaceAll( "app_", "" )]]></variableExpression>
</variable>
</code>```

If I use this variable in form, it returns null (while using "$V{TITLE}"). But if I remove replaceAll method, it works and returns correct value.
What is wrong with expression? Should I use something instead of "<variableExpression>"?

答:
If you are printing this variable in Title band change its evaluation time to "Report"</p>

```<code><title>
    <band height="79" splitType="Stretch">
        **<textField evaluationTime="Report">**
            <reportElement x="143" y="43" width="100" height="30" uuid="4fc0ce80-ced5-448e-bdd1-1571b3bc788f"/>
            <textFieldExpression><![CDATA[$V{TITLE}]]></textFieldExpression>
        </textField>
    </band>
</title>
</code>```

Body:
Here's the simple code in XML view of print form:

<variable name="TITLE" class="java.lang.String">
     <variableExpression><![CDATA[$F{APP_NUMBER}.replaceAll( "app_", "" )]]></variableExpression>
</variable>

If I use this variable in form, it returns null (while using "$V{TITLE}"). But if I remove replaceAll method, it works and returns correct value.
What is wrong with expression? Should I use something instead of "<variableExpression>"?

Body:
If you are printing this variable in Title band change its evaluation time to "Report"

<title>
    <band height="79" splitType="Stretch">
        **<textField evaluationTime="Report">**
            <reportElement x="143" y="43" width="100" height="30" uuid="4fc0ce80-ced5-448e-bdd1-1571b3bc788f"/>
            <textFieldExpression><![CDATA[$V{TITLE}]]></textFieldExpression>
        </textField>
    </band>
</title>


问:
Php download of *.zip or *.rar file are corrupted
I'm trying a download of a protected zip, rar file. After trying hundreds of different headers and combinations, I'm lost. I cann download images, pdf but zip and rar are corrupted.

Where is the problem?

Code

```<code>$url = url_for('/staff/photos/error.php');
$error = $url;

//$filepath = 'C:\wamp\www\photo_gallery\public\files\3d_models';
$url2 = PROJECT_PATH.DS.'public'.DS.'files'.DS.'3d_models';
$filepath = $url2;

$filename = null;

if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
    $filename = $_GET['file'];
} else {
    header("Location: $error");
    exit;
}

if ($filename) {

    $abs_path = $filepath . DIRECTORY_SEPARATOR . $filename;
    if (file_exists($abs_path) && is_readable($abs_path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Type: application/rar");
        header("Content-Transfer-Encoding: Binary");
        header('Content-length: ' . filesize($abs_path));
        header('Content-disposition: attachment; filename=' . $filename);
        readfile($abs_path);
    } else {
        header("Location: $error");
    }
}
</code>```

答:
SOLVED
I added:

```<code>ob_start();

if ($filename) {
$abs_path = $filepath . DS . $filename;
if (file_exists($abs_path) && is_readable($abs_path)) {

        header('Content-type: application/octet-stream');
        header('Content-length: ' . filesize($abs_path));
        header('Content-disposition: attachment; filename=' . $filename);
        header('Content-transfer-encoding: binary');

        while (ob_get_level()) {
        ob_end_clean();
        }
        readfile($abs_path);

    } else {
        header("Location: $error");
    }
}
</code>```

Body:
I'm trying a download of a protected zip, rar file. After trying hundreds of different headers and combinations, I'm lost. I cann download images, pdf but zip and rar are corrupted.

Where is the problem?

Code

$url = url_for('/staff/photos/error.php');
$error = $url;

//$filepath = 'C:\wamp\www\photo_gallery\public\files\3d_models';
$url2 = PROJECT_PATH.DS.'public'.DS.'files'.DS.'3d_models';
$filepath = $url2;

$filename = null;

if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
    $filename = $_GET['file'];
} else {
    header("Location: $error");
    exit;
}

if ($filename) {

    $abs_path = $filepath . DIRECTORY_SEPARATOR . $filename;
    if (file_exists($abs_path) && is_readable($abs_path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Type: application/rar");
        header("Content-Transfer-Encoding: Binary");
        header('Content-length: ' . filesize($abs_path));
        header('Content-disposition: attachment; filename=' . $filename);
        readfile($abs_path);
    } else {
        header("Location: $error");
    }
}

Body:
SOLVED
I added:

ob_start();

if ($filename) {
$abs_path = $filepath . DS . $filename;
if (file_exists($abs_path) && is_readable($abs_path)) {

        header('Content-type: application/octet-stream');
        header('Content-length: ' . filesize($abs_path));
        header('Content-disposition: attachment; filename=' . $filename);
        header('Content-transfer-encoding: binary');

        while (ob_get_level()) {
        ob_end_clean();
        }
        readfile($abs_path);

    } else {
        header("Location: $error");
    }
}


问:
React TypeScript Error. onCreate! No overload matches this call. Overload 1 of 2, '(props: Readonly<{}>): gave the following error
when it on Javascript, it work. but on typeScript, say it error. why?
how can i do?

App.tsx

```<code>class App extends React.Component<{}, null> {
    handleCreate = (data) => {
        console.log(data);
    }

    render() {
        return (
            <React.Fragment>
                <PhoneForm **onCreate**={this.handleCreate}/>
            </React.Fragment>
        );
    }
}
</code>```

that case, render()'s onCreate has next error :

```<code>TS2769: No overload matches this call.   Overload 1 of 2, '(props: Readonly<{}>): PhoneForm', gave the following error.     Type '{ onCreate: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.       Property 'onCreate' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.   Overload 2 of 2, '(props: {}, context?: any): PhoneForm', gave the following error.     Type '{ onCreate: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.       Property 'onCreate' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
</code>```

PhoneForm.tsx

```<code>class PhoneForm extends Component {
    state = {
        memberName: '',
        phone: ''
    }
    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.**onCreate**(this.state);
        this.setState({
            name: '',
            phone: ''
        })
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    placeholder="Member's Name"
                    value={this.state.memberName}
                    onChange={this.handleChange}
                    name="memberName"
                />
                <input
                    placeholder="Phone Number"
                    value={this.state.phone}
                    onChange={this.handleChange}
                    name="phone"
                />
                <button type="submit">Add</button>
            </form>
        );
    }
}
</code>```

and on PhoneForm.tsx has next error :

```<code>TS2339: Property 'onCreate' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
</code>```

how can i set type to onCreate?
(i'm not want resolve by ts-lint @ts-ignore. i want to know how to set type to onCreate!)

答:
If you are working with TypeScript and React, you will need to define an interface or type alias for your class components props and state:

```<code>interface PhoneFormState {
  memberName: string;
  phone: string;
}

interface PhoneFormProps {
  onCreate: (formState: PhoneFormState) => void;
}
</code>```

And then, you will use the interfaces are part of React.Component's type generic parameters:

```<code>class PhoneForm extends Component<PhoneFormProps, PhoneFormState> {
</code>```

Body:
when it on Javascript, it work. but on typeScript, say it error. why?
how can i do?

App.tsx

class App extends React.Component<{}, null> {
    handleCreate = (data) => {
        console.log(data);
    }

    render() {
        return (
            <React.Fragment>
                <PhoneForm **onCreate**={this.handleCreate}/>
            </React.Fragment>
        );
    }
}

that case, render()'s onCreate has next error :

TS2769: No overload matches this call.   Overload 1 of 2, '(props: Readonly<{}>): PhoneForm', gave the following error.     Type '{ onCreate: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.       Property 'onCreate' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.   Overload 2 of 2, '(props: {}, context?: any): PhoneForm', gave the following error.     Type '{ onCreate: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.       Property 'onCreate' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PhoneForm> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

PhoneForm.tsx

class PhoneForm extends Component {
    state = {
        memberName: '',
        phone: ''
    }
    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.**onCreate**(this.state);
        this.setState({
            name: '',
            phone: ''
        })
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    placeholder="Member's Name"
                    value={this.state.memberName}
                    onChange={this.handleChange}
                    name="memberName"
                />
                <input
                    placeholder="Phone Number"
                    value={this.state.phone}
                    onChange={this.handleChange}
                    name="phone"
                />
                <button type="submit">Add</button>
            </form>
        );
    }
}

and on PhoneForm.tsx has next error :

TS2339: Property 'onCreate' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

how can i set type to onCreate?
(i'm not want resolve by ts-lint @ts-ignore. i want to know how to set type to onCreate!)

Body:
If you are working with TypeScript and React, you will need to define an interface or type alias for your class components props and state:

interface PhoneFormState {
  memberName: string;
  phone: string;
}

interface PhoneFormProps {
  onCreate: (formState: PhoneFormState) => void;
}

And then, you will use the interfaces are part of React.Component's type generic parameters:

class PhoneForm extends Component<PhoneFormProps, PhoneFormState> {


问:
How to configure PuLP to call GLPK solver
I am using the PuLP library in Python to solve an MILP problem. I have run my problem successfully with the default solver (CBC). Now I would like to use PuLP with another solver (GLPK). How do I set up PuLP with GLPK?

I have done some research online and found information on how to use GLPK (e.g. with lp_prob.solve(pulp.GLPK_CMD())) but haven't found information on how to actually set up PuLP with GLPK (or any other solver for that matter), so that it finds my GLPK installation. I have already installed GLPK seperately (but I didn't add it to my PATH environment variable).

I ran the command pulp.pulpTestAll()

and got:

Solver <class 'pulp.solvers.GLPK_CMD'> unavailable

I know that I should be getting a "passed" instead of an "unavailable" to be able to use it.

答: I had same problem, but is not related with glpk installation, is with solution file create, the message is confusim. My problem was I use numeric name for my variables, as '0238' ou '1342', I add a 'x' before it, then they looked like 'x0238'.</p>