问:
How to remove punctuation and numbers during TweetTokenizer step in NLP?
I am relatively new to NLP so please be gentle. I
have a complete list of the text from Trump's tweets since taking office and I am tokenizing the text to analyze the content.

I am using the TweetTokenizer from the nltk library in python and I'm trying to get everything tokenized except for numbers and punctuation. Problem is my code removes all the tokens except one.

I have tried using the .isalpha() method but this did not work, which I thought would as should only be True for strings composed from the alphabet.

#Create a content from the tweets
text= non_re['text']
#Make all text in lowercase
low_txt= [l.lower() for l in text]

#Iteratively tokenize the tweets
TokTweet= TweetTokenizer()
tokens= [TokTweet.tokenize(t) for t in low_txt
        if t.isalpha()]
```

My output from this is just one token.
If I remove the if t.isalpha() statement then I get all of the tokens including numbers and punctuation, suggesting the isalpha() is to blame from the over-trimming.

What I would like, is a way to get the tokens from the tweet text without punctuation and numbers.
Thanks for your help!

答:
```<code># Function for removing Punctuation from Text and It gives total no.of punctuation removed also
# Input: Function takes Existing fie name and New file name as string i.e 'existingFileName.txt' and 'newFileName.txt'
# Return: It returns two things Punctuation Free File opened in read mode and a punctuation count variable.

def removePunctuation(tokenizeSampleText, newFileName):

    from nltk.tokenize import word_tokenize
    existingFile = open(tokenizeSampleText, 'r')
    read_existingFile = existingFile.read()
    tokenize_existingFile = word_tokenize(read_existingFile)

    puncRemovedFile = open(newFileName, 'w+')

    import string
    stringPun = list(string.punctuation)
    count_pun = 0

    for word in tokenize_existingFile:
        if word in stringPun:
            count_pun += 1
        else:
            word = word + ' '
            puncRemovedFile.write(''.join(word))

    existingFile.close()
    puncRemovedFile.close()

    return open(newFileName, 'r'), count_pun

punRemoved, punCount = removePunctuation('Macbeth.txt', 'Macbeth-punctuationRemoved.txt')
print(f'Total Punctuation : {punCount}')
punRemoved.read()
</code>```

Body:
I am relatively new to NLP so please be gentle. I
have a complete list of the text from Trump's tweets since taking office and I am tokenizing the text to analyze the content.

I am using the TweetTokenizer from the nltk library in python and I'm trying to get everything tokenized except for numbers and punctuation. Problem is my code removes all the tokens except one.

I have tried using the .isalpha() method but this did not work, which I thought would as should only be True for strings composed from the alphabet.

#Create a content from the tweets
text= non_re['text']
#Make all text in lowercase
low_txt= [l.lower() for l in text]

#Iteratively tokenize the tweets
TokTweet= TweetTokenizer()
tokens= [TokTweet.tokenize(t) for t in low_txt
        if t.isalpha()]

My output from this is just one token.
If I remove the if t.isalpha() statement then I get all of the tokens including numbers and punctuation, suggesting the isalpha() is to blame from the over-trimming.

What I would like, is a way to get the tokens from the tweet text without punctuation and numbers.
Thanks for your help!


来源: stackexchange

问:
Remove file from latest commit
How do I remove a file from the latest commit?</p>

答:
From git 2.23 onwards, you can simply use this command:</p>
```<code>git restore --staged <file>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Remove file from latest commit

Body:
From git 2.23 onwards, you can simply use this command:

git restore --staged <file>


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

答:
CSS:

```<code>table {
  empty-cells: show;
}
</code>```

