问:
JSON.NET Error Self referencing loop detected for type
I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject
```

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?

答:
C# code:</p>

```<code>            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            };

            var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);

            var filePath = @"E:\json.json";

            File.WriteAllText(filePath, jsonString);
</code>```

Body:
I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?

Body:
C# code:

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            };

            var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);

            var filePath = @"E:\json.json";

            File.WriteAllText(filePath, jsonString);


来源: stackexchange

问:
Is there an easy way in Javascript to add parameterised event listeners to dynamically generated HTML elements?
I have an ordered list whose list items are generated using Javascript (as the number of items/their contents is variable), and I would like to add an event listener to each item dependant on which element of the list it is - so I want the 1st item to call foo(1), the 2nd element to call foo(2), the 30th element to call foo(30), etc. However, currently all elements are ending up with a listener identical to that of the last element. Code I'm using is shown below:

```<code>document.getElementById("mylist").innerHTML = "";
  for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
  }
</code>```

答:
What about if you use let to declare your i variable:

```<code>document.getElementById("mylist").innerHTML = "";
for (let i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
}
</code>```

Reference: 'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?

ContentLicense: CC BY-SA 4.0

Body:
I have an ordered list whose list items are generated using Javascript (as the number of items/their contents is variable), and I would like to add an event listener to each item dependant on which element of the list it is - so I want the 1st item to call foo(1), the 2nd element to call foo(2), the 30th element to call foo(30), etc. However, currently all elements are ending up with a listener identical to that of the last element. Code I'm using is shown below:

document.getElementById("mylist").innerHTML = "";
  for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
  }

Body:
What about if you use let to declare your i variable:

document.getElementById("mylist").innerHTML = "";
for (let i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
}

Reference: 'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?


问:
how to add timer in ReactJS hooks
I am trying to add timer,
problem statement - when user click on button, it should call timer to start and after 3 seconds it should perform something.

my code which is not working

```<code>const [timer, setTimer] = useState(3);

useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){                /*Button onClick=submitStartTimer()*/
    setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}
</code>```

but the tab automatically gets close after 3 seconds, i know because of useEffect, but how can i start useEffect after click of submitStartTimer()?

答:
const [timer, setTimer] = useState(0);

You just have to start the timer with 0. Since you're starting with 3, useEffects kicks in and keep decreasing the timer right from the beginning because of this:

```<code>if (timer > 0) {
  setTimeout(() => setTimer(timer - 1), 1000);
}
</code>```

As [timer] has been passed as a dependency, whenever this changes, useEffects is called and hence you're seeing the behaviour. You have already used:

setTimer(3) in your submit method so that should work provided you go with this: const [timer, setTimer] = useState(0);

Another solution could be to remove [timer] from the dependency in useEffects and keep it [].

Title: how to add timer in ReactJS hooks

Body:
I am trying to add timer,
problem statement - when user click on button, it should call timer to start and after 3 seconds it should perform something.

my code which is not working

const [timer, setTimer] = useState(3);

useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){                /*Button onClick=submitStartTimer()*/
    setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}

but the tab automatically gets close after 3 seconds, i know because of useEffect, but how can i start useEffect after click of submitStartTimer()?

Body:
const [timer, setTimer] = useState(0);

You just have to start the timer with 0. Since you're starting with 3, useEffects kicks in and keep decreasing the timer right from the beginning because of this:

if (timer > 0) {
  setTimeout(() => setTimer(timer - 1), 1000);
}

As [timer] has been passed as a dependency, whenever this changes, useEffects is called and hence you're seeing the behaviour. You have already used:

setTimer(3) in your submit method so that should work provided you go with this: const [timer, setTimer] = useState(0);

Another solution could be to remove [timer] from the dependency in useEffects and keep it [].


问:
Store cron job logs in a file Php laravel
I am trying to get my cron jobs log in a log file. unfortunately i am not able to achieve that and i cant find any tutorial/blog about this.

I am using latest laravel version and i wrote 1 cron job

This is my command file handle

```<code>public function handle()
    {
        Employee::where('id', 2)->update(['salary' => 0]);

        $this->info('Command:Update Run successfully!');
    }
</code>```

and this is my schedule

```<code>$schedule->command('command:update')
        ->everyMinute();
</code>```

答:
In cron job command do this.This will create logs of cron in queue.log.

```<code>/usr/local/bin/<ea-php71> /home/<domain>/public_html/artisan queue:listen 1>> public_html/queue.log 2>&1
</code>```

Here ea-php71 is for php version 7.1.You can find this for other php versions.

Body:
I am trying to get my cron jobs log in a log file. unfortunately i am not able to achieve that and i cant find any tutorial/blog about this.

I am using latest laravel version and i wrote 1 cron job

This is my command file handle

public function handle()
    {
        Employee::where('id', 2)->update(['salary' => 0]);

        $this->info('Command:Update Run successfully!');
    }

and this is my schedule

$schedule->command('command:update')
        ->everyMinute();

Body:
In cron job command do this.This will create logs of cron in queue.log.

/usr/local/bin/<ea-php71> /home/<domain>/public_html/artisan queue:listen 1>> public_html/queue.log 2>&1

Here ea-php71 is for php version 7.1.You can find this for other php versions.


问:
How to normalize this into 1NF?
I am trying to breakdown this table into 1NF:

```<code>STUDENT    AGE    SUBJECT
Nancy      15     Math
Nancy      15     Bio
Peter      14     Math
Hal        17     Math
</code>```

I first have a separate table of student and age,

```<code>STUDENT    AGE
Nancy      15
Peter      14
Hal        17
</code>```

I known I should have a separate table for subject as well, but how can I achieve that and makes it relational to the previous table?

答:
Thanks to @philipxy, As per first normal form, the values in each attribute should be simple value(non-relational value). Your table is already having simple value for every attribute. Age, Student, Subject. So, it is already in first normal form.

For higher normal forms, I would suggest to you to define first Key for tables. It will ensure entity integrity is maintained. Also, create separate table for Subject, as it is not functionally depending on studentId. This will avoid update anomalies for updating subjects.

Student: StudentId, StudentName, Age

Subject: SubjectId, SubjectName

StudentSubject: StudentId, SubjectId

Title: How to normalize this into 1NF?

Body:
I am trying to breakdown this table into 1NF:

STUDENT    AGE    SUBJECT
Nancy      15     Math
Nancy      15     Bio
Peter      14     Math
Hal        17     Math

I first have a separate table of student and age,

STUDENT    AGE
Nancy      15
Peter      14
Hal        17

I known I should have a separate table for subject as well, but how can I achieve that and makes it relational to the previous table?


问:
'App not Installed' Error on Android
I have a program working in the Android Emulator. Every now and again I have been creating a signed .apk and exporting it to my HTC Desire to test. It has all been fine.

On my latest exported .apk I get the error message 'App not installed' when I try to install the .apk. It runs fine on the emulators.

As I have mainly been testing on the emulators and only every now and again exporting to a real phone I am not sure when this happened. What is the likely cause of it not installing on a physical phone but running fine in the emulators?

I have tried rebooting the phone & removing the existing .apk, does not fix the fault.

答:
In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

Open Google Play Console

Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

You can now download the derived apk:

Install the downloaded derived apk on your phone now.
The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.

ContentLicense: CC BY-SA 3.0

Title: 'App not Installed' Error on Android


问:
How to delete folders that are older than some days using camel
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

```<code>            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");
</code>```

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

答:
Draft decision, as example,java decision

```<code>File directory = new File(dirWay);
if(directory.exists()){

File[] listFiles = directory.listFiles();
long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);// how old

int  i = listFiles.length //for checking if directory is empty // you can use your logic for checking directory is empty or not

for(File listFile : listFiles) {
    if(listFile.lastModified() < purgeTime) {
      if(listFile.delete()) {
        i--;  //for checking if directory is empty // you can use your logic for checking directory is empty or not
      }

    }
  }
}