You also need to put IE in standards rendering mode for this to work. After adding a doctype, at least IE8 (Beta 2 and higher) plays nicely.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
</code>```

IE7 and below still won't do it. Support for empty-cells is said to be "partial" (for IE7 and IE8 Beta 1) on the MS CSS compatibility statement. Whatever "partial" means, not implementing "show" can hardly be called "partial support". These browsers can be forced to draw the cell borders by generally collapsing table borders:

```<code>table {
  border-collapse: collapse;
}
</code>```

The setting of empty-cells is ignored. But once you collapse the borders, you don't need to set that anyway, because all browsers will display collapsed borders.

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

Body:
CSS:

table {
  empty-cells: show;
}

You also need to put IE in standards rendering mode for this to work. After adding a doctype, at least IE8 (Beta 2 and higher) plays nicely.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

IE7 and below still won't do it. Support for empty-cells is said to be "partial" (for IE7 and IE8 Beta 1) on the MS CSS compatibility statement. Whatever "partial" means, not implementing "show" can hardly be called "partial support". These browsers can be forced to draw the cell borders by generally collapsing table borders:

table {
  border-collapse: collapse;
}

The setting of empty-cells is ignored. But once you collapse the borders, you don't need to set that anyway, because all browsers will display collapsed borders.

OwnerDisplayName: Tomalak

LastEditorDisplayName: Tomalak


问:
.htaccess redirect conflict wordpress /wp-admin
I will try to be the most specific as I can when I request help in solving this problem, though I don't have much knowledge about the configuration files used by Wordpress here!

The main folder in the website have this code in .htaccess as my objective was to remove .html from pages

```<code>RewriteOptions inherit
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{THE_REQUEST} \/index.html\ HTTP [NC]
RewriteRule (.*)index.html$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
</code>```

I've also installed wordpress to a /blog folder only inside the main folder. Now I can't access /wp-admin/ (*/blog/wp-admin/), and am receiving an ERR_TOO_MANY_REDIRECTS

How might I correct this?

答:
Replace your .htaccess content with this:</p>

```<code>RewriteOptions inherit
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [QSA,L]
</code>```

Body:
I will try to be the most specific as I can when I request help in solving this problem, though I don't have much knowledge about the configuration files used by Wordpress here!

The main folder in the website have this code in .htaccess as my objective was to remove .html from pages

RewriteOptions inherit
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{THE_REQUEST} \/index.html\ HTTP [NC]
RewriteRule (.*)index.html$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

I've also installed wordpress to a /blog folder only inside the main folder. Now I can't access /wp-admin/ (*/blog/wp-admin/), and am receiving an ERR_TOO_MANY_REDIRECTS

How might I correct this?

Body:
Replace your .htaccess content with this:

RewriteOptions inherit
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [QSA,L]


问:
Error sending AJAX POST request from local .html file to localhost:8080. CORS: "It does not have HTTP ok status."
I am getting an error when attempting to send a POST via AJAX from my own .html and .js files to localhost:8080.  Upon submitting the request, the full error reads: "Access to XMLHttpRequest at 'http://localhost:8080/contact/new-message' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

CORS is already enabled on my browser, so access is automatically "Access-Control-Allow-Origin : *", so this is a different from that error.

Is there a way to include an "ok" status in the header?  Or is the problem arising from elsewhere?  Any help is greatly appreciated.  Here are some code snippets:

My JavaScript, which runs as part of a form-submission:

```<code>function submitMessageAJAXCall(inputName, inputEmail, inputMessage, inputRegion) {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:8080/contact/new-message',
        data: JSON.stringify({
            rbName: inputName,
            rbEmail: inputEmail,
            rbMessageText: inputMessage,
            rbRegionId: inputRegion
        }),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        success: function() {

            alert('Success!');
            displayThankYouMessage();

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Unfortunately that message did not go through.');
        }
    });
}
</code>```

The Java code which recieves it:

```<code>@PostMapping("/new-message")
    private ResponseEntity<HttpStatus> addNewMessage(@RequestBody RBNewMessage rbNewMessage) {
        //validate message in service layer
        boolean isRequestValid = contactService.validateNewMessageRB(rbNewMessage);

        //is message is good, save it; else, return an error
        if (isRequestValid == true) {
            //create a new message
            ContactMessage message = new ContactMessage();

            //set message fields
            message.setMyName(rbNewMessage.getRbName());

            message.setMyEmail(rbNewMessage.getRbEmail());

            message.setMessageText(rbNewMessage.getRbMessageText());

            LocalDateTime timeOfMessage = LocalDateTime.now();
            LocalDateTime timeWithoutNano = timeOfMessage.withNano(0);
            message.setTimeStamp(timeWithoutNano);

            int regionId = rbNewMessage.getRbRegionId();
            Region region = regionService.getRegionById(regionId);
            message.setRegion(region);

            ContactStatus cs = contactStatService.getStatusById(1);
            message.setContactStatus(cs);

            //save message
            contactService.save(message);

            //return success
            return new ResponseEntity<>(HttpStatus.OK);

        } else {
            //return error
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
</code>```

And this is an example of a Postman request that is successful:

```<code>{
    "rbName": "John Johnson",
    "rbEmail" : "JohnJohnson@Email.com",
    "rbMessageText" : "Hello there, this is my message.",
    "rbRegionId" : 5
}
</code>```

答: Add @CrossOrigin annotation (import org.springframework.web.bind.annotation.CrossOrigin) to the top of the controller class that is handling the request.</p>

Body:
I am getting an error when attempting to send a POST via AJAX from my own .html and .js files to localhost:8080.  Upon submitting the request, the full error reads: "Access to XMLHttpRequest at 'http://localhost:8080/contact/new-message' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

CORS is already enabled on my browser, so access is automatically "Access-Control-Allow-Origin : *", so this is a different from that error.

Is there a way to include an "ok" status in the header?  Or is the problem arising from elsewhere?  Any help is greatly appreciated.  Here are some code snippets:

My JavaScript, which runs as part of a form-submission:

function submitMessageAJAXCall(inputName, inputEmail, inputMessage, inputRegion) {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:8080/contact/new-message',
        data: JSON.stringify({
            rbName: inputName,
            rbEmail: inputEmail,
            rbMessageText: inputMessage,
            rbRegionId: inputRegion
        }),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        success: function() {

            alert('Success!');
            displayThankYouMessage();

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Unfortunately that message did not go through.');
        }
    });
}

The Java code which recieves it:

@PostMapping("/new-message")
    private ResponseEntity<HttpStatus> addNewMessage(@RequestBody RBNewMessage rbNewMessage) {
        //validate message in service layer
        boolean isRequestValid = contactService.validateNewMessageRB(rbNewMessage);

        //is message is good, save it; else, return an error
        if (isRequestValid == true) {
            //create a new message
            ContactMessage message = new ContactMessage();

            //set message fields
            message.setMyName(rbNewMessage.getRbName());

            message.setMyEmail(rbNewMessage.getRbEmail());

            message.setMessageText(rbNewMessage.getRbMessageText());

            LocalDateTime timeOfMessage = LocalDateTime.now();
            LocalDateTime timeWithoutNano = timeOfMessage.withNano(0);
            message.setTimeStamp(timeWithoutNano);

            int regionId = rbNewMessage.getRbRegionId();
            Region region = regionService.getRegionById(regionId);
            message.setRegion(region);

            ContactStatus cs = contactStatService.getStatusById(1);
            message.setContactStatus(cs);

            //save message
            contactService.save(message);

            //return success
            return new ResponseEntity<>(HttpStatus.OK);

        } else {
            //return error
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

And this is an example of a Postman request that is successful:

{
    "rbName": "John Johnson",
    "rbEmail" : "JohnJohnson@Email.com",
    "rbMessageText" : "Hello there, this is my message.",
    "rbRegionId" : 5
}


问:
How do I make words of certain length flip?
So I'm trying to create a program that takes sentences and makes words of length 5 or longer reverse itself. At the moment it is only flipping the last word that meets the condition and I don't know why.

```<code>userInput = "Hello this is a test sentence"
wordList = userInput.split()

for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = userInput.replace(i, reversedWord)

print(reversedSentence)
</code>```

Instead of outputing "olleH this is a test ecnetnes" it outputs "Hello this is a test ecnetnes"

答:
You keep replacing the original userInput

```<code>reversedSentence = userInput
for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = reversedSentence.replace(i, reversedWord)
</code>```

You need to keep updating the reversedSentence variable instead.

Body:
So I'm trying to create a program that takes sentences and makes words of length 5 or longer reverse itself. At the moment it is only flipping the last word that meets the condition and I don't know why.

userInput = "Hello this is a test sentence"
wordList = userInput.split()

for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = userInput.replace(i, reversedWord)

print(reversedSentence)

Instead of outputing "olleH this is a test ecnetnes" it outputs "Hello this is a test ecnetnes"

Body:
You keep replacing the original userInput

reversedSentence = userInput
for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = reversedSentence.replace(i, reversedWord)

You need to keep updating the reversedSentence variable instead.


问:
Loading page fragments using $.post in jQuery
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

```<code>//data.php
<div id="alpha">alpha</div><div id="beta">beta</div>
</code>```

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

```<code>$("#container").load('data.php #alpha');
</code>```

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

```<code>$.post('data.php',null,function(data){
//what to do here?
});
</code>```

Thanks

答:
If the response is exactly as you describe and does not have a root element.

```<code>$.post("some url", {},
  function(data) {
    var $d = $("<div/>").append(data);
    $('body').append($d.find("#alpha"));
});
</code>```

Example on jsfiddle

ContentLicense: CC BY-SA 3.0

Body:
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

//data.php

alpha

beta

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

$("#container").load('data.php #alpha');

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

$.post('data.php',null,function(data){
//what to do here?
});

Thanks

Body:
If the response is exactly as you describe and does not have a root element.

$.post("some url", {},
  function(data) {
    var $d = $("<div/>").append(data);
    $('body').append($d.find("#alpha"));
});

Example on jsfiddle


问:
Make an integration test of the dbContext
I am trying to do an integration test to test if my ApplicationDbContext is working properly. It is on a MVC core asp.net 3.1 application using entity framework and Pomelo.EntityFramework.MySql.

For the moment, I have just created the MVC application with ApplicationDbContext; An entity ; and I configured the database in startup.cs. At that time, I tested to migrate and update the database and it works.

After that, I added 2 projects in my solution for the unit test and the integration test, then adding the project reference on them. I did a simple test to use ApplicationDbContext but it doesn't work and I'm having trouble solving this problem.

If anyone has an idea on how to create this kind of test using xunit.

My project code is here: https://github.com/BeRoots/aspnetcore3.1-MVC-EF-MySQL

The integration test that I tryed to do is HERE

答:
First, you will need to add the Pomelo.EntityFrameworkCore.MySql NuGet package to your weblab2 and XUnitIntegrationTestWeblab2 projects.

Then you need to reference your weblab2 project from your XUnitIntegrationTestWeblab2 project.

Your project will now compile, but your test will still fail.

Finally, you will need to setup your ApplicationDbContext instance, before using it.
I did this in form of a very simple example for the Application_DbContext_Should_Connect_To_MySql_Database test:

[Fact]
public void Application_DbContext_Should_Connect_To_MySql_Database()
{
    // Arrange
    var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>()
        .UseMySql("server=127.0.0.1;port=3306;user=root;password=;database=so59888273", builder => builder
            .ServerVersion(new Version(8, 0, 18), ServerType.MySql));

    ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);
    bool expected = true;

    // Act
    bool result = dbContext.Database.CanConnect();

    // Assert
    Assert.Equal(expected, result);
}

```

<p>Here is a patch containing all the changes:</p>

```diff --git a/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs b/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
index 2c60ea3..0b058a5 100644
--- a/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
+++ b/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
@@ -1,4 +1,6 @@
 ï»¿using System;
+using Microsoft.EntityFrameworkCore;
+using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
 using weblab2.Data;
 using Xunit;

@@ -6,18 +8,24 @@ namespace XUnitIntegrationTestWeblab2
 {
     public class UnitTest2_Pomelo_EntityFramework_Core_MySql_ApplicationDbContextTest
     {
-        [Fact]
-        public void Application_DbContext_Should_Connect_To_MySql_Database()
-        {
-            // Arrange
-            ApplicationDbContext DbContext = new ApplicationDbContext();
-            bool expected = true;
-            // Act
-            bool result = DbContext.Database.CanConnect();
+[Fact]
+public void Application_DbContext_Should_Connect_To_MySql_Database()
+{
+    // Arrange
+    var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>()
+        .UseMySql("server=127.0.0.1;port=3306;user=root;password=;database=so59888273", builder => builder
+            .ServerVersion(new Version(8, 0, 18), ServerType.MySql));

-            // Assert
-            Assert.Equal(expected, result);
-        }
+    ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);
+    bool expected = true;
+
+    // Act
+    bool result = dbContext.Database.CanConnect();
+
+    // Assert
+    Assert.Equal(expected, result);
+}
+
         [Fact]
         public async void Application_DbContext_Should_Connect_To_MySql_Database_Async()
         {
diff --git a/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj b/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
index a2352e4..665815c 100644
--- a/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
+++ b/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
@@ -8,9 +8,14 @@

   <ItemGroup>
     <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
+    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
     <PackageReference Include="xunit" Version="2.4.0" />
     <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
     <PackageReference Include="coverlet.collector" Version="1.0.1" />
   </ItemGroup>

+  <ItemGroup>
+    <ProjectReference Include="..\weblab2\weblab2.csproj" />
+  </ItemGroup>
+
 </Project>
diff --git a/weblab2/weblab2.csproj b/weblab2/weblab2.csproj
index 0fcc948..6a736ad 100644
--- a/weblab2/weblab2.csproj
+++ b/weblab2/weblab2.csproj
@@ -4,6 +4,10 @@
     <TargetFramework>netcoreapp3.1</TargetFramework>
   </PropertyGroup>

+  <ItemGroup>
+    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
+  </ItemGroup>
+

 </Project>
```

Body:
First, you will need to add the Pomelo.EntityFrameworkCore.MySql NuGet package to your weblab2 and XUnitIntegrationTestWeblab2 projects.

Then you need to reference your weblab2 project from your XUnitIntegrationTestWeblab2 project.

Your project will now compile, but your test will still fail.

Finally, you will need to setup your ApplicationDbContext instance, before using it.
I did this in form of a very simple example for the Application_DbContext_Should_Connect_To_MySql_Database test:

[Fact]
public void Application_DbContext_Should_Connect_To_MySql_Database()
{
    // Arrange
    var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>()
        .UseMySql("server=127.0.0.1;port=3306;user=root;password=;database=so59888273", builder => builder
            .ServerVersion(new Version(8, 0, 18), ServerType.MySql));

    ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);
    bool expected = true;

    // Act
    bool result = dbContext.Database.CanConnect();

    // Assert
    Assert.Equal(expected, result);
}

Here is a patch containing all the changes:

diff --git a/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs b/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
index 2c60ea3..0b058a5 100644
--- a/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
+++ b/XUnitIntegrationTestWeblab2/UnitTest2.Pomelo.EntityFramework.Core.MySql.ApplicationDbContextTest.cs
@@ -1,4 +1,6 @@
 ï»¿using System;
+using Microsoft.EntityFrameworkCore;
+using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
 using weblab2.Data;
 using Xunit;

@@ -6,18 +8,24 @@ namespace XUnitIntegrationTestWeblab2
 {
     public class UnitTest2_Pomelo_EntityFramework_Core_MySql_ApplicationDbContextTest
     {
-        [Fact]
-        public void Application_DbContext_Should_Connect_To_MySql_Database()
-        {
-            // Arrange
-            ApplicationDbContext DbContext = new ApplicationDbContext();
-            bool expected = true;
-            // Act
-            bool result = DbContext.Database.CanConnect();
+[Fact]
+public void Application_DbContext_Should_Connect_To_MySql_Database()
+{
+    // Arrange
+    var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>()
+        .UseMySql("server=127.0.0.1;port=3306;user=root;password=;database=so59888273", builder => builder
+            .ServerVersion(new Version(8, 0, 18), ServerType.MySql));

-            // Assert
-            Assert.Equal(expected, result);
-        }
+    ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);
+    bool expected = true;
+
+    // Act
+    bool result = dbContext.Database.CanConnect();
+
+    // Assert
+    Assert.Equal(expected, result);
+}
+
         [Fact]
         public async void Application_DbContext_Should_Connect_To_MySql_Database_Async()
         {
diff --git a/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj b/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
index a2352e4..665815c 100644
--- a/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
+++ b/XUnitIntegrationTestWeblab2/XUnitIntegrationTestWeblab2.csproj
@@ -8,9 +8,14 @@

   <ItemGroup>
     <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
+    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
     <PackageReference Include="xunit" Version="2.4.0" />
     <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
     <PackageReference Include="coverlet.collector" Version="1.0.1" />
   </ItemGroup>

+  <ItemGroup>
+    <ProjectReference Include="..\weblab2\weblab2.csproj" />
+  </ItemGroup>
+
 </Project>
diff --git a/weblab2/weblab2.csproj b/weblab2/weblab2.csproj
index 0fcc948..6a736ad 100644
--- a/weblab2/weblab2.csproj
+++ b/weblab2/weblab2.csproj
@@ -4,6 +4,10 @@
     <TargetFramework>netcoreapp3.1</TargetFramework>
   </PropertyGroup>

+  <ItemGroup>
+    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
+  </ItemGroup>
+

 </Project>


问:
Using Azure Data Factory to ingest incoming data from a REST API
Is there a way to create an Azure ADF Pipeline to ingest the incoming POST requests? I have this gateway app (outside Azure) that is able to publish data via REST as it arrives from the application and this data needs to be ingested into a Data Lake. I am utilizing the REST calls from another pipeline to pull the data but this basically needs to do the reverse - the data will be pushed and i need to be constantly 'listening' to those calls...

Is this something an ADF pipeline should do or maybe there are any other Azure components able to do it?

答:
Azure Data Factory is a batch data movement service.  If you want to push the data over HTTP, you can implement a simple Azure Function to accept the data and write it to the Azure Data Lake.

See Azure Functions HTTP triggers and bindings overview


问:
Preserve Colors of a PNG Image inside of a Button and List SwiftUI
The colors of the image are changed when it is nested in List and Button View.

struct ContentView: View {
    var body:some View{
        List{
            Button(action:{}){
                Image("img")
            }
        }
    }
}
```

答:
Adding a style PlainButtonStyle() to the Button preserves the colors of the PNG:

struct ContentView: View {
    var body:some View{
        List{
            Button(action:{}){
                Image("img")
            }.buttonStyle(PlainButtonStyle())
        }
    }
}
```


问:
POST request not working for Django form and Django formset
I have a form, ApplyJobForm and a Formset, ApplyJobFormset. GET method works when I pass the form and the formset to a view, but for the post request the form and the formset is_valid() isn't working, after clicking submit it returns me to a view without saving. I am unable to save the form with the formset, I don't know what I'm doing wrong here.
Here are my codes.

models.py

```<code>class Applicants(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants')
    experience = models.IntegerField(blank=True, null=True)
    cv = models.FileField(upload_to=user_directory_path)
    degree = models.CharField(choices=DEGREE_TYPE, blank=True, max_length=10)
    created_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.user.get_full_name()} Applied'

class Certification(models.Model):
    applicant = models.ForeignKey(Applicants, on_delete=models.CASCADE, related_name='applicant_certifications')
    name = models.CharField(max_length=50)
    certification = models.FileField(upload_to=user_directory_path, blank=True)

    def __str__(self):
        return f'{self.user.get_full_name()} certificate'
</code>```

forms.py

```<code>class ApplyJobForm(forms.ModelForm):

    class Meta:
        model = Applicants
        fields = ('job', 'degree', 'experience', 'cv')
        exclude = ('job',)
        labels = {
            'degree': 'Degree',
            'experience': 'Experience',
            'cv': 'CV',
        }
        widgets = {
            'degree': forms.Select(attrs={
                'class': 'form-control',
            }
            ),
            'experience': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                }
            ),
            'cv': forms.FileInput(
                attrs={
                    'class': 'form-control',
                }
            ),
        }

ApplyFormset = modelformset_factory(
    Certification,
    fields=('name', 'certification'),
    extra=1,
    widgets={
        'name': forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Certification name'
            }
        ),
        'certification': forms.FileInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Upload certification'
            }
        )
    }
)
</code>```

views.py

```<code>def job_apply(request, job_id=None):
    template_name = 'apply_form.html'
    applyform = ApplyJobForm(request.GET or None)
    job = get_object_or_404(Job, id=job_id)
    formset = ApplyFormset(queryset=Certification.objects.none())
    if request.method == 'GET':
        context = {'applyform': applyform, 'formset': formset}
        return render(request, template_name, context)
    elif request.method == 'POST':
        applyform = ApplyJobForm(request.POST)
        formset = ApplyFormset(request.POST)
        if applyform.is_valid() and formset.is_valid():
            apply = applyform.save(commit=False)
            applyform.job = job
            apply.save()
            for form in formset:
                # so that `apply` instance can be attached.
                certification = form.save(commit=False)
                certification.apply = apply
                certification.save()
            return redirect('successful-apply')
        else:
            return redirect('job-detail', id=job.id)

    return render(request, template_name, {'applyform': applyform, 'formset': formset})
</code>```

Here an applicant can add as many certification field when applying for a job, although the certification field is not a required field. Certification model is bound to the Applicants model.

.html

```<code><form class="form" method="POST" action="" enctype="multipart/form-data" role="form" autocomplete="off">
.................
</form>
</code>```

答:
First of all, never redirect if your forms are not valid. You want to render your template with the invalid form so that you can display the errors to the user. This also helps debugging since you'll see the errors.

So in your view, remove these two lines:

```<code>        else:
            return redirect('job-detail', id=job.id)
</code>```

so that the invalid case renders the forms in your template.

Next, since you have files to upload, you need to initialise forms that require files with request.FILES:

```<code>formset = ApplyFormset(request.POST, request.FILES)
</code>```

(and the same for applyform).

Finally make sure that in your template you are also displaying all the errors, either on each field ({{ form.<field>.errors }}) or globally ({{ form.errors }}).

Body:
I have a form, ApplyJobForm and a Formset, ApplyJobFormset. GET method works when I pass the form and the formset to a view, but for the post request the form and the formset is_valid() isn't working, after clicking submit it returns me to a view without saving. I am unable to save the form with the formset, I don't know what I'm doing wrong here.
Here are my codes.

models.py

class Applicants(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants')
    experience = models.IntegerField(blank=True, null=True)
    cv = models.FileField(upload_to=user_directory_path)
    degree = models.CharField(choices=DEGREE_TYPE, blank=True, max_length=10)
    created_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.user.get_full_name()} Applied'

class Certification(models.Model):
    applicant = models.ForeignKey(Applicants, on_delete=models.CASCADE, related_name='applicant_certifications')
    name = models.CharField(max_length=50)
    certification = models.FileField(upload_to=user_directory_path, blank=True)

    def __str__(self):
        return f'{self.user.get_full_name()} certificate'

forms.py

class ApplyJobForm(forms.ModelForm):

    class Meta:
        model = Applicants
        fields = ('job', 'degree', 'experience', 'cv')
        exclude = ('job',)
        labels = {
            'degree': 'Degree',
            'experience': 'Experience',
            'cv': 'CV',
        }
        widgets = {
            'degree': forms.Select(attrs={
                'class': 'form-control',
            }
            ),
            'experience': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                }
            ),
            'cv': forms.FileInput(
                attrs={
                    'class': 'form-control',
                }
            ),
        }

ApplyFormset = modelformset_factory(
    Certification,
    fields=('name', 'certification'),
    extra=1,
    widgets={
        'name': forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Certification name'
            }
        ),
        'certification': forms.FileInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Upload certification'
            }
        )
    }
)