if (i == 0) { // check if directory empty delete it. Because of all files older than 10yers then directory older too. // you can use your logic for checking directory is empty or not
  FileUtils.forceDelete(new File(dirWay));
}
</code>```

public static void forceDelete(File file)
                        throws IOException

Deletes a file. If file is a directory, delete it and all sub-directories. https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)

Body:
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

Body:
Draft decision, as example,java decision

File directory = new File(dirWay);
if(directory.exists()){

File[] listFiles = directory.listFiles();
long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);// how old

int  i = listFiles.length //for checking if directory is empty // you can use your logic for checking directory is empty or not

for(File listFile : listFiles) {
    if(listFile.lastModified() < purgeTime) {
      if(listFile.delete()) {
        i--;  //for checking if directory is empty // you can use your logic for checking directory is empty or not
      }

    }
  }
}

if (i == 0) { // check if directory empty delete it. Because of all files older than 10yers then directory older too. // you can use your logic for checking directory is empty or not
  FileUtils.forceDelete(new File(dirWay));
}

public static void forceDelete(File file)
                        throws IOException

Deletes a file. If file is a directory, delete it and all sub-directories. https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)


问:
What is the correct way to include React in both an application and a private library? (React Invalid Hook Call warning from duplicate React)
I have a sort of a "monorepo", one big project consisting of a few smaller projects that use React.

I'm trying to break these up into three separate repositories, lets call them Core, Application1, and Application2

The Core is a dependency of both applications, and the Core depends on React, because it defines some React component classes.  The applications both also use React.

When I tried to build this all together (using Parcel bundler), I am getting a final bundle which at runtime gives the Invalid Hook Call warning in one (but not both) of the applications.

On that page (or in the error message), it says that the error could be caused by one o these:

You might have mismatching versions of React and React DOM.

You might be breaking the Rules of Hooks.

You might have more than one copy of React in the same app.

I have checked that #1 is not true, and I'm not even using hooks in any way that I am aware of, so the problem is seems to be multiple versions of React.

I gathered from reading about this that it was a mistake for my Core library to declare React as a dependency, and that it should instead declare it in peerDependencies.  That made the Application stop giving the error, but it also made my Core library start having a bunch of Typescript errors and failing to be able to run the unit tests (which rely on React, using Jest/Enzyme to render and validate DOM).

Since specifying React in peerDependencies caused it not to be installed in the node_modules of Core, I decided that I should probably include React in both the peerDependencies and the devDependencies of Core.  That fixes the Core library again but breaks the Application.

I'm not really sure of the following:

Why one of my applications fail due to duplicate React copies and the other doesn't, since they seem pretty symmetrical to each other.

Why, even though I only specify React in peerDependencies and devDepenencies in Core I still would get a duplicate copy of React in the dependent application

Whether the method used to bring Core in to the application has any bearing on this.  (one method I'm trying is package.json I specify core as a "file:../" style of URL.  Another alternative is to use "yarn link", or possibly to do both of these, and I'm not sure whether this has any effect on what ends up in node_modules underneath the application folder or on what gets bundled)

What is the right way to include React in both an Application and a library, in such a way that both of those projects have React available but there does not end up being duplicates in the Application causing this hook error (or, just taking up extra space).

答:
Answering my own question.

I found the following issue helpful: https://github.com/facebook/react/issues/14257

Various different suggestions were made in the comments of ways to solve this problem, either by npm link or yarn linking the react library from the library to the application, or vice versa.  Those all seemed promising, since the idea is to make sure that all of the different references to React are actually pointing to the same place.  Unfortunately none of those worked for me. (e.g. the answers by JerryGreen and Kas in that issue)

Another user, dcecile, suggested using webpack's alias feature, but I'm not using webpack.

```<code>resolve: {
    alias: { react: require.resolve("react") }
},
</code>```

Parcel has a similar alias feature but can't be used in quite the same way because it's used in the package.json file so things like require.resolve can't be called like they are in webpack's js config file.

I ended up finding a way to use Parcel's alias feature to do what I wanted, based on another example from https://github.com/jaredpalmer/tsdx/issues/64 from user jaredpalmer.  In my situation, I'm adding this to the application's package.json, and it appears to get rid of the duplication problem and the "Invalid Hook Call" error:

```<code> "alias": {
    "react": "../my-core-library/node_modules/react",
  },
</code>```

Body:
Answering my own question.

I found the following issue helpful: https://github.com/facebook/react/issues/14257

Various different suggestions were made in the comments of ways to solve this problem, either by npm link or yarn linking the react library from the library to the application, or vice versa.  Those all seemed promising, since the idea is to make sure that all of the different references to React are actually pointing to the same place.  Unfortunately none of those worked for me. (e.g. the answers by JerryGreen and Kas in that issue)

Another user, dcecile, suggested using webpack's alias feature, but I'm not using webpack.

resolve: {
    alias: { react: require.resolve("react") }
},

Parcel has a similar alias feature but can't be used in quite the same way because it's used in the package.json file so things like require.resolve can't be called like they are in webpack's js config file.

I ended up finding a way to use Parcel's alias feature to do what I wanted, based on another example from https://github.com/jaredpalmer/tsdx/issues/64 from user jaredpalmer.  In my situation, I'm adding this to the application's package.json, and it appears to get rid of the duplication problem and the "Invalid Hook Call" error:

 "alias": {
    "react": "../my-core-library/node_modules/react",
  },


问:
How to return record base on page index parameter?
I'm working on index. I want to return a records based on the page index.

What I'm doing right now see below

First I create the table Customers:

```<code>CREATE TABLE [dbo].[Customers]
(
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CompanyName] [nvarchar](40) NOT NULL,
    [ContactName] [nvarchar](30) NULL,
    [ContactTitle] [nvarchar](30) NULL,
    [Address] [nvarchar](60) NULL,
    [City] [nvarchar](15) NULL,
    [Region] [nvarchar](15) NULL,
    [PostalCode] [nvarchar](10) NULL,
    [Country] [nvarchar](15) NULL,
    [Phone] [nvarchar](24) NULL,
    [Fax] [nvarchar](24) NULL,
    [NewsLetters] [bit] NULL,

    PRIMARY KEY(CustomerID)
)
</code>```

then I inserted 90 records and then I created the stored procedure:

```<code>CREATE PROCEDURE [dbo].[Get_Customers]
    @PageIndex int,
    @Pagesize int = 10
AS
BEGIN
    SELECT *
    FROM Customers
    ORDER BY CompanyName ASC
        OFFSET @PageIndex ROWS
        FETCH NEXT @Pagesize ROWS ONLY

    RETURN
END
</code>```

Issue is when I execute the stored procedure, it does not display the proper data based on the index.

```<code>DECLARE @PageIndex int, @Pagesize int = 10

EXEC Get_Customers 5,10        --here issue is displaying the data starting with the 5 to 14
</code>```

When I execute the stored procedure like this, it must return the records 51 to 63

```<code>DECLARE @PageIndex int, @Pagesize int = 10
EXEC Get_Customers 5,10
</code>```

I'm referring to and learning from the below article.

Primary key create automatically clustered index.

https://www.essentialsql.com/what-is-the-differenence-between-top-and-offset-fetch/

Which place need to correct?

答:
Your logic in the stored procedure is all wrong. You pass in @PageIndex and @PageSize - but you never multiply the two!

When you want to get page no. 0 - you need to OFFSET by 0 rows.

When you want to get page no. 5 - you need to OFFSET by 5 * 10 = 50 rows - by @PageIndex * @PageSize - not just by @PageIndex (that is only 5)

Try something like this:

```<code>CREATE PROCEDURE [dbo].[Get_Customers]
    @PageIndex int,
    @Pagesize int = 10
AS
BEGIN
    SELECT *
    FROM Customers
    ORDER BY CompanyName ASC
        -- you need to offset by the **multiplication** of index and size!!!
        OFFSET @PageIndex * @PageSize ROWS
        FETCH NEXT @Pagesize ROWS ONLY

    RETURN
END
</code>```

With this, if you pass in @PageIndex = 5 and @PageSize = 10, your code will first skip the first 5 * 10 = 50 rows, and then return the next 10 rows (rows no. 51 - 60).

Body:
I'm working on index. I want to return a records based on the page index.

What I'm doing right now see below

First I create the table Customers:

CREATE TABLE [dbo].[Customers]
(
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CompanyName] [nvarchar](40) NOT NULL,
    [ContactName] [nvarchar](30) NULL,
    [ContactTitle] [nvarchar](30) NULL,
    [Address] [nvarchar](60) NULL,
    [City] [nvarchar](15) NULL,
    [Region] [nvarchar](15) NULL,
    [PostalCode] [nvarchar](10) NULL,
    [Country] [nvarchar](15) NULL,
    [Phone] [nvarchar](24) NULL,
    [Fax] [nvarchar](24) NULL,
    [NewsLetters] [bit] NULL,

    PRIMARY KEY(CustomerID)
)

then I inserted 90 records and then I created the stored procedure:

CREATE PROCEDURE [dbo].[Get_Customers]
    @PageIndex int,
    @Pagesize int = 10
AS
BEGIN
    SELECT *
    FROM Customers
    ORDER BY CompanyName ASC
        OFFSET @PageIndex ROWS
        FETCH NEXT @Pagesize ROWS ONLY

    RETURN
END

Issue is when I execute the stored procedure, it does not display the proper data based on the index.

DECLARE @PageIndex int, @Pagesize int = 10

EXEC Get_Customers 5,10        --here issue is displaying the data starting with the 5 to 14

When I execute the stored procedure like this, it must return the records 51 to 63

DECLARE @PageIndex int, @Pagesize int = 10
EXEC Get_Customers 5,10

I'm referring to and learning from the below article.

Primary key create automatically clustered index.

https://www.essentialsql.com/what-is-the-differenence-between-top-and-offset-fetch/

Which place need to correct?

Body:
Your logic in the stored procedure is all wrong. You pass in @PageIndex and @PageSize - but you never multiply the two!

When you want to get page no. 0 - you need to OFFSET by 0 rows.

When you want to get page no. 5 - you need to OFFSET by 5 * 10 = 50 rows - by @PageIndex * @PageSize - not just by @PageIndex (that is only 5)

Try something like this:

CREATE PROCEDURE [dbo].[Get_Customers]
    @PageIndex int,
    @Pagesize int = 10
AS
BEGIN
    SELECT *
    FROM Customers
    ORDER BY CompanyName ASC
        -- you need to offset by the **multiplication** of index and size!!!
        OFFSET @PageIndex * @PageSize ROWS
        FETCH NEXT @Pagesize ROWS ONLY

    RETURN
END

With this, if you pass in @PageIndex = 5 and @PageSize = 10, your code will first skip the first 5 * 10 = 50 rows, and then return the next 10 rows (rows no. 51 - 60).


问:
Which framework is better for UI Testing React testing library or python robot framework?
Can someone please help me with this, Which framework we can use for UI testing i.e React testing library or Python robot framework?
As per my understanding if we are proceeding with multiple data-driven operations python robot framework is better then react testing library.</p>

答:
react-testing-library vs Robot Framework: What are the differences?

react-testing-library: A lightweight solution for testing React components. It is a simple and complete React DOM testing utility that encourage good testing practices. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices; Robot Framework: A test automation framework for acceptance testing and ATDD. It is a generic test automation framework for acceptance testing and acceptance test-driven development. It has easy-to-use tabular test data syntax and it utilizes the keyword-driven testing approach. Its testing capabilities can be extended by test libraries implemented either with Python or Java, and users can create new higher-level keywords from existing ones using the same syntax that is used for creating test cases.

https://stackshare.io/stackups/react-testing-library-vs-robot-frame-work


问:
Check Contact Number and Email is fake or not?
Is there any way to find out number or mail entered by user is fake or not?
Using angular7 anf firebase?</p>

答:
Then you can only make email validation that send email which contains validation link ,
Then search mailchimp services for this to send emails. Generally services allows to limited numbers as free.

for mobile send sms contains pin code to validate it.Then search sms services for this.

You should solve this backend part not angular part for security issues.

There is no way without using sms and email services.


问:
XMLHttpRequest from VBA returns error 406 "Not Accepted"
I'm trying to do some scraping using Excel VBA, specifically, to get a JSON from a server.
I'm using exactly the same request headers that show on the browsers dev tools, but when I do this request from Excel I always get a 406 ("Not accepted") answer from the server.
What am I missing?

```<code>Sub getJSON()

   Dim XHR As New MSXML2.ServerXMLHTTP60

   XHR.Open "GET", "https://www.magazineluiza.com.br/produto/calculo-frete/08226021/615254900/frigelar.json", False

   XHR.setRequestHeader "Host", "www.magazineluiza.com.br"
   XHR.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0"
   XHR.setRequestHeader "Accept", "application/json, text/javascript, */*; q=0.01"
   XHR.setRequestHeader "Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3"
   XHR.setRequestHeader "Accept-Encoding", "gzip, deflate, br"
   XHR.setRequestHeader "X-Requested-With", "XMLHttpRequest"
   XHR.setRequestHeader "Connection", "keep-alive"
   XHR.setRequestHeader "Referer", "https://www.magazineluiza.com.br/refrigerador-expositor-para-bebidas-metalfrio-com-controlador-eletronico-497-litros-vb52r-220v/p/6152549/pi/expb/"
   XHR.setRequestHeader "TE", "Trailers"

   XHR.send

   Debug.Print XHR.responseText

End Sub
</code>```

This is the answer I get on the browser:

```<code>{"address":{"address":"18 DE ABRIL","area":"CIDADE ANTONIO ESTEVAO DE CARVALHO","city":"SAO PAULO","state":"SP","zip_code":"08226021"},"delivery":[{"description":"Entrega padrão","distribution_center":0,"is_deadline":true,"price":"263.91","time":13,"zip_code_restriction":false}],"is_delivery_unavailable":false,"zip_code":"08226021"}
</code>```

Edit: This JSON is retrieved by the browser when I add the zip code "08226021" on the right side of this page and click "Ok".

答:
Try this to get the required response:

```<code>Sub FetchJsonResponse()
    Const Url$ = "https://www.magazineluiza.com.br/produto/calculo-frete/08226021/615254900/frigelar.json"

    With CreateObject("WinHttp.WinHttpRequest.5.1")
        .Open "GET", Url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
        .setRequestHeader "Referer", "https://www.magazineluiza.com.br/refrigerador-expositor-para-bebidas-metalfrio-com-controlador-eletronico-497-litros-vb52r-220v/p/6152549/pi/expb/"
        .setRequestHeader "x-requested-with", "XMLHttpRequest"
        .send
        Debug.Print .responseText
    End With