views.py

def job_apply(request, job_id=None):
    template_name = 'apply_form.html'
    applyform = ApplyJobForm(request.GET or None)
    job = get_object_or_404(Job, id=job_id)
    formset = ApplyFormset(queryset=Certification.objects.none())
    if request.method == 'GET':
        context = {'applyform': applyform, 'formset': formset}
        return render(request, template_name, context)
    elif request.method == 'POST':
        applyform = ApplyJobForm(request.POST)
        formset = ApplyFormset(request.POST)
        if applyform.is_valid() and formset.is_valid():
            apply = applyform.save(commit=False)
            applyform.job = job
            apply.save()
            for form in formset:
                # so that `apply` instance can be attached.
                certification = form.save(commit=False)
                certification.apply = apply
                certification.save()
            return redirect('successful-apply')
        else:
            return redirect('job-detail', id=job.id)

    return render(request, template_name, {'applyform': applyform, 'formset': formset})

Here an applicant can add as many certification field when applying for a job, although the certification field is not a required field. Certification model is bound to the Applicants model.

.html

<form class="form" method="POST" action="" enctype="multipart/form-data" role="form" autocomplete="off">
.................
</form>

Body:
First of all, never redirect if your forms are not valid. You want to render your template with the invalid form so that you can display the errors to the user. This also helps debugging since you'll see the errors.

So in your view, remove these two lines:

        else:
            return redirect('job-detail', id=job.id)

so that the invalid case renders the forms in your template.

Next, since you have files to upload, you need to initialise forms that require files with request.FILES:

formset = ApplyFormset(request.POST, request.FILES)

(and the same for applyform).

Finally make sure that in your template you are also displaying all the errors, either on each field ({{ form.<field>.errors }}) or globally ({{ form.errors }}).


问:
C# Converting mixed JSON into an object
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

```<code>struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}
</code>```

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

答:
Assuming that you do not want to use a static model,the problem with the code is that it doesn't match signature of your Json. The Json comprises of a Dictionary<string,Dictionary<string,List<string>>. However, there is another concern.

Some of the values in inner Dictionary is not List<string>. Instead, they are strings. For example,

```<code>'Short name':'test_s_name'
</code>```

For this purpose you need to use a a Custom JsonConverter which if the values is not a array, converts the single string value to list. For example, consider the following Custom JsonConverter.

```<code>class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
</code>```

Now, you could deserialize your Json as

```<code>string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }";

var deserialized_entry = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string, List<string>>>>(test_string,new SingleOrArrayConverter<string>());
</code>```

Output

Title: C# Converting mixed JSON into an object

Body:
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

Body:
Assuming that you do not want to use a static model,the problem with the code is that it doesn't match signature of your Json. The Json comprises of a Dictionary<string,Dictionary<string,List<string>>. However, there is another concern.

Some of the values in inner Dictionary is not List<string>. Instead, they are strings. For example,

'Short name':'test_s_name'

For this purpose you need to use a a Custom JsonConverter which if the values is not a array, converts the single string value to list. For example, consider the following Custom JsonConverter.

class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

Now, you could deserialize your Json as

string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }";

var deserialized_entry = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string, List<string>>>>(test_string,new SingleOrArrayConverter<string>());

Output


Title: Get nearest time previous to current time which is divisible by 5

Body:
I have a dataframe with a column which have time data in the format HH:MM:SS. Sample data is shown below for reference:

Time
09:25:03
09:28:40
09:36:12
09:36:14
09:41:10
09:51:00
09:58:48
10:00:11
10:00:17
10:21:44
10:21:53
10:32:58
11:08:59
11:45:55
11:49:14
12:18:54
12:21:22
13:05:47
13:19:37
13:19:57
13:25:22
14:21:10

I want to get the nearest time previous to current time which is divisible by 5. I want the output like below:

Time        Nearest_Time
09:25:03    09:25:00
09:28:40    09:25:00
09:36:12    09:35:00
09:36:14    09:35:00
09:41:10    09:40:00
09:51:00    09:50:00
09:58:48    09:50:00
10:00:11    10:00:00
10:00:17    10:00:00
10:21:44    10:20:00
10:21:53    10:20:00
10:32:58    10:30:00
11:08:59    11:05:00
11:45:55    11:45:00
11:49:14    11:45:00
12:18:54    12:15:00
12:21:22    12:20:00
13:05:47    13:05:00
13:19:37    13:15:00
13:19:57    13:15:00
13:25:22    13:25:00
14:21:10    14:20:00

Body:
You can use dt.floor setting freq to 5 minutes:

pd.to_datetime(df.Time).dt.floor('5 min')

0    2020-02-14 09:25:00
1    2020-02-14 09:25:00
2    2020-02-14 09:35:00
3    2020-02-14 09:35:00
4    2020-02-14 09:40:00
5    2020-02-14 09:50:00
6    2020-02-14 09:55:00
7    2020-02-14 10:00:00
8    2020-02-14 10:00:00
9    2020-02-14 10:20:00
10   2020-02-14 10:20:00
11   2020-02-14 10:30:00
12   2020-02-14 11:05:00
13   2020-02-14 11:45:00
14   2020-02-14 11:45:00
15   2020-02-14 12:15:00
16   2020-02-14 12:20:00
17   2020-02-14 13:05:00
18   2020-02-14 13:15:00
19   2020-02-14 13:15:00
20   2020-02-14 13:25:00
21   2020-02-14 14:20:00
Name: Time, dtype: datetime64[ns]


问:
How is memory deallocated in c++
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

```<code>int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD
</code>```

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.

答:
How does C++ know I deallocated that memory.

When you use a delete expression, "C++ knows" that you deallocated that memory.

If it just turns it to arbitrary garbage binary numbers

C++ doesn't "turn [deallocated memory] to arbitrary garbage binary numbers". C++ merely makes the memory available for other allocations. Changing the state of that memory may be a side effect of some other part of the program using that memory - which it is now free to do.

wouldn't I just be reading in that garbage number when I dereference the pointer?

When you indirect through the pointer, the behaviour of the program is undefined.

Instead, of course, c++ knows that these are segfaults somehow.

This is where your operating system helpfully stepped in. You did something that did not make sense, and the operating system killed the misbehaving process. This is one of the many things that may but might not happen when the behaviour of the program is undefined.

Title: How is memory deallocated in c++

Body:
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.


问:
Fix for 'Gem::Requirement::BadRequirementError: Illformed requirement [">=1 <2"]' error
How do I fix this error when deploying a rails 6 application to heroku?
(It has spree gem installed)</p>

```<code>      rake aborted!
       Gem::Requirement::BadRequirementError: Illformed requirement [">=1 <2"]
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/check_yarn.rake:11:in `new'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/check_yarn.rake:11:in `block (2 levels) in <top (required)>'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/compile.rake:14:in `block in enhance_assets_precompile'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/gems/rake-13.0.1/exe/rake:27:in `<top (required)>'
       Tasks: TOP => webpacker:compile => webpacker:verify_install => webpacker:check_yarn
       (See full trace by running task with --trace)
 !
 !     Precompiling assets failed.
 !
 !     Push rejected, failed to compile Ruby app.
 !     Push failed
</code>```

答:
What caused it:

Adding

```<code>gem 'spree', '~> 4.0'
gem 'spree_auth_devise', '~> 4.0'
gem 'spree_gateway', '~> 3.6'
</code>```

How I worked my way around it:

```<code>mv Gemfile.lock /tmp/
bundle install
mv yarn.lock /tmp/
yarn install --check-files
</code>```

Btw I'm on

```<code>Rails 6.0.2.1
ruby 2.7.0p0
Bundler version 2.1.2
yarn 1.17.3
</code>```

Hope this helps someone.

Body:
How do I fix this error when deploying a rails 6 application to heroku?
(It has spree gem installed)

      rake aborted!
       Gem::Requirement::BadRequirementError: Illformed requirement [">=1 <2"]
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/check_yarn.rake:11:in `new'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/check_yarn.rake:11:in `block (2 levels) in <top (required)>'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/bundler/gems/webpacker-07a62a9dfed3/lib/tasks/webpacker/compile.rake:14:in `block in enhance_assets_precompile'
       /tmp/build_d17738d2f38bed1a2488535e1dbef5b9/vendor/bundle/ruby/2.7.0/gems/rake-13.0.1/exe/rake:27:in `<top (required)>'
       Tasks: TOP => webpacker:compile => webpacker:verify_install => webpacker:check_yarn
       (See full trace by running task with --trace)
 !
 !     Precompiling assets failed.
 !
 !     Push rejected, failed to compile Ruby app.
 !     Push failed

Body:
What caused it:

Adding

gem 'spree', '~> 4.0'
gem 'spree_auth_devise', '~> 4.0'
gem 'spree_gateway', '~> 3.6'

How I worked my way around it:

mv Gemfile.lock /tmp/
bundle install
mv yarn.lock /tmp/
yarn install --check-files

Btw I'm on

Rails 6.0.2.1
ruby 2.7.0p0
Bundler version 2.1.2
yarn 1.17.3

Hope this helps someone.


Body:
You could change Time to timedelta and do normal arithmetic operations:

df['Time'] = pd.to_timedelta(df['Time'])