End Sub
</code>```

This is the output it produces:

```<code>{"address": {"address": "18 DE ABRIL", "area": "CIDADE ANTONIO ESTEVAO DE CARVALHO", "city": "SAO PAULO", "state": "SP", "zip_code": "08226021"}, "delivery": [{"description": "Entrega padr\u00e3o", "distribution_center": 0, "is_deadline": true, "price": "263.91", "time": 13, "zip_code_restriction": false}], "is_delivery_unavailable": false, "zip_code": "08226021"}
</code>```

Body:
I'm trying to do some scraping using Excel VBA, specifically, to get a JSON from a server.
I'm using exactly the same request headers that show on the browsers dev tools, but when I do this request from Excel I always get a 406 ("Not accepted") answer from the server.
What am I missing?

Sub getJSON()

   Dim XHR As New MSXML2.ServerXMLHTTP60

   XHR.Open "GET", "https://www.magazineluiza.com.br/produto/calculo-frete/08226021/615254900/frigelar.json", False

   XHR.setRequestHeader "Host", "www.magazineluiza.com.br"
   XHR.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0"
   XHR.setRequestHeader "Accept", "application/json, text/javascript, */*; q=0.01"
   XHR.setRequestHeader "Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3"
   XHR.setRequestHeader "Accept-Encoding", "gzip, deflate, br"
   XHR.setRequestHeader "X-Requested-With", "XMLHttpRequest"
   XHR.setRequestHeader "Connection", "keep-alive"
   XHR.setRequestHeader "Referer", "https://www.magazineluiza.com.br/refrigerador-expositor-para-bebidas-metalfrio-com-controlador-eletronico-497-litros-vb52r-220v/p/6152549/pi/expb/"
   XHR.setRequestHeader "TE", "Trailers"

   XHR.send

   Debug.Print XHR.responseText

End Sub

This is the answer I get on the browser:

{"address":{"address":"18 DE ABRIL","area":"CIDADE ANTONIO ESTEVAO DE CARVALHO","city":"SAO PAULO","state":"SP","zip_code":"08226021"},"delivery":[{"description":"Entrega padrão","distribution_center":0,"is_deadline":true,"price":"263.91","time":13,"zip_code_restriction":false}],"is_delivery_unavailable":false,"zip_code":"08226021"}

Edit: This JSON is retrieved by the browser when I add the zip code "08226021" on the right side of this page and click "Ok".

Body:
Try this to get the required response:

Sub FetchJsonResponse()
    Const Url$ = "https://www.magazineluiza.com.br/produto/calculo-frete/08226021/615254900/frigelar.json"

    With CreateObject("WinHttp.WinHttpRequest.5.1")
        .Open "GET", Url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
        .setRequestHeader "Referer", "https://www.magazineluiza.com.br/refrigerador-expositor-para-bebidas-metalfrio-com-controlador-eletronico-497-litros-vb52r-220v/p/6152549/pi/expb/"
        .setRequestHeader "x-requested-with", "XMLHttpRequest"
        .send
        Debug.Print .responseText
    End With
End Sub

This is the output it produces:

{"address": {"address": "18 DE ABRIL", "area": "CIDADE ANTONIO ESTEVAO DE CARVALHO", "city": "SAO PAULO", "state": "SP", "zip_code": "08226021"}, "delivery": [{"description": "Entrega padr\u00e3o", "distribution_center": 0, "is_deadline": true, "price": "263.91", "time": 13, "zip_code_restriction": false}], "is_delivery_unavailable": false, "zip_code": "08226021"}


问:
ModuleNotFoundError: No module named 'google.appengine'
I want to do a google search in python3 on windows. The google instructions say they support python3 and to type "gcloud topic init" for details - but that fails saying no interpreter for python2.7. Do I have to install python2.7 to find out how to get it working on python3?

On python3 I get an error message as below. I have set up an API key and a Custom search engine. I did "pip install google-api-python-client". I downloaded and ran GoogleCloudSDKInstaller. This is the error:

```<code>from googleapiclient.discovery import build
service = build("customsearch", "v1", developerKey="xxxxxx")
</code>```

I get:

```<code>[googleapiclient.discovery_cache:WARNING]:file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth (__init__.py:44, time=Apr-07 17:25) Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\__init__.py", line 36, in autodetect
    from google.appengine.api import memcache ModuleNotFoundError: No module named 'google.appengine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile ModuleNotFoundError: No module named 'oauth2client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile ModuleNotFoundError: No module named 'oauth2client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\__init__.py", line 41, in autodetect
    from . import file_cache   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth') ImportError: file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth [googleapiclient.discovery:INFO]:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/customsearch/v1/rest?key=AIzaSyBGDtIo_P8xXbn0ksb15wUhy6sdR_eBDpU
</code>```

答:
Although it arrives looking like a cascading error, when looking closely at the first line, this is in fact only a warning:

[googleapiclient.discovery_cache:WARNING]:file_cache is unavailable...

As such, if you don't have access to the instantiation, you can suppress it like this:

import logging

logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

You will still get any actual errors.

With thanks to theacodes who gave that answer here

See also the discussion here

Body:
I want to do a google search in python3 on windows. The google instructions say they support python3 and to type "gcloud topic init" for details - but that fails saying no interpreter for python2.7. Do I have to install python2.7 to find out how to get it working on python3?

On python3 I get an error message as below. I have set up an API key and a Custom search engine. I did "pip install google-api-python-client". I downloaded and ran GoogleCloudSDKInstaller. This is the error:

from googleapiclient.discovery import build
service = build("customsearch", "v1", developerKey="xxxxxx")

I get:

[googleapiclient.discovery_cache:WARNING]:file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth (__init__.py:44, time=Apr-07 17:25) Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\__init__.py", line 36, in autodetect
    from google.appengine.api import memcache ModuleNotFoundError: No module named 'google.appengine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile ModuleNotFoundError: No module named 'oauth2client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile ModuleNotFoundError: No module named 'oauth2client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\__init__.py", line 41, in autodetect
    from . import file_cache   File "C:\Users\simon\Anaconda3\lib\site-packages\googleapiclient\discovery_cache\file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth') ImportError: file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth [googleapiclient.discovery:INFO]:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/customsearch/v1/rest?key=AIzaSyBGDtIo_P8xXbn0ksb15wUhy6sdR_eBDpU


问:
How do I remap keyboard shortcuts in UWP C# app?
For example, say I wanted to switch Ctrl+C and Ctrl+V so that Ctrl+C will paste and Ctrl+V will copy. I will need to first override Ctrl+Ccopying and then make Ctrl+C paste. I will have to do the same with Ctrl + V as well, except I will need to override the paste and make it copy.

How should I go about doing this? Is this possible in a UWP app using C#? Whenever I look up something along the lines of "remapping keyboard shortcuts in c#", it shows me results for remapping keyboard shortcuts in Visual Studio, not for in my app.

答:
>How do I remap keyboard shortcuts in UWP C# app?

It is a little complicated but you could do it in your app. You need to handle the keyboard input event - CoreWindow.KeyDown Event first. In the input event, check both if the control key is pressed and if the C key is pressed. When both of them are pressed, then you could do your own logic in the event handler.

Here is a sample code about how to handle the keydown event.

```<code>  Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

 private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
        if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && args.VirtualKey == VirtualKey.V)
        {
            //clean the data in the clipboard.
            Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
            // do your stuff
            Debug.WriteLine("Ctr+V");
            return;
        } else if(ctrl.HasFlag(CoreVirtualKeyStates.Down) && args.VirtualKey == VirtualKey.C)
        {
            //clean the data in the clipboard.
            Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
            // do your stuff
            Debug.WriteLine("Ctr+C");
            return;
        }
    }
</code>```

Body:
>How do I remap keyboard shortcuts in UWP C# app?

It is a little complicated but you could do it in your app. You need to handle the keyboard input event - CoreWindow.KeyDown Event first. In the input event, check both if the control key is pressed and if the C key is pressed. When both of them are pressed, then you could do your own logic in the event handler.

Here is a sample code about how to handle the keydown event.

  Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

 private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
        if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && args.VirtualKey == VirtualKey.V)
        {
            //clean the data in the clipboard.
            Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
            // do your stuff
            Debug.WriteLine("Ctr+V");
            return;
        } else if(ctrl.HasFlag(CoreVirtualKeyStates.Down) && args.VirtualKey == VirtualKey.C)
        {
            //clean the data in the clipboard.
            Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
            // do your stuff
            Debug.WriteLine("Ctr+C");
            return;
        }
    }


问:
How to pass data from functional component to class component
I am new to ReactJS and have created a functional component for user input data(date and select).
Another class component to invoke the APIs from the user input data. I need to pass the input values from functional component to class component.

Can you please help?

Below is the snippet for functional component with input fields. The setShowGetAPI is initially set to false and will be true once the user clicks submit button.Please let me know if the condition is correct

```<code>  const [showTable, setshowTable] = useState("hidetable");
const [showGetAPI, setShowGetAPI] = React.useState("false");

  const [startDate, setStartDate] = useState(false);
  const [endDate, setendDate] = useState(false);
  const [expenseType, setexpenseType] = useState(false);

const showMessage = () => {
    setshowTable("");
    setShowGetAPI("true");
  };

  debugger;
  const handleEndDate = (e) => {
    setendDate(e.target.value);
  };

  const handleStartDate = (e) => {
    setStartDate(e.target.value);
  };

  const handleType = (e) => {
    console.log(e.target.value);
    setexpenseType(e.target.value);
  };
  console.log(endDate);

  return (
    <div>
      <Navbar color="info" light expand="md">
        <Nav color="info" navbar>
          <NavItem className="hdr">
            <NavLink>API Demo Tool</NavLink>
          </NavItem>
        </Nav>
      </Navbar>
      <Nav tabs>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "1" }}
            onClick={() => {
              toggle("1");
            }}
          >
            Request
          </NavLink>
        </NavItem>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "2" }}
            onClick={() => {
              toggle("2");
            }}
          >
            Receipt
          </NavLink>
        </NavItem>
      </Nav>
      <TabContent activeTab={activeTab}>

        <TabPane tabId="2">
          <br />
          <Form>
            <FormGroup row>
              <Label for="Start Date" sm={1}>
                Start Date
              </Label>
              <Col sm={2}>
                <Input
                  type="date"
                  name="startDate"
                  id="startDate"
                  placeholder="startDate"
                  value={startDate}
                  onChange={handleStartDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label for="End Date" sm={1}>
                End Date
              </Label>
              <Col sm={2}>
                <Input
                  type="date"
                  name="endDate"
                  id="endDate"
                  value={endDate}
                  placeholder="endDate"
                  onChange={handleEndDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label for="Segment" sm={1}>
                Expense Type
              </Label>
              <Col sm={2}>
                <Input
                  type="select"
                  name="expenseType"
                  value={expenseType}
                  id=" expenseType"
                  onChange={handleType}
                >
                  <option>Hotel</option>
                  <option>Airfare</option>
                  <option>Rail</option>
                  <option>All</option>
                </Input>
              </Col>
            </FormGroup>
            <FormGroup check row>
              <Col sm={{ size: 10, offset: 1 }}>
                <Button onClick={showMessage}>Submit</Button>
              </Col>
            </FormGroup>
          </Form>
          <div>

            {showGetAPI == "true" && (
            <div>
              <GetAPI
                startDt={startDate}
                endDt={endDate}
                exptype={expenseType}
              />
            </div>
          )}
          </div>
          <div class={showTable}>
            <Table></Table>
          </div>
        </TabPane>
      </TabContent>
    </div>
  );
};

export default TabsDemo;
</code>```

GETAPI- This is a class component where i need the inputs values from above functional component to invoke the API with req. params

```<code>class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      ReportEntryID: [],
      token: null,
      Url: [
        {
          Url: "",
        },
      ],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
    return <h1> {this.props.startdate}</h1>;
  }
}

export default GetAPI;
</code>```

答:
You are passing the data from your functional component in the class component via props. So you should be able to access the data in your GetAPI class component like:

```<code>this.props.startDt
this.props.endDt
this.props.exptype
</code>```

In your GetApi function, you are rendering:

```<code>render() {
    return <h1> {this.props.startdate}</h1>;
}
</code>```

Instead, you are passing startDt, so you should be doing:

```<code>render() {
    return <h1> {this.props.startDt}</h1>;
}
</code>```

Body:
I am new to ReactJS and have created a functional component for user input data(date and select).
Another class component to invoke the APIs from the user input data. I need to pass the input values from functional component to class component.

Can you please help?

Below is the snippet for functional component with input fields. The setShowGetAPI is initially set to false and will be true once the user clicks submit button.Please let me know if the condition is correct

  const [showTable, setshowTable] = useState("hidetable");
const [showGetAPI, setShowGetAPI] = React.useState("false");

  const [startDate, setStartDate] = useState(false);
  const [endDate, setendDate] = useState(false);
  const [expenseType, setexpenseType] = useState(false);

const showMessage = () => {
    setshowTable("");
    setShowGetAPI("true");
  };

  debugger;
  const handleEndDate = (e) => {
    setendDate(e.target.value);
  };

  const handleStartDate = (e) => {
    setStartDate(e.target.value);
  };

  const handleType = (e) => {
    console.log(e.target.value);
    setexpenseType(e.target.value);
  };
  console.log(endDate);

  return (

      <Navbar color="info" light expand="md">

          <NavItem className="hdr">
            <NavLink>API Demo Tool</NavLink>
          </NavItem>

      </Navbar>

        <NavItem>
          <NavLink
            className={{ active: activeTab === "1" }}
            onClick={() => {
              toggle("1");
            }}
          >
            Request
          </NavLink>
        </NavItem>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "2" }}
            onClick={() => {
              toggle("2");
            }}
          >
            Receipt
          </NavLink>
        </NavItem>

      <TabContent activeTab={activeTab}>

        <TabPane tabId="2">

          <Form>
            <FormGroup row>

                Start Date

              <Col sm={2}>
                <Input
                  type="date"
                  name="startDate"
                  id="startDate"
                  placeholder="startDate"
                  value={startDate}
                  onChange={handleStartDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>

                End Date

              <Col sm={2}>
                <Input
                  type="date"
                  name="endDate"
                  id="endDate"
                  value={endDate}
                  placeholder="endDate"
                  onChange={handleEndDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>

                Expense Type

              <Col sm={2}>
                <Input
                  type="select"
                  name="expenseType"
                  value={expenseType}
                  id=" expenseType"
                  onChange={handleType}
                >
                  <option>Hotel</option>
                  <option>Airfare</option>
                  <option>Rail</option>
                  <option>All</option>
                </Input>
              </Col>
            </FormGroup>
            <FormGroup check row>
              <Col sm={{ size: 10, offset: 1 }}>
                <Button onClick={showMessage}>Submit</Button>
              </Col>
            </FormGroup>
          </Form>

            {showGetAPI == "true" && (

              <GetAPI
                startDt={startDate}
                endDt={endDate}
                exptype={expenseType}
              />

          )}

        </TabPane>
      </TabContent>

  );
};

export default TabsDemo;

GETAPI- This is a class component where i need the inputs values from above functional component to invoke the API with req. params

class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      ReportEntryID: [],
      token: null,
      Url: [
        {
          Url: "",
        },
      ],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
    return
 {this.props.startdate}
;
  }
}

export default GetAPI;

Body:
You are passing the data from your functional component in the class component via props. So you should be able to access the data in your GetAPI class component like:

this.props.startDt
this.props.endDt
this.props.exptype

In your GetApi function, you are rendering:

render() {
    return <h1> {this.props.startdate}</h1>;
}

Instead, you are passing startDt, so you should be doing:

render() {
    return <h1> {this.props.startDt}</h1>;
}


问:
Stuck in the middle
When should I use margin-left:auto; margin-right:auto to center and when should I use margin-left:50%; margin-right:50%?

Maybe "auto" when I am centering something contained in another element & 50% when I am centering on the page?

Or I am I just hopelessly confused?

答:
Or I am I just hopelessly confused?

Maybe :)

margin-left: 50%; margin-right: 50% is not generally useful: http://jsfiddle.net/VcDYr/

Where you might use margin-left: 50% is if you're centering like this: http://jsfiddle.net/VcDYr/1/

To "center the page", you invariably want margin-left: auto; margin-right: auto. A shorter way to write this is margin: 0 auto: http://jsfiddle.net/VcDYr/2/

Consider that div is a block-level element.

See: http://www.w3.org/TR/CSS21/box.html#margin-properties

auto - See the section on calculating
  widths and margins for behavior.

Which leads to: http://www.w3.org/TR/CSS21/visudet.html#Computing_widths_and_margins

Block-level, non-replaced elements in
  normal flow

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

Title: Stuck in the middle


问:
WooCommerce REST API v3 remote ordering and payment and sending all data into WP
I started creating a program where we can browse products by category. Add items to our cart (in messenger) and update cart etc.

We have Stripe / PayPal already connected to our App and would like to handle everything on our end, in the app. Then, when the order is completed, send the entire order as the data array into WP.

A few questions since I'm stuck.

I'd use this part from the API docs:
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-an-order

```<code><?php
$data = [
    'payment_method' => 'bacs',
    'payment_method_title' => 'Direct Bank Transfer',
    'set_paid' => true,
    'billing' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US',
        'email' => 'john.doe@example.com',
        'phone' => '(555) 555-5555'
    ],
    'shipping' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US'
    ],
    'line_items' => [
        [
            'product_id' => 93,
            'quantity' => 2
        ],
        [
            'product_id' => 22,
            'variation_id' => 23,
            'quantity' => 1
        ]
    ],
    'shipping_lines' => [
        [
            'method_id' => 'flat_rate',
            'method_title' => 'Flat Rate',
            'total' => 10
        ]
    ]
];