period = pd.to_timedelta('5M')
df['nearest_past'] = df['Time'] // period * period

# floor also works
# df['nearest_past'] = df['Time'].dt.floor(period)

Output:

       Time nearest_past
0  09:25:03     09:25:00
1  09:28:40     09:25:00
2  09:36:12     09:35:00
3  09:36:14     09:35:00
4  09:41:10     09:40:00
5  09:51:00     09:50:00
6  09:58:48     09:55:00
7  10:00:11     10:00:00
8  10:00:17     10:00:00
9  10:21:44     10:20:00
10 10:21:53     10:20:00
11 10:32:58     10:30:00
12 11:08:59     11:05:00
13 11:45:55     11:45:00
14 11:49:14     11:45:00
15 12:18:54     12:15:00
16 12:21:22     12:20:00
17 13:05:47     13:05:00
18 13:19:37     13:15:00
19 13:19:57     13:15:00
20 13:25:22     13:25:00
21 14:21:10     14:20:00


问:
Using octave headless
Is there a possibility to use Octave headless.

Something like this

octave < "5+4" >result.txt

答:
Using

```<code>octave --silent --eval 5+4 > result.txt
</code>```

you'll get

```<code>ans =  9
</code>```

in result.txt. See octave --help for details about command-line arguments.

Yet, there is this infamous ans = that might be remove using sed, e.g.

```<code>octave --silent --eval 'x=5+4; y=x+1; disp(y)' | sed -e 's/ans = //' >> result.txt
</code>```

which add the appropriate result (10) in result.txt.

It should not be too hard to wrap this into a bash script.

Title: Using octave headless

Body:
Using

octave --silent --eval 5+4 > result.txt

you'll get

ans =  9

in result.txt. See octave --help for details about command-line arguments.

Yet, there is this infamous ans = that might be remove using sed, e.g.

octave --silent --eval 'x=5+4; y=x+1; disp(y)' | sed -e 's/ans = //' >> result.txt

which add the appropriate result (10) in result.txt.

It should not be too hard to wrap this into a bash script.


问:
React npm "module build failed (from ./node_modules/babel-loader/lib/index.js)"
I am trying to setup React environment and I am getting two errors when running npm start in command prompt.

First error is "module build failed (from ./node_modules/babel-loader/lib/index.js)" and second is
"error plugin/preset files are not allowed to export objects only functions".

Any idea how this could be solved? I am new to this whole thing so please try to keep answer simple and steps easy to follow.

答:
change your directory and install your app again via this code :

```<code>npx create-react-app yourAppName
</code>```

then install all dependencies

Body:
change your directory and install your app again via this code :

npx create-react-app yourAppName

then install all dependencies


问:
Why TCP handshake is not happening while using sockets in c#?
I tried implementing socket server and clients using c#, I noticed that TCP hand shake has not happened and the data flows from the very first send/receive. is this usual socket behavior? or the methods Send and Receive hide the handshake implementation?

Note: opened a socket using below code.

IPEndPoint endPoint = new IPEndPoint(ipAddress, portNumber);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);

答:
You have binded the socket to a address but haven't actually started listening for connections yet. You need to call Listen() to actually listen for connections.

According to the documentation:

"If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method."

Use the following code:

```<code>IPEndPoint endPoint = new IPEndPoint(ipAddress, portNumber);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
listener.Listen(1);
</code>```

Body:
You have binded the socket to a address but haven't actually started listening for connections yet. You need to call Listen() to actually listen for connections.

According to the documentation:

"If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method."

Use the following code:

IPEndPoint endPoint = new IPEndPoint(ipAddress, portNumber);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
listener.Listen(1);


问:
API does not list newly created folders
I am using the Google Drive API V3. I was trying to list files and folders from a pre-existing folder. Earlier this folder consisted only files. The listing returned all the files. Then when I created 2 new folders. I am unable to find these two folders.

Shown below is my C# method:

```<code>        public void FindFiles(FindFilesParam p)
        {
            // Define parameters of request.
            FilesResource.ListRequest listRequest = _service.Files.List();
            listRequest.PageSize = p.PageSize;
            //listRequest.Fields = "nextPageToken, files(id, name)";
            //listRequest.Fields = "nextPageToken, files(*)";
            //listRequest.Fields = "nextPageToken, files(id, name, md5Checksum, createdTime, modifiedTime, size)";
            listRequest.Fields = "nextPageToken, files(*)";
            if ( !string.IsNullOrEmpty(p.FolderId))
                listRequest.Q = $@"('{p.FolderId}' in parents)";
            Google.Apis.Drive.v3.Data.FileList fileList = listRequest.Execute();
            while (!string.IsNullOrWhiteSpace(fileList.NextPageToken))
            {
                listRequest.PageToken = fileList.NextPageToken;
                fileList = listRequest.Execute();
                if (FindFilesReturnedPage != null)
                {
                    var e = new FindFilesReturnedPageEventArgs(
                        fileList.Files, p.RelativePath);
                    FindFilesReturnedPage(this, e);
                    if (e.Cancel)
                        break;
                }
            }

            if (FindFilesFinished != null)
                FindFilesFinished(this, EventArgs.Empty);
        }

    public class FindFilesParam
    {
        public FindFilesParam()
        {
            PageSize = 10;
        }

        public string FolderId { set; get; }
        public string RelativePath { set; get; }
        public int? PageSize { set; get; }
    }

// Calling this as follows:

FindFiles(new FindFilesParam()
{
    FolderId = "1hYcRWXaQcg1Noh06rPCouIgIl5TZ8BWP",
    RelativePath = string.Empty
});
</code>```

答:
You are not using the first page of files list, the code at the beginning of the while it's overriding the first files list page which is made outside the while.

Use this piece of code instead to ensure you'll use both the first and last files list pages:

```<code> Google.Apis.Drive.v3.Data.FileList fileList = listRequest.Execute();
 while (true) {
     .......
     //Print or use files list
     ........

     //Break loop if there's no NextPageToken
     if(!string.IsNullOrWhiteSpace(fileList.NextPageToken)) break;

     listRequest.PageToken = fileList.NextPageToken;
     fileList = listRequest.Execute();
}
</code>```

Title: API does not list newly created folders

Body:
I am using the Google Drive API V3. I was trying to list files and folders from a pre-existing folder. Earlier this folder consisted only files. The listing returned all the files. Then when I created 2 new folders. I am unable to find these two folders.

Shown below is my C# method:

        public void FindFiles(FindFilesParam p)
        {
            // Define parameters of request.
            FilesResource.ListRequest listRequest = _service.Files.List();
            listRequest.PageSize = p.PageSize;
            //listRequest.Fields = "nextPageToken, files(id, name)";
            //listRequest.Fields = "nextPageToken, files(*)";
            //listRequest.Fields = "nextPageToken, files(id, name, md5Checksum, createdTime, modifiedTime, size)";
            listRequest.Fields = "nextPageToken, files(*)";
            if ( !string.IsNullOrEmpty(p.FolderId))
                listRequest.Q = $@"('{p.FolderId}' in parents)";
            Google.Apis.Drive.v3.Data.FileList fileList = listRequest.Execute();
            while (!string.IsNullOrWhiteSpace(fileList.NextPageToken))
            {
                listRequest.PageToken = fileList.NextPageToken;
                fileList = listRequest.Execute();
                if (FindFilesReturnedPage != null)
                {
                    var e = new FindFilesReturnedPageEventArgs(
                        fileList.Files, p.RelativePath);
                    FindFilesReturnedPage(this, e);
                    if (e.Cancel)
                        break;
                }
            }

            if (FindFilesFinished != null)
                FindFilesFinished(this, EventArgs.Empty);
        }

    public class FindFilesParam
    {
        public FindFilesParam()
        {
            PageSize = 10;
        }

        public string FolderId { set; get; }
        public string RelativePath { set; get; }
        public int? PageSize { set; get; }
    }

// Calling this as follows:

FindFiles(new FindFilesParam()
{
    FolderId = "1hYcRWXaQcg1Noh06rPCouIgIl5TZ8BWP",
    RelativePath = string.Empty
});

Body:
You are not using the first page of files list, the code at the beginning of the while it's overriding the first files list page which is made outside the while.

Use this piece of code instead to ensure you'll use both the first and last files list pages:

 Google.Apis.Drive.v3.Data.FileList fileList = listRequest.Execute();
 while (true) {
     .......
     //Print or use files list
     ........

     //Break loop if there's no NextPageToken
     if(!string.IsNullOrWhiteSpace(fileList.NextPageToken)) break;

     listRequest.PageToken = fileList.NextPageToken;
     fileList = listRequest.Execute();
}


问:
Are there drawbacks in using classes to construct redux store?
One of our developers suggested it is preferable to not use classes to construct redux store, but didn't give a concrete reason, mostly saying "it is not idiomatic and classes are not that well-implemented in ES6; it is preferable to avoid using classes in React".