print_r($woocommerce->post('orders', $data));
</code>```

I have some issues with that though. I haven't tested it yet because we use it on a live store, but I'd like to know some stuff that isn't mentioned anywhere. Except for when using a 3rd party plugin, which we don't want. We want to only use the native, clean WooCommerce plugin.

• Is it possible to use a payment method as the reference, even though it does not exist in WP itself? So, if we use Stripe to create and pay for the order in messenger even though Stripe itself isn't in use in our store, can we still push that as the payment reference in the $data array here:

```<code>'payment_method' => 'stripe',
'payment_method_title' => 'Offsite Payment Method',
</code>```

I read you need to create the order first normally if you want to get the payment token, and then update the status after payment, but since we're doing the entire ordering and payment processing offsite (only utilizing the WooCommerce catalog) and want to shoot in the order after a successful ordering process outside of WP, I'm a bit puzzled.

There's a lot of info to be found about missing cart features unless you use something like cocart, which we don't want since we can't ask customers to all install another to be able to use our tool.

Anybody came across a similar use case?

答:
Is it possible to use a payment method as the reference, even though it does not exist in WP itself?

Yes, they are basically strings you can pass any data which is of string type it doesn't matter whether it exists in wp or not

And as you said "you need to create the order first normally if you want to get the payment token, and then update the status after payment"

This is true first you need to create order ..

Why ?

Because in most of the payment gateways there will be a field called orderId to bind order id with that transaction and to keep things clean it's used ...So you need to create an order first when you create the order you need to set the status to pending. Then you will get orderId now redirect the user to payment gateway. Once user comes back again update the order status to processing if it success or failure if it failed

Body:
I started creating a program where we can browse products by category. Add items to our cart (in messenger) and update cart etc.

We have Stripe / PayPal already connected to our App and would like to handle everything on our end, in the app. Then, when the order is completed, send the entire order as the data array into WP.

A few questions since I'm stuck.

I'd use this part from the API docs:
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-an-order

<?php
$data = [
    'payment_method' => 'bacs',
    'payment_method_title' => 'Direct Bank Transfer',
    'set_paid' => true,
    'billing' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US',
        'email' => 'john.doe@example.com',
        'phone' => '(555) 555-5555'
    ],
    'shipping' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US'
    ],
    'line_items' => [
        [
            'product_id' => 93,
            'quantity' => 2
        ],
        [
            'product_id' => 22,
            'variation_id' => 23,
            'quantity' => 1
        ]
    ],
    'shipping_lines' => [
        [
            'method_id' => 'flat_rate',
            'method_title' => 'Flat Rate',
            'total' => 10
        ]
    ]
];

print_r($woocommerce->post('orders', $data));

I have some issues with that though. I haven't tested it yet because we use it on a live store, but I'd like to know some stuff that isn't mentioned anywhere. Except for when using a 3rd party plugin, which we don't want. We want to only use the native, clean WooCommerce plugin.

• Is it possible to use a payment method as the reference, even though it does not exist in WP itself? So, if we use Stripe to create and pay for the order in messenger even though Stripe itself isn't in use in our store, can we still push that as the payment reference in the $data array here:

'payment_method' => 'stripe',
'payment_method_title' => 'Offsite Payment Method',

I read you need to create the order first normally if you want to get the payment token, and then update the status after payment, but since we're doing the entire ordering and payment processing offsite (only utilizing the WooCommerce catalog) and want to shoot in the order after a successful ordering process outside of WP, I'm a bit puzzled.

There's a lot of info to be found about missing cart features unless you use something like cocart, which we don't want since we can't ask customers to all install another to be able to use our tool.

Anybody came across a similar use case?


问:
"App not setup: This app is still in development mode" Ionic 4 Facebook login
I Created my Ionic 4 app with facebook login

everything is fine expect when I make login with facebook

I got thes message "App not setuo: This app is still in development mode"

and my app is already in live mode

I don't know if this is a facebook bug or something wrong with my app?

答: I solved it by removing the platform and added it again </p>


问:
Azure Application Gateway : Backend server certificate expired. Please upload a valid certificate
We have an Azure Application Gateway V2 setup with WAF feature enabled. We ran into trouble when suddenly, the health of all our backend pools (3 in our case) started showing unhealthy and the error was being shown when we checked backend health:

Backend server certificate expired. Please upload a valid certificate.

Now, the same certificate is applied on application gateway and on the backend pool servers/VMs. We had to switch to non-SSL port for our backend servers to make the problem go away.

I am not able to pinpoint the problem as if any certificate is expired when applied to backend pool VM should give the same error once applied to the application gateway itself. Can someone help to identify the actual root cause of the problem and why it is showing error only at the backend pool level?

Very important thing is that the certificates being shown in browser when the backend pool URL is opened is showing still more than 2 months before it expires.

Thanks.

答: Same thing happened with my web app (roughly at the same time as reported by you) hosted on Azure which is also behind an Application Gateway V2 setup with WAF enabled. Taking a restart of the web app resolved the error.</p>


问:
why 'exec' is behaving different inside the function?
My Question

My solution:

```<code>import re
import math
a = input().replace("|","")
op = re.findall("[A-Z]+", a)[0]
a = list(map(float,re.split(r'P|S|M|D',a)))
expressions = {'P':'str(a[0]+a[1])','S':'str(a[0]-a[1])','M':'str(a[0]*a[1])','D':'str(a[0]/a[1])'}
exec('ex = eval(expressions[op])+"0"')
ex = ex[:ex.find(".")+3][::-1]
l = [6]
l.extend([6+3*x for x in range(1,(len(ex)-6)//2+1)])
if ex[-1]=="-":
    l.pop()
for i in l:
    ex = ex[:i] + "|" + ex[i:]
ex = ex[::-1]
ex = "0"+ex.strip("|") if ex.find("|")==1 else ex.strip("|")
print(ex)
</code>```

The issue:

If I wrap this code inside a function who take string input and try to return my ex the code shows error and nothing is changed.My question is , can anyone explain why this works perfect alone and throws error when wrapped inside a function?

答:
This is discussed on execs interaction with locals. In the global context (not in a function) there is no problem - exec modifies global variables, and you see the result. In a function the execution context is the local function, but exec cannot change the local context. The usual work around is to pass a local context where you can see the changes:

```<code>local_context = {}
exec('ex = eval(expressions[op])+"0"', locals(), local_context)
ex = local_context['ex']
</code>```

Here, the second parameter locals() is in fact passed as a "globals" to exec. This is so stuff like expressions and op are available. Passing globals() here is usually not useful unless you are actually using a global variable or some other function.

The third parameter is the locals exec can use, and what will be populated. If you pass globals() as the second parameter, then usually you want to pass local variables you intend to use here as well. Passing locals() here will not modify your actual locals, so is usually more confusing.

Note using

```<code>exec('global ex; ex = eval(expressions[op])+"0"')
global ex # Need this to make sure the function knows about the new global variable in its local context
</code>```

will work and create a global ex variable with the correct content. This is why exec works out of a function as you expect, in the global context there is no problem in modifying the current context. Note the function itself needs to be told to add a global ex to its local context, hence two globals.

Note the defaults is for the locals to be locals() and globals to be globals() if nothing is given, and if only the globals are given then the locals will equal that as well.

Body:
My Question

My solution:

import re
import math
a = input().replace("|","")
op = re.findall("[A-Z]+", a)[0]
a = list(map(float,re.split(r'P|S|M|D',a)))
expressions = {'P':'str(a[0]+a[1])','S':'str(a[0]-a[1])','M':'str(a[0]*a[1])','D':'str(a[0]/a[1])'}
exec('ex = eval(expressions[op])+"0"')
ex = ex[:ex.find(".")+3][::-1]
l = [6]
l.extend([6+3*x for x in range(1,(len(ex)-6)//2+1)])
if ex[-1]=="-":
    l.pop()
for i in l:
    ex = ex[:i] + "|" + ex[i:]
ex = ex[::-1]
ex = "0"+ex.strip("|") if ex.find("|")==1 else ex.strip("|")
print(ex)

The issue:

If I wrap this code inside a function who take string input and try to return my ex the code shows error and nothing is changed.My question is , can anyone explain why this works perfect alone and throws error when wrapped inside a function?

Body:
This is discussed on execs interaction with locals. In the global context (not in a function) there is no problem - exec modifies global variables, and you see the result. In a function the execution context is the local function, but exec cannot change the local context. The usual work around is to pass a local context where you can see the changes:

local_context = {}
exec('ex = eval(expressions[op])+"0"', locals(), local_context)
ex = local_context['ex']

Here, the second parameter locals() is in fact passed as a "globals" to exec. This is so stuff like expressions and op are available. Passing globals() here is usually not useful unless you are actually using a global variable or some other function.

The third parameter is the locals exec can use, and what will be populated. If you pass globals() as the second parameter, then usually you want to pass local variables you intend to use here as well. Passing locals() here will not modify your actual locals, so is usually more confusing.

Note using

exec('global ex; ex = eval(expressions[op])+"0"')
global ex # Need this to make sure the function knows about the new global variable in its local context

will work and create a global ex variable with the correct content. This is why exec works out of a function as you expect, in the global context there is no problem in modifying the current context. Note the function itself needs to be told to add a global ex to its local context, hence two globals.

Note the defaults is for the locals to be locals() and globals to be globals() if nothing is given, and if only the globals are given then the locals will equal that as well.


问:
How can I extend the div content of my page to fit the screen?
take a look at it
-> the page (simulated).

```<code><!doctype html>
<html>
<head>
<style type=text/css media=all>
*{  margin:0; padding:0; }
#header
{
    background-color:orange;
    position:relative;
    top:0;
}
#header #image
{
    width:120px;
    height:120px;
    background-color:#000;
}
#content
{
    background-color:red;
}

#footer
{
    background-color:green;
}
</style>
</head>
<body>
    <div id=header>
        <div id=image></div><!-- emulating an image -->
    </div>
    <div id=content>
        <p> BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA</p>
    </div>
    <div id=footer>
        <p><center>Copyright</center></p>
    </div>
</body>
</html>
</code>```

I'd like to extend the div content that it can fit the whole page whatever if the content of the div is too short or too long I just want it to fit the height between the header and the footer (the footer is always laying on the bottom) and if the content is too long for the page's height in that case then add a scrollbar, and if the window is resized then the content has to get the new height, I've intermingled my brushes

答:
You need some tweaks in the css and need to add some jquery code. this will solve the problem. Here is the working demo on JSFIDDLE

CSS:

```<code>*{    margin:0; padding:0; }

#header

{

    background-color:orange;

    position:relative;

    top:0;

}

#header #image

{

    width:120px;

    height:120px;

    background-color:#000;

}

#content

{

    background-color:red;
    width:100%;

}

#footer

{
    position:fixed;
    bottom:0;
    width:100%;
    background-color:green;

}
</code>```

jQuery:

```<code>$('#content').height(
     $(document).height()-$('#header').height()-$('#footer').height()
);
</code>```

Body:
take a look at it
-> the page (simulated).

<!doctype html>

 BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA

Copyright

I'd like to extend the div content that it can fit the whole page whatever if the content of the div is too short or too long I just want it to fit the height between the header and the footer (the footer is always laying on the bottom) and if the content is too long for the page's height in that case then add a scrollbar, and if the window is resized then the content has to get the new height, I've intermingled my brushes

Body:
You need some tweaks in the css and need to add some jquery code. this will solve the problem. Here is the working demo on JSFIDDLE

CSS:

*{    margin:0; padding:0; }

#header

{

    background-color:orange;

    position:relative;

    top:0;

}

#header #image

{

    width:120px;

    height:120px;

    background-color:#000;

}

#content

{

    background-color:red;
    width:100%;

}

#footer

{
    position:fixed;
    bottom:0;
    width:100%;
    background-color:green;

}

jQuery:

$('#content').height(
     $(document).height()-$('#header').height()-$('#footer').height()
);


问:
What does the localhost: 3000 server created by express mean?
What is it that you access when you type in "localhost: 3000" onto your browser? What does that represent? </p>

答: localhost:3000 is a local development server running on port 3000 of your computer. It is created by the express and can render html pages and route the apis for different requests. With the expressjs framework you can create different routes and associate it with the development or production port. You can also change the port during the development which can be done by changing the value of listening port on your app/index/server .js file.


问:
Can an Activity access a Fragment to know if a button has been pressed?
The Objective: I'm trying to make a notepad application. What my app does is, a button is pressed to create a new note. This pops up a fragment in which the user types his note. Within the same fragment, I have another button that signifies when the user is done typing.

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

Thank you for your help.

答:
For triggering a method on click of a button in fragment, there are number of ways to achieve this. Try this.

```<code>If (getActivity() instanceof MainActivity){
     //Getting instance of your activity
     MainActivity instance = ((MainActivity)getActivity());
     //Using the instance calling the method in your activity
     instance.methodName();
}
</code>```

Use the above code in your fragment on button click.

Another way is using Interface, calling its abstract methods in fragment and overriding it MainActivity; on button click those methods will be called.

Or you can also try using RxEventBus. You can publish it in the fragment and listen in the MainActivity.

Hope this resolves your issue.

Body:
For triggering a method on click of a button in fragment, there are number of ways to achieve this. Try this.

If (getActivity() instanceof MainActivity){
     //Getting instance of your activity
     MainActivity instance = ((MainActivity)getActivity());
     //Using the instance calling the method in your activity
     instance.methodName();
}

Use the above code in your fragment on button click.

Another way is using Interface, calling its abstract methods in fragment and overriding it MainActivity; on button click those methods will be called.

Or you can also try using RxEventBus. You can publish it in the fragment and listen in the MainActivity.

Hope this resolves your issue.


问:
Is there a program that allows you to write "pretty" library tutorials?
I need to write tutorial for a library I wrote. The tutorial should also include code.
I wonder if there is a platform/application that provides a nice option for writing such tutorials with code?</p>

答: I would suggest write your documentation in Markdown syntax and publish the file on Github.</p>


问:
Laravel Call a middleware if another middleware fails
So I have been using Passport to handle any OAuth requests which works perfectly. However there are some scenarios where I do not need a user instance to request and API endpoint. Static lists etc. I have created a middleware for that and it works fine. And finally there are scenarios when pulling things like lists where i want to give developers the freedom to either use the Token or OAuth to post to those endpoints. And struggling on how to do that...

Anyone have any insights? I am thinking I could always call the Token middleware and then from the token middleware call the normal passport OAuth? Not really sure how i would go about doing that though.

Chaining would not work in this scenario because if one fails it would boot them out, where I want it to check for a token IF it does not exist THEN check OAuth token and follow normal behavior after that.

```<code>Route::group(['middleware' => 'token:auth:api',
</code>```

Not seeing anywhere in the docs on how to do this. But maybe I am missing something.

Cheers

Citti

答:
Below handle of middleware to check for normal token and otherwise send request to another middleware for authentication.
In api endpoint allows authorization token it can be either predefined token or an oauth token.</p>

```<code>public function handle($request, Closure $next)
    {
        if ($request->is('api/*')) {
            if($request->hasHeader('authorization')){
                $bearertoken = $request->bearerToken();
                $token = $request->header('authorization');
                if(!empty($bearertoken)){
                    return app(Authenticate::class)->handle($request, function ($request) use ($next) {
                        return $next($request);
                    },'api');
                }
                if(!empty($token)){
                    $client = Client::where('secret',$token)->first();
                    if(!empty($client)){
                        return $next($request);
                    }
                }
            }
            throw new APIException("Unauthorized Access.");
        }

        return $next($request);
    }
</code>```

Body:
So I have been using Passport to handle any OAuth requests which works perfectly. However there are some scenarios where I do not need a user instance to request and API endpoint. Static lists etc. I have created a middleware for that and it works fine. And finally there are scenarios when pulling things like lists where i want to give developers the freedom to either use the Token or OAuth to post to those endpoints. And struggling on how to do that...

Anyone have any insights? I am thinking I could always call the Token middleware and then from the token middleware call the normal passport OAuth? Not really sure how i would go about doing that though.

Chaining would not work in this scenario because if one fails it would boot them out, where I want it to check for a token IF it does not exist THEN check OAuth token and follow normal behavior after that.

Route::group(['middleware' => 'token:auth:api',

Not seeing anywhere in the docs on how to do this. But maybe I am missing something.

Cheers

Citti

Body:
Below handle of middleware to check for normal token and otherwise send request to another middleware for authentication.
In api endpoint allows authorization token it can be either predefined token or an oauth token.

public function handle($request, Closure $next)
    {
        if ($request->is('api/*')) {
            if($request->hasHeader('authorization')){
                $bearertoken = $request->bearerToken();
                $token = $request->header('authorization');
                if(!empty($bearertoken)){
                    return app(Authenticate::class)->handle($request, function ($request) use ($next) {
                        return $next($request);
                    },'api');
                }
                if(!empty($token)){
                    $client = Client::where('secret',$token)->first();
                    if(!empty($client)){
                        return $next($request);
                    }
                }
            }
            throw new APIException("Unauthorized Access.");
        }

        return $next($request);
    }


问:
Python multiprocessing RuntimeError
I have a simple function that I intend to run in Parallel using the Python multiprocessing module. However I get the following error RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. The error suggests that I add this:

```<code>if __name__ == '__main__':
freeze_support()
</code>```

And most posts online suggest the same like this SO answer.

I added it and it works but I don't seem to understand why it's necessary for such a simple piece of code.

Code without __name__=="__main__" (throws RuntimeError)

```<code>import multiprocessing
import time

start = time.perf_counter()

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping...')

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)
p1.start()
p2.start()

finish = time.perf_counter()

print(f'Finished in {round(finish - start, 2)} second(s)')
</code>```

Code with __name__=="__main__" (doesn't throw RuntimeError)

```<code>import multiprocessing
import time

start = time.perf_counter()

def do_something():
  print('Sleeping 1 second...')
  time.sleep(1)
  print('Done sleeping...')

def main():
   p1 = multiprocessing.Process(target=do_something)
   p2 = multiprocessing.Process(target=do_something)
   p1.start()
   p2.start()

   finish = time.perf_counter()
   print(f'Finished in {round(finish - start, 2)} second(s)')

if __name__ == "__main__":
   main()
</code>```

答:
In Windows, multiprocessing.Process executes a fresh copy of python to run the code. It has to get the code you want to execute to load in that process so it pickles a snapshot of your current environment to expand in the child. For that to work, the child needs to reimport modules used by the parent. In particular, it needs to import the main script as a module. When you import, any code residing at module level executes.

So lets make the simplest case

foo.py

```<code>import multiprocessing as mp
process = mp.Process(target=print, args=('foo',))
process.start()
process.join()
</code>```

process.start() executes a new python which imports foo.py. And there's the problem. That new foo will create another subprocess which will again import foo.py. So yet another process is created.

The would go on until you blow up your machine except that python detects the problem and raises the exception.

THE FIX

Python modules have the __name__ attribute. If you run your program as a script, __name__ is "main", otherwise, __name__ is the name of your module. So, when a multiprocessing process is importing your main script to setup your environment, its name is not __main__. You can use that to make sure that your MP work is only done in the parent module.

```<code>import multiprocessing as mp

if __name__ == "__main__":
    # run as top level script, but not as imported module
    process = mp.Process(target=print, args=('foo',))
    process.start()
    process.join()
</code>```

Title: Python multiprocessing RuntimeError

Body:
I have a simple function that I intend to run in Parallel using the Python multiprocessing module. However I get the following error RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. The error suggests that I add this:

if __name__ == '__main__':
freeze_support()

And most posts online suggest the same like this SO answer.

I added it and it works but I don't seem to understand why it's necessary for such a simple piece of code.

Code without __name__=="__main__" (throws RuntimeError)

import multiprocessing
import time

start = time.perf_counter()

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping...')

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)
p1.start()
p2.start()

finish = time.perf_counter()

print(f'Finished in {round(finish - start, 2)} second(s)')

Code with __name__=="__main__" (doesn't throw RuntimeError)

import multiprocessing
import time

start = time.perf_counter()

def do_something():
  print('Sleeping 1 second...')
  time.sleep(1)
  print('Done sleeping...')

def main():
   p1 = multiprocessing.Process(target=do_something)
   p2 = multiprocessing.Process(target=do_something)
   p1.start()
   p2.start()

   finish = time.perf_counter()
   print(f'Finished in {round(finish - start, 2)} second(s)')

if __name__ == "__main__":
   main()

Body:
In Windows, multiprocessing.Process executes a fresh copy of python to run the code. It has to get the code you want to execute to load in that process so it pickles a snapshot of your current environment to expand in the child. For that to work, the child needs to reimport modules used by the parent. In particular, it needs to import the main script as a module. When you import, any code residing at module level executes.

So lets make the simplest case

foo.py

import multiprocessing as mp
process = mp.Process(target=print, args=('foo',))
process.start()
process.join()

process.start() executes a new python which imports foo.py. And there's the problem. That new foo will create another subprocess which will again import foo.py. So yet another process is created.

The would go on until you blow up your machine except that python detects the problem and raises the exception.

THE FIX

Python modules have the __name__ attribute. If you run your program as a script, __name__ is "main", otherwise, __name__ is the name of your module. So, when a multiprocessing process is importing your main script to setup your environment, its name is not __main__. You can use that to make sure that your MP work is only done in the parent module.

import multiprocessing as mp

if __name__ == "__main__":
    # run as top level script, but not as imported module
    process = mp.Process(target=print, args=('foo',))
    process.start()
    process.join()