Are there any issues (even if it's actually not an industry-standard?) to construct a redux store in this manner?

```<code>class Item {
  public name: string;
}

class ItemState {
  public items: Item[];
  public currentItem: Item;
}

// redux store
class AppState {
  public Items = new ItemState();
}

// then createStore(/*reducer*/, new AppState())
</code>```

答:
In my limited experience... I have not used classes in this way, but I have used complex Objects as part of my redux store. By complex objects I mean some of my state variables are objects with different properties and arrays of other objects in them. They work, so I see no reason why classes would not. But I would advise to avoid it if at all possible, as it may make accessing state more confusing as the app grows. Note that when you connect a Component that needs to acces the currentItem's name you will have to write:

```<code>function mapStateToProps(state)
{
   return {currentItemName: state.Items.currentItem.name};
}
</code>```

That seems too long to me.
Even if you pass state.Items directly to your component, at some point you will need to access the currentItem's name and need to write the fully qualified name. I think the choice mostly depends on the particular aspects of the app. But as I said, my experience is limited, and I have made my redux stores using classes yet.

Body:
One of our developers suggested it is preferable to not use classes to construct redux store, but didn't give a concrete reason, mostly saying "it is not idiomatic and classes are not that well-implemented in ES6; it is preferable to avoid using classes in React".

Are there any issues (even if it's actually not an industry-standard?) to construct a redux store in this manner?

class Item {
  public name: string;
}

class ItemState {
  public items: Item[];
  public currentItem: Item;
}

// redux store
class AppState {
  public Items = new ItemState();
}

// then createStore(/*reducer*/, new AppState())

Body:
In my limited experience... I have not used classes in this way, but I have used complex Objects as part of my redux store. By complex objects I mean some of my state variables are objects with different properties and arrays of other objects in them. They work, so I see no reason why classes would not. But I would advise to avoid it if at all possible, as it may make accessing state more confusing as the app grows. Note that when you connect a Component that needs to acces the currentItem's name you will have to write:

function mapStateToProps(state)
{
   return {currentItemName: state.Items.currentItem.name};
}

That seems too long to me.
Even if you pass state.Items directly to your component, at some point you will need to access the currentItem's name and need to write the fully qualified name. I think the choice mostly depends on the particular aspects of the app. But as I said, my experience is limited, and I have made my redux stores using classes yet.


问:
Trouble with OQL 'unique' function of 'jhat' in Java 1.6.0_24
this is my first posted question. I have a fairly complicated OQL query which lists static fields of classes loaded in our packages. One problem I'm seeing with running the query against 'jhat' of Java 1.6.0_24 is that the 'unique' function doesn't work as expected. I expect

```<code>select unique(['a', 'b', 'c', 'a'])
</code>```

to return ['a', 'b', 'c'] but instead it returns ['a'], wtf?

If anyone's interested the actual full query is (replace 'com.mydomain' with what you like):

```<code>select cl.name + ' -- ' + unique(map(filter(referees(cl), "classof(it).name != 'java.lang.Class' && classof(it).name != 'java.lang.String' && classof(it).name != 'sun.misc.Launcher$AppClassLoader' && classof(it).name != 'java.security.ProtectionDomain' && classof(it).name != '[Ljava.security.cert.Certificate;' && classof(it).name != 'sun.plugin2.applet.JNLP2ClassLoader'"), "classof(it).name")).join(', ')
from instanceof java.lang.Class cl
where /com.mydomain./(cl.name) && ! /com.mydomain.xs.protobuf./(cl.name)
&& length(filter(referees(cl), "classof(it).name != 'java.lang.Class' && classof(it).name != 'java.lang.String' && classof(it).name != 'sun.misc.Launcher$AppClassLoader' && classof(it).name != 'java.security.ProtectionDomain'")) > 0;
</code>```

答:
By default, unique uniquifies on the object's objectid, which is suitable for actual traced objects, but for strings it returns null. Thus, only the last string is kept (since all the strings have non-unique objectid values).

You have two options:

Uniquify on the traced objects, rather than their names:

```<code>map(unique(filter(map(referees(cl), classof), "it.name != ...")), "it.name")
</code>```

Specify the "function" to uniquify with, so that it works for strings:

```<code>unique(['a', 'b', 'c', 'a'], 'it')
</code>```

This will cause the strings themselves to be uniquified.

Body:
this is my first posted question. I have a fairly complicated OQL query which lists static fields of classes loaded in our packages. One problem I'm seeing with running the query against 'jhat' of Java 1.6.0_24 is that the 'unique' function doesn't work as expected. I expect

select unique(['a', 'b', 'c', 'a'])

to return ['a', 'b', 'c'] but instead it returns ['a'], wtf?

If anyone's interested the actual full query is (replace 'com.mydomain' with what you like):

select cl.name + ' -- ' + unique(map(filter(referees(cl), "classof(it).name != 'java.lang.Class' && classof(it).name != 'java.lang.String' && classof(it).name != 'sun.misc.Launcher$AppClassLoader' && classof(it).name != 'java.security.ProtectionDomain' && classof(it).name != '[Ljava.security.cert.Certificate;' && classof(it).name != 'sun.plugin2.applet.JNLP2ClassLoader'"), "classof(it).name")).join(', ')
from instanceof java.lang.Class cl
where /com.mydomain./(cl.name) && ! /com.mydomain.xs.protobuf./(cl.name)
&& length(filter(referees(cl), "classof(it).name != 'java.lang.Class' && classof(it).name != 'java.lang.String' && classof(it).name != 'sun.misc.Launcher$AppClassLoader' && classof(it).name != 'java.security.ProtectionDomain'")) > 0;

Body:
By default, unique uniquifies on the object's objectid, which is suitable for actual traced objects, but for strings it returns null. Thus, only the last string is kept (since all the strings have non-unique objectid values).

You have two options:

Uniquify on the traced objects, rather than their names:

map(unique(filter(map(referees(cl), classof), "it.name != ...")), "it.name")

Specify the "function" to uniquify with, so that it works for strings:

unique(['a', 'b', 'c', 'a'], 'it')

This will cause the strings themselves to be uniquified.


问:
How to designate a printer using VBA?
I’ve automated much of what I need using xlwings.

The final stage of my Python is printing a label.

Sub Print_Label()

    Print_Label Macro

    Prints Loan Label

    Range("C2:C8").Select

    Application.Dialogs(xlDialogPrinterSetup).Show

    Selection.PrintOut Copies:=Range("A10"), Collate:=True

End Sub
```

<p>The label is created using VBA and Python then triggers the print using the xlwings code.</p>

```import xlwings as xw

wb = xw.Book(file.xlsm')

your_macro = wb.macro('Print_Label')

your_macro()
```

This prompts a pop up in Excel requesting which printer to use with an OK button. I need it to be a particular printer and run automatically in the background.

答:
Did it in the end - VBA -</p>

```<code>Worksheets("Print").Activate
Worksheets("Print").Range("C2:C8").Select

Application.ActivePrinter = "ZDesigner ZM400 200 dpi (ZPL) on LAN_"
Selection.PrintOut Copies:=Worksheets("Print").Range("A10"), Collate:=True
</code>```

Title: How to designate a printer using VBA?

Body:
I’ve automated much of what I need using xlwings.

The final stage of my Python is printing a label.

Sub Print_Label()

    Print_Label Macro

    Prints Loan Label

    Range("C2:C8").Select

    Application.Dialogs(xlDialogPrinterSetup).Show

    Selection.PrintOut Copies:=Range("A10"), Collate:=True

End Sub

The label is created using VBA and Python then triggers the print using the xlwings code.

import xlwings as xw

wb = xw.Book(file.xlsm')

your_macro = wb.macro('Print_Label')

your_macro()

This prompts a pop up in Excel requesting which printer to use with an OK button. I need it to be a particular printer and run automatically in the background.

Body:
Did it in the end - VBA -

Worksheets("Print").Activate
Worksheets("Print").Range("C2:C8").Select

Application.ActivePrinter = "ZDesigner ZM400 200 dpi (ZPL) on LAN_"
Selection.PrintOut Copies:=Worksheets("Print").Range("A10"), Collate:=True


问:
Angle between vectors - Python
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

```<code>def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result
</code>```

Help me pls! :(

答: From my understanding the arccos function only returns values between 0 and Pi, so you won't find any negative numbers there.</p>

Title: Angle between vectors - Python

Body:
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result

Help me pls! :(


问:
tensorflow 2.0, model.fit() : Your input ran out of data
I am absolutely new to TensorFlow and Keras, and I am trying to make my way around trying out some code that I am finding online.

In particular I am using the fashion-MNIST - consisting of 60000 examples and  test set of 10000 examples. Each of them is a 28x28 grayscale image.

I am following this tutorial "https://towardsdatascience.com/building-your-first-neural-network-in-tensorflow-2-tensorflow-for-hackers-part-i-e1e2f1dfe7a0", and I have no problem until the definition of

```<code>history = model.fit(
train_dataset.repeat(),
epochs=10,
steps_per_epoch=500,
validation_data=val_dataset.repeat(),
validation_steps=2)
</code>```

As long as I understood, I need to use train_dataset.repeat() as input dataset because otherwise I won't have enough training example using those values for the hyperparameters (epochs, steps_per_epochs).

My question is: how can I avoid to have to use .repeat()?
How do I need to change the hyperparameters?

I am coping the code here, for simplicity:

```<code>def preprocess(x,y):

    x = tf.cast(x,tf.float32) / 255.0
    y = tf.cast(y, tf.float32)

    return x,y

def create_dataset(xs, ys, n_classes=10):

    ys = tf.one_hot(ys, depth=n_classes)

    return tf.data.Dataset.from_tensor_slices((xs, ys)).map(preprocess).shuffle(len(ys)).batch(128)

model.compile(optimizer = 'adam', loss =tf.losses.CategoricalCrossentropy(from_logits= True), metrics =['accuracy'])

history1 = model.fit(train_dataset.repeat(),
                    epochs=10,
                    steps_per_epoch=500,
                    validation_data=val_dataset.repeat(),
                    validation_steps=2)
</code>```

Thanks!

答:
If you don't want to use .repeat() you need to have your model passing thought your entire data only one time per epoch.

In order to do that you need to calculate how many steps it will take for your model to pass throught the entire dataset, the calcul is easy :

```<code>steps_per_epoch = len(train_dataset) // batch_size
</code>```

So with a train_dataset of 60 000 sample and a batch_size of 128, you need to have 468 steps per epoch.

By setting this parameter like that you make sure that you do not exceed the size of your dataset.

Body:
I am absolutely new to TensorFlow and Keras, and I am trying to make my way around trying out some code that I am finding online.

In particular I am using the fashion-MNIST - consisting of 60000 examples and  test set of 10000 examples. Each of them is a 28x28 grayscale image.

I am following this tutorial "https://towardsdatascience.com/building-your-first-neural-network-in-tensorflow-2-tensorflow-for-hackers-part-i-e1e2f1dfe7a0", and I have no problem until the definition of

history = model.fit(
train_dataset.repeat(),
epochs=10,
steps_per_epoch=500,
validation_data=val_dataset.repeat(),
validation_steps=2)

As long as I understood, I need to use train_dataset.repeat() as input dataset because otherwise I won't have enough training example using those values for the hyperparameters (epochs, steps_per_epochs).

My question is: how can I avoid to have to use .repeat()?
How do I need to change the hyperparameters?

I am coping the code here, for simplicity:

def preprocess(x,y):

    x = tf.cast(x,tf.float32) / 255.0
    y = tf.cast(y, tf.float32)

    return x,y

def create_dataset(xs, ys, n_classes=10):

    ys = tf.one_hot(ys, depth=n_classes)

    return tf.data.Dataset.from_tensor_slices((xs, ys)).map(preprocess).shuffle(len(ys)).batch(128)

model.compile(optimizer = 'adam', loss =tf.losses.CategoricalCrossentropy(from_logits= True), metrics =['accuracy'])

history1 = model.fit(train_dataset.repeat(),
                    epochs=10,
                    steps_per_epoch=500,
                    validation_data=val_dataset.repeat(),
                    validation_steps=2)

Thanks!

Body:
If you don't want to use .repeat() you need to have your model passing thought your entire data only one time per epoch.

In order to do that you need to calculate how many steps it will take for your model to pass throught the entire dataset, the calcul is easy :

steps_per_epoch = len(train_dataset) // batch_size

So with a train_dataset of 60 000 sample and a batch_size of 128, you need to have 468 steps per epoch.

By setting this parameter like that you make sure that you do not exceed the size of your dataset.


问:
Setting IIS to execute EXE instead of downloading
I'm using EXE files for the back end of an in-house website.
I have server 2019 and IIS 10.
When I call the EXE file IIS tries to download the file instead of executing it.

I'm calling like this:

```<code>             $.ajax({
                    url: "cgi-bin/compPack.exe",
                    dataType: "json",
                    type: "post",
                    data: dataString,
                    error: ajaxError,
                    success: function(json){
</code>```

Which gives an error because it's expecting a JSON string, and if I enter

```<code>sandbox/cgi-bin/myProgram.exe
</code>```

in the browser it just downloads the EXE.

I've added the CGI module, set permissions on the CGI-BIN folder, tried adding and and removing .exe from Mime types as application/octet-stream but can't get it to run the binary file.

I'm not sure what I need to do to make it execute (any) EXE file in the cgi-bin folder.

答:
The fix was to apply the settings as demonstrated here by IBM.
Their Watson Explorer Engine also uses EXE's for it's CGI back end.

```<code>IIS 7.0 and higher on Windows 2008 and later systems:
Open IIS Manager:
For Windows 2008 systems: Select Control Panel > Administrative Tools > Internet Information Services (IIS) Manager.
For Windows 2012 systems: From the desktop, hover your cursor in the upper- or lower- right corner of the screen to show the charms. Click the Start charm, and then click the Internet Information Services (IIS) Manager tile.
In the Connections pane, expand the entry for your computer system, expand Sites, and select the default site, which is the site in which the Watson Explorer Engine virtual directory (vivisimo) is created.
Double-click the Handler Mappings feature.
If the state of CGI-exe is Enabled, no additional configuration is necessary. Proceed to Completing the Installation Process (All Platforms).
If the state of CGI-exe is Disabled, select it and click Edit Feature Permissions from the Actions pane. The Edit Feature Permissions window displays.
Select Execute and click OK to enable applications with the .exe extension to execute in response to CGI requests. If Execute is disabled, select Script > Execute, and then click OK.
</code>```

Body:
I'm using EXE files for the back end of an in-house website.
I have server 2019 and IIS 10.
When I call the EXE file IIS tries to download the file instead of executing it.

I'm calling like this:

             $.ajax({
                    url: "cgi-bin/compPack.exe",
                    dataType: "json",
                    type: "post",
                    data: dataString,
                    error: ajaxError,
                    success: function(json){

Which gives an error because it's expecting a JSON string, and if I enter

sandbox/cgi-bin/myProgram.exe

in the browser it just downloads the EXE.

I've added the CGI module, set permissions on the CGI-BIN folder, tried adding and and removing .exe from Mime types as application/octet-stream but can't get it to run the binary file.

I'm not sure what I need to do to make it execute (any) EXE file in the cgi-bin folder.

Body:
The fix was to apply the settings as demonstrated here by IBM.
Their Watson Explorer Engine also uses EXE's for it's CGI back end.

IIS 7.0 and higher on Windows 2008 and later systems:
Open IIS Manager:
For Windows 2008 systems: Select Control Panel > Administrative Tools > Internet Information Services (IIS) Manager.
For Windows 2012 systems: From the desktop, hover your cursor in the upper- or lower- right corner of the screen to show the charms. Click the Start charm, and then click the Internet Information Services (IIS) Manager tile.
In the Connections pane, expand the entry for your computer system, expand Sites, and select the default site, which is the site in which the Watson Explorer Engine virtual directory (vivisimo) is created.
Double-click the Handler Mappings feature.
If the state of CGI-exe is Enabled, no additional configuration is necessary. Proceed to Completing the Installation Process (All Platforms).
If the state of CGI-exe is Disabled, select it and click Edit Feature Permissions from the Actions pane. The Edit Feature Permissions window displays.
Select Execute and click OK to enable applications with the .exe extension to execute in response to CGI requests. If Execute is disabled, select Script > Execute, and then click OK.


问:
How to fix "error: control reaches end of non-void function"?
```<code>int climbStairs(int n ){

    if(n==1){
        return 1;
    }
    if (n>=2){
         return (2+ climbStairs(n-2)+ climbStairs(n-1));
    }
}
</code>```

How do I fix the compiler error?

答:
Your compiler is not as clever as you. You may well know that the function is never called with n less than 1, but the compiler doesn't. Personally I think it's called with n as 0 for typical inputs.

Therefore it thinks that program control can reach the function closing brace } without an explicit return, which formally is undefined behaviour if you make use of the function return value which, to repeat, I think you do.

You have this warning the compiler issues to you elevated to an error, so compilation halts.

Some fixes:

Block the recursion with the stronger if (n <= 1){.

Run-time assert before the closing brace } using assert(false) or similar.

Switch off the elevation of that warning to an error, but do deal with the warning nonetheless.

Some advice from @JonathanLeffler

Don't switch off -Werror — it is too valuable. Deal with the warning. assert(n >= 0); at the top; if (n <= 1) { return 1; } as well. Assertions fire in debug builds; erroneous parameter value handled reasonably safely and sanely even if assertions are not enabled.

Body:
int climbStairs(int n ){

    if(n==1){
        return 1;
    }
    if (n>=2){
         return (2+ climbStairs(n-2)+ climbStairs(n-1));
    }
}

How do I fix the compiler error?


问:
Python 3.x rounding behavior
I was just re-reading What’s New In Python 3.0 and it states:

The round() function rounding strategy and return type have changed.
  Exact halfway cases are now rounded to the nearest even result instead
  of away from zero. (For example, round(2.5) now returns 2 rather than
  3.)

and
the documentation for round:

For the built-in types supporting round(), values are rounded to the
  closest multiple of 10 to the power minus n; if two multiples are
  equally close, rounding is done toward the even choice

So, under v2.7.3:

```<code>In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0
</code>```

as I'd have expected. However, now under v3.2.3:

```<code>In [32]: round(2.5)
Out[32]: 2

In [33]: round(3.5)
Out[33]: 4
</code>```

This seems counter-intuitive and contrary to what I understand about
rounding (and bound to trip up people). English isn't my native language but
until I read this I thought I knew what rounding meant :-/  I am sure
at the time v3 was introduced there must have been some discussion of
this, but I was unable to find a good reason in my search.

Does anyone have insight into why this was changed to this?

Are there any other mainstream programming languages (e.g., C, C++, Java, Perl, ..) that do this sort of (to  me inconsistent) rounding?

What am I missing here?

UPDATE: @Li-aungYip's comment re "Banker's rounding" gave me the right search term/keywords to search for and I found this SO question: Why does .NET use banker's rounding as default?, so I will be reading that carefully.

答:
You can control the rounding you  using the math.ceil module:</p>

```<code>import math
print(math.ceil(2.5))
> 3
</code>```

Title: Python 3.x rounding behavior

Body:
I was just re-reading What’s New In Python 3.0 and it states:

The round() function rounding strategy and return type have changed.
  Exact halfway cases are now rounded to the nearest even result instead
  of away from zero. (For example, round(2.5) now returns 2 rather than
  3.)

and
the documentation for round:

For the built-in types supporting round(), values are rounded to the
  closest multiple of 10 to the power minus n; if two multiples are
  equally close, rounding is done toward the even choice

So, under v2.7.3:

In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0

as I'd have expected. However, now under v3.2.3:

In [32]: round(2.5)
Out[32]: 2

In [33]: round(3.5)
Out[33]: 4

This seems counter-intuitive and contrary to what I understand about
rounding (and bound to trip up people). English isn't my native language but
until I read this I thought I knew what rounding meant :-/  I am sure
at the time v3 was introduced there must have been some discussion of
this, but I was unable to find a good reason in my search.

Does anyone have insight into why this was changed to this?

Are there any other mainstream programming languages (e.g., C, C++, Java, Perl, ..) that do this sort of (to  me inconsistent) rounding?

What am I missing here?

UPDATE: @Li-aungYip's comment re "Banker's rounding" gave me the right search term/keywords to search for and I found this SO question: Why does .NET use banker's rounding as default?, so I will be reading that carefully.

Body:
You can control the rounding you  using the math.ceil module:

import math
print(math.ceil(2.5))
> 3


问:
How to use a gem method (returning strings) as custom validation in rails app
I'm new to RoR/Gems, this is a basic question.

I created a gem, MyNameGem, in order to learn the process. It contains these methods:

```<code>def returnValidationString1
  puts 'Validation String'
end
def returnValidationString2
  puts 'ANother Validation String'
end
</code>```

I included the gem in a simple rails app, everything seems to be working as expected.
I this to my model:

```<code>validates :name => MyNameGem.returnValidationString1
</code>```

What I'm trying to create is a gem that I can use inside a validation routine. So, for example, I want to do this: validates :name => (call my gem method, return a string, and use that string as the validation requirement)

答:
puts only prints to console.

if you want to return 'MyNameGem' write return 'MyNameGem' or simply 'MyNameGem because the last line gets returned automatically.

Body:
I'm new to RoR/Gems, this is a basic question.

I created a gem, MyNameGem, in order to learn the process. It contains these methods:

def returnValidationString1
  puts 'Validation String'
end
def returnValidationString2
  puts 'ANother Validation String'
end

I included the gem in a simple rails app, everything seems to be working as expected.
I this to my model:

validates :name => MyNameGem.returnValidationString1

What I'm trying to create is a gem that I can use inside a validation routine. So, for example, I want to do this: validates :name => (call my gem method, return a string, and use that string as the validation requirement)


问:
Conditionally moving the position of a single data label in a pie chart
The following sample code will generate the donut chart I'll use as my example:

```<code>import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.weight'] = 'extra bold'

size_of_groups=[12,11,30,0.3]

colors = ['#a1daaa','#bbbbb4','#444511','#1afff2']

import matplotlib as mpl
mpl.rcParams['text.color'] = '#273859'

# Create a pieplot
my_pie,texts,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',
             'size':15  #, 'weight':"extra bold"
            }, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.
labels=['High','Low','Normal','NA']
plt.legend(my_pie,labels,loc='lower center',ncol=2,bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')
fig1 = plt.gcf()
fig1.show()
</code>```

The above outputs this:

Mostly, this is great. Finally I got a nice looking donut chart!

But there is just one last thing to finesse - when the portion of the donut chart is very small (like the 0.6%), I need the labels to be moved out of the chart, and possibly colored black instead.

I managed to do something similar for bar charts using plt.text, but I don't think that will be feasible with pie charts at all. I figure someone has definitely solved a similar problem before, but I can't readily fine any decent solutions.

答:
I attempted a solution by tweaking the solution of ImportanceOfBeingErnest on a different problem given here. For some reason, the percentage sign is not being displayed in my system but you can figure that out

```<code>rad = 1.2 # Define a radius variable for later use

my_pie, texts, autotexts = plt.pie(size_of_groups, radius=rad, colors=colors, autopct="%.1f%%",
                     pctdistance=0.75, labeldistance=0.7, textprops={'color':'white', 'size':20})

# Rest of the code

cx, cy = 0, 0 # Center of the pie chart

for t in autotexts:
    x, y = t.get_position()
    text = t.get_text()

    if float(text.strip('%')) < 1: # Here 1 is the target threshold percentage
        angle = np.arctan2(y-cy, x-cx)
        xt, yt = 1.1*rad*np.cos(angle)+cx, 1.1*rad*np.sin(angle)+cy
        t.set_color("k")
        t.set_position((xt,yt))
</code>```

Body:
The following sample code will generate the donut chart I'll use as my example:

import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.weight'] = 'extra bold'

size_of_groups=[12,11,30,0.3]

colors = ['#a1daaa','#bbbbb4','#444511','#1afff2']

import matplotlib as mpl
mpl.rcParams['text.color'] = '#273859'

# Create a pieplot
my_pie,texts,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',
             'size':15  #, 'weight':"extra bold"
            }, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.
labels=['High','Low','Normal','NA']
plt.legend(my_pie,labels,loc='lower center',ncol=2,bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')
fig1 = plt.gcf()
fig1.show()

The above outputs this:

Mostly, this is great. Finally I got a nice looking donut chart!

But there is just one last thing to finesse - when the portion of the donut chart is very small (like the 0.6%), I need the labels to be moved out of the chart, and possibly colored black instead.

I managed to do something similar for bar charts using plt.text, but I don't think that will be feasible with pie charts at all. I figure someone has definitely solved a similar problem before, but I can't readily fine any decent solutions.

Body:
I attempted a solution by tweaking the solution of ImportanceOfBeingErnest on a different problem given here. For some reason, the percentage sign is not being displayed in my system but you can figure that out

rad = 1.2 # Define a radius variable for later use

my_pie, texts, autotexts = plt.pie(size_of_groups, radius=rad, colors=colors, autopct="%.1f%%",
                     pctdistance=0.75, labeldistance=0.7, textprops={'color':'white', 'size':20})

# Rest of the code

cx, cy = 0, 0 # Center of the pie chart

for t in autotexts:
    x, y = t.get_position()
    text = t.get_text()

    if float(text.strip('%')) < 1: # Here 1 is the target threshold percentage
        angle = np.arctan2(y-cy, x-cx)
        xt, yt = 1.1*rad*np.cos(angle)+cx, 1.1*rad*np.sin(angle)+cy
        t.set_color("k")
        t.set_position((xt,yt))


问:
Code only runs on Woocommerce shop page but not on other Wordpress/Woocomerce pages
I have tried to add a quantity input field to all my Wordpress pages which display Woocommerce products. My code adds a quantity input file to all products on all pages as intended but it only processes inputs on the Woocomerce shop page. If the product is on any other page including Woocommerce category pages only the input field is shown but id does not affect anything. Anyone got any idea what I am missing? Thank you.</p>

```<code>/**
 * Add quantity field on the archive page.
 */
function custom_quantity_field_archive() {

    $product = wc_get_product( get_the_ID() );

    if ( ! $product->is_sold_individually() && 'variable' != $product->product_type && $product->is_purchasable() ) {
        woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
    }

}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );

/**
 * Add requires JavaScript.
 */
function custom_add_to_cart_quantity_handler() {

    wc_enqueue_js( '
        jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
            return false;
        });
        jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
            var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
            // For AJAX add-to-cart actions
            add_to_cart_button.data( "quantity", jQuery( this ).val() );
            // For non-AJAX add-to-cart actions
            add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
        });
    ' );

}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );
</code>```

答: post-type-archive-product needs to be replaced with type-product</p>

Body:
I have tried to add a quantity input field to all my Wordpress pages which display Woocommerce products. My code adds a quantity input file to all products on all pages as intended but it only processes inputs on the Woocomerce shop page. If the product is on any other page including Woocommerce category pages only the input field is shown but id does not affect anything. Anyone got any idea what I am missing? Thank you.

/**
 * Add quantity field on the archive page.
 */
function custom_quantity_field_archive() {

    $product = wc_get_product( get_the_ID() );

    if ( ! $product->is_sold_individually() && 'variable' != $product->product_type && $product->is_purchasable() ) {
        woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
    }

}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );

/**
 * Add requires JavaScript.
 */
function custom_add_to_cart_quantity_handler() {

    wc_enqueue_js( '
        jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
            return false;
        });
        jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
            var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
            // For AJAX add-to-cart actions
            add_to_cart_button.data( "quantity", jQuery( this ).val() );
            // For non-AJAX add-to-cart actions
            add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
        });
    ' );

}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );