问:
Dynamic collection of classes
It works, but I don't know how:
I want to create a dynamic number of classes, so I use a dictionary for that.
But I can't add a key to each class of the dictionary.
It works when I add each entry of the 1st dictionary to a second dictionary as a couple item/key.

```<code>sub test()
Dim dict As New Dictionary
Dim dict2 As New Dictionary

For i = 1 To 2
    Set dict(i) = New Cfgadress
    dict(i).Col1 = i
    dict2.Add "d" & i, dict(i)
Next i

Debug.Print dict2("d1").Col1
Debug.Print dict2("d2").Col1
End Sub
</code>```

That was a guess and I'm not sure I understand how it works : is the entry of the first dictionary a class object, while the entry of the second dictionary is a dictionary object (couple item/key) ?

答:
I think I get it, correct me if I'm wrong.

When I create a dictionary entry with

```<code>Set dict(i) = New Cfgadress
</code>```

It creates a new dictionary entry: blank object of class Cfgadress associated to the key i

Dict(i) refers to the item contained in entry i of the dictionary dict, i.e. to the class object contained.

To change the key, I need to assign a new couple item/key, but the item exists only as entry i of the dictionnary. So I need either :

to use the entry of the dictionary as an item associated with a key in a new dictionary/collection/array (what I did in my code)

or to assign dict(i) to an object, add it to the with a correct key and remove the former one.

```<code>Set object as New class
Set object=dict(i)
dict.Add "key", object
dict.remove "1"
</code>```

Did I get it ?

Your solution is way simpler and that's what I tried first, but I went to dynamic dictionary because on each iteration, updating the class instance was also updating the previous entries of the collection

```<code>Set Wb = ThisWorkbook           '==================
Set WsCfg = Wb.Sheets("Cfg")    '==================

Dim dict_cfg As New Dictionary
Dim coll As New Collection
Set tcfg_adress = New Cfgadress

For i = 3 To 4 '22

    If WsCfg.Cells(i, 10) = 1 And WsCfg.Cells(i, 11) = 1 Then
        tcfg_adress.Row1 = WsCfg.Cells(i, 4).Value
        tcfg_adress.Col1 = WsCfg.Cells(i, 5).Value
        tcfg_adress.Lrow = WsCfg.Cells(i, 6).Value
        tcfg_adress.Lcol = WsCfg.Cells(i, 7).Value
        tcfg_adress.Nbrow = WsCfg.Cells(i, 8).Value
        tcfg_adress.Nbcol = WsCfg.Cells(i, 9).Value
        coll.Add tcfg_adress, WsCfg.Cells(i, 1)

     End If
Next i
</code>```

Turns out that setting a new class instance in each loop, as I saw you did in your code, solved my problem. I thought there was nothing to do and was investigating in get arounds. Thanks a lot !

Title: Dynamic collection of classes

Body:
It works, but I don't know how:
I want to create a dynamic number of classes, so I use a dictionary for that.
But I can't add a key to each class of the dictionary.
It works when I add each entry of the 1st dictionary to a second dictionary as a couple item/key.

sub test()
Dim dict As New Dictionary
Dim dict2 As New Dictionary

For i = 1 To 2
    Set dict(i) = New Cfgadress
    dict(i).Col1 = i
    dict2.Add "d" & i, dict(i)
Next i

Debug.Print dict2("d1").Col1
Debug.Print dict2("d2").Col1
End Sub

That was a guess and I'm not sure I understand how it works : is the entry of the first dictionary a class object, while the entry of the second dictionary is a dictionary object (couple item/key) ?

Body:
I think I get it, correct me if I'm wrong.

When I create a dictionary entry with

Set dict(i) = New Cfgadress

It creates a new dictionary entry: blank object of class Cfgadress associated to the key i

Dict(i) refers to the item contained in entry i of the dictionary dict, i.e. to the class object contained.

To change the key, I need to assign a new couple item/key, but the item exists only as entry i of the dictionnary. So I need either :

to use the entry of the dictionary as an item associated with a key in a new dictionary/collection/array (what I did in my code)

or to assign dict(i) to an object, add it to the with a correct key and remove the former one.

Set object as New class
Set object=dict(i)
dict.Add "key", object
dict.remove "1"

Did I get it ?

Your solution is way simpler and that's what I tried first, but I went to dynamic dictionary because on each iteration, updating the class instance was also updating the previous entries of the collection

Set Wb = ThisWorkbook           '==================
Set WsCfg = Wb.Sheets("Cfg")    '==================

Dim dict_cfg As New Dictionary
Dim coll As New Collection
Set tcfg_adress = New Cfgadress

For i = 3 To 4 '22

    If WsCfg.Cells(i, 10) = 1 And WsCfg.Cells(i, 11) = 1 Then
        tcfg_adress.Row1 = WsCfg.Cells(i, 4).Value
        tcfg_adress.Col1 = WsCfg.Cells(i, 5).Value
        tcfg_adress.Lrow = WsCfg.Cells(i, 6).Value
        tcfg_adress.Lcol = WsCfg.Cells(i, 7).Value
        tcfg_adress.Nbrow = WsCfg.Cells(i, 8).Value
        tcfg_adress.Nbcol = WsCfg.Cells(i, 9).Value
        coll.Add tcfg_adress, WsCfg.Cells(i, 1)

     End If
Next i

Turns out that setting a new class instance in each loop, as I saw you did in your code, solved my problem. I thought there was nothing to do and was investigating in get arounds. Thanks a lot !


来源: stackexchange

问:
MySQL : transaction within a stored procedure
The basic structure of my stored procedure is,

```<code>BEGIN

    .. Declare statements ..

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;

END
</code>```

MySQL version: 5.1.61-0ubuntu0.11.10.1-log

Currently, if 'query 2' fails, result of 'query 1' is committed.

How can I rollback the transaction if any of the query fails?

答:
[This is just an explanation not addressed in other answers]

At least in recent versions of MySQL, your first query is not committed.

If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.

What's going on?

When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.

So BE CAREFUL, any table/row that was locked with a previous query like SELECT ... FOR SHARE/UPDATE, UPDATE, INSERT or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a following query commits it explicitly (COMMIT) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).

That's why the solution involves declaring handlers to immediately ROLLBACK when an error happens.

Extra

Inside the handler you can also re-raise the error using RESIGNAL, otherwise the stored procedure executes "Successfully":

BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
        BEGIN
            ROLLBACK;
            RESIGNAL;
        END;

    START TRANSACTION;
        -- .. Query 1 ..
        -- .. Query 2 ..
        -- .. Query 3 ..
    COMMIT;
END;
```

ContentLicense: CC BY-SA 3.0

Body:
The basic structure of my stored procedure is,

BEGIN

    .. Declare statements ..

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;

END

MySQL version: 5.1.61-0ubuntu0.11.10.1-log

Currently, if 'query 2' fails, result of 'query 1' is committed.

How can I rollback the transaction if any of the query fails?

ContentLicense: CC BY-SA 4.0


问:
Which azure service plan is best for hosting an SPA with high traffic
SPA in Angular 8 needs hosting on the Azure web app. which will be the best plan Basic, Standard or Premium? or can we go with the Azure Storage approach?</p>

答:
App service plan in Azure is essentially the set of compute resources for your application to run, and each every app service plan tier offers some features.

As you have mentioned that this is going to be your production build and incoming traffic to the app would be higher - The Standard app service plan should be fine for you which is recommended for production workloads. As far as the tier is concerned - you can start with S1 and monitor the traffic or load or even perform the stress testing to conclude the right capacity. Going with standard plan will not only offer you the SLA of 99.95% but will also enable you to configure additional and quite useful features such as auto-scaling, custom domain, SSL and daily backups.

Do note that - App Service Free and Shared (preview) hosting plans are base tiers that run on the same Azure virtual machines as other App Service apps. Some apps might belong to other customers. These tiers are intended to be used only for development and testing purposes. So you can still use cost effective plans but ensure that you are using free or shared app service plans only for your development and test environments.


问:
SELECT INTO USING UNION QUERY
I want to create a new table in SQL Server with the following query. I am unable to understand why this query doesn't work.

Query1: Works

```<code>SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
</code>```

Query2: Does not Work.
Error: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near ')'.

```<code>SELECT * INTO [NEW_TABLE]
FROM
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
)
</code>```

Thanks!

答:
Here's one working syntax for SQL Server 2017:</p>

```<code>USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>
</code>```

ContentLicense: CC BY-SA 2.5

Title: SELECT INTO USING UNION QUERY

Body:
I want to create a new table in SQL Server with the following query. I am unable to understand why this query doesn't work.

Query1: Works

SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2

Query2: Does not Work.
Error: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near ')'.

SELECT * INTO [NEW_TABLE]
FROM
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
)

Thanks!

Body:
Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>


问:
inet_ntop() was not decleared in this scope
I am building a TCP server using C: I included the library where the inet_ntop() function is (WS2tcpip.h), yet my compiler returns with the following error:

'inet_ntop' was not declared in this scope

I have no idea why; even my IDE doesn't notice anything wrong (I use vscode as my IDE because it can detect errors in real-time without compiling every time) yet when I compile it gcc returns the error I stated previously.

What I have included and defined:

```<code>#include <stdio.h>
#include <WS2tcpip.h>

#define WIN32_LEAN_AND_MEAN

#pragma comment (lib, "ws2_32.lib")
</code>```

The faulty line of code:

```<code>if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXHOST, 0) == 0) {
        printf("\n[CONNECTION]: %c connesso sulla porta %c", host, service);
    } else {
        inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
        printf("\n[CONNECTION]: %c connesso sulla porta %c", host, ntohs(client.sin_port));
    }
</code>```

Any helpful tip is appreciated, thanks!

答: Are you working on Windows? If not, try including arpa/inet.h</p>

Body:
I am building a TCP server using C: I included the library where the inet_ntop() function is (WS2tcpip.h), yet my compiler returns with the following error:

'inet_ntop' was not declared in this scope

I have no idea why; even my IDE doesn't notice anything wrong (I use vscode as my IDE because it can detect errors in real-time without compiling every time) yet when I compile it gcc returns the error I stated previously.

What I have included and defined:

#include <stdio.h>
#include <WS2tcpip.h>

#define WIN32_LEAN_AND_MEAN

#pragma comment (lib, "ws2_32.lib")

The faulty line of code:

if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXHOST, 0) == 0) {
        printf("\n[CONNECTION]: %c connesso sulla porta %c", host, service);
    } else {
        inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
        printf("\n[CONNECTION]: %c connesso sulla porta %c", host, ntohs(client.sin_port));
    }

Any helpful tip is appreciated, thanks!


问:
How to concatenate char and string on iPhone?
I want to add some marks to separate some strings.
How to add a char to a string?

e.g. add '\x01' to "Hello", add '\x02' before "World" and add '\x03' after "World".

So I can create a string "\x01 Hello \x02 World \x03" which has some separate marks.

答:
Not exactly sure what you're asking... But would stringWithFormat maybe help you?

E.g,

```<code>[NSString stringWithFormat:@"%c%@%c%@%c", 1, @"hello", 2, @"world", 3];
</code>```

OwnerDisplayName: iphony

LastEditorDisplayName: andynormancx

Body:
Not exactly sure what you're asking... But would stringWithFormat maybe help you?

E.g,

[NSString stringWithFormat:@"%c%@%c%@%c", 1, @"hello", 2, @"world", 3];

OwnerDisplayName: squelart


问:
jQuery, optimal usage question
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

```<code>var thingy = $('#thingy');
</code>```

Further down in the code, is there any difference in reusing thingy:

```<code>thingy.empty();
</code>```

versus just making the jQuery again? :

```<code>$('#thingy').empty();
</code>```

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.

答: The other thing to consider is DOM changes. Be sure that, after you set thingy, something doesn't happen that makes $('#thingy') go away!</p>

Title: jQuery, optimal usage question

Body:
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

var thingy = $('#thingy');

Further down in the code, is there any difference in reusing thingy:

thingy.empty();

versus just making the jQuery again? :

$('#thingy').empty();

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.


问:
Rails: Communicating between RSpec helper modules
I would be very grateful for some advice on the following.

Below I have a simplified example for our setup.

I have defined some Helper modules on our RSpec test suite:

```<code>## spec/rails_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.include ViewHelpers
end

### spec/support/view_helpers/base.rb

# frozen_string_literal: true

module ViewHelpers
  class Base
    # class content
  end
end

### spec/support/view_helpers/admins/payments/new.rb

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < Base
        # class content
      end
    end
  end
end
</code>```

With this setup the specs run perfectly locally; the sub-class New inherits from Base as expected. However, when the tests are running on Travis CI, we get the following error:

```<code>NameError:
1433  uninitialized constant ViewHelpers::Admins::Payments::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'
</code>```

I have also tried inheriting with explicit namespacing:

```<code># frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < ViewHelpers::Base
        # class content
      end
    end
  end
end
</code>```

Again, this runs successfully locally but Travis CI errors:

```<code>NameError:
1433  uninitialized constant ViewHelpers::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'
</code>```

I am rather stumped as to why this works locally but not on CI.
Would be very grateful for any support and insight.

Thanks
Sam

答:
It turns out the ordering of

```<code>Dir[Rails.root.join("spec/support/**/*.rb")]
</code>```

depends on the OS and filesystem.

This means the sub-classes were getting required before the super-class.

Solution:

```<code>Dir[Rails.root.join("spec/support/**/*.rb")].sort
</code>```

Body:
I would be very grateful for some advice on the following.

Below I have a simplified example for our setup.

I have defined some Helper modules on our RSpec test suite:

## spec/rails_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.include ViewHelpers
end

### spec/support/view_helpers/base.rb

# frozen_string_literal: true

module ViewHelpers
  class Base
    # class content
  end
end

### spec/support/view_helpers/admins/payments/new.rb

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < Base
        # class content
      end
    end
  end
end

With this setup the specs run perfectly locally; the sub-class New inherits from Base as expected. However, when the tests are running on Travis CI, we get the following error:

NameError:
1433  uninitialized constant ViewHelpers::Admins::Payments::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'

I have also tried inheriting with explicit namespacing:

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < ViewHelpers::Base
        # class content
      end
    end
  end
end

Again, this runs successfully locally but Travis CI errors:

NameError:
1433  uninitialized constant ViewHelpers::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'

I am rather stumped as to why this works locally but not on CI.
Would be very grateful for any support and insight.

Thanks
Sam

Body:
It turns out the ordering of

Dir[Rails.root.join("spec/support/**/*.rb")]

depends on the OS and filesystem.

This means the sub-classes were getting required before the super-class.

Solution:

Dir[Rails.root.join("spec/support/**/*.rb")].sort


问:
How to loop a question until getting the answer from scanner?
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}
```

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

答:
You should consider a 'do-while' loop, since you want to run the code once regardless of whether or not the condition is fulfilled. Then, at the end of the loop, you can check if the condition is fulfilled. If it is not fulfilled, it will run again. For example:

```<code>public static String[] positionQuery(int dim) {

    boolean errorEncountered = false;
    String[] coordinates;
    Scanner stdin = new Scanner(System.in);

    do {
        if(errorEncountered)
             System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        else {
            System.out.println("Provide origin and destination coordinates.");
            System.out.println("Enter two positions between A1-H8:");
        }
        String s1 = stdin.nextLine();
        coordinates = s1.split(" ");
        String origin = coordinates[0];
        String dest = coordinates[1];
        if(!validCoordinate(origin, dim) || !validCoordinate(dest,dim) || coordinates.length != 2) //makes sure there's only 2 coords
            errorEncountered = true;
        else
            errorEncountered = false;
    } while (errorEncountered);

    return coordinates;
}
</code>```

In this example, I have taken the liberty of removing the Scanner test_in input, since you didn't use it.

I also noticed you were returning the String[] wrong. If you just want to return the String[] as generated by the split(), you should be returning that variable. Not making a new String[] (See the above example).

This loop (like all loops) could also be accomplished with a while(true) that breaks or returns for the right condition. However, these are sometimes considered bad practice (see Are "while(true)" loops so bad?) because when you learn to write more complicated code, a bunch of break's or return's can make the code very confusing and difficult to read. Thus, you're better-off getting in the habit of using booleans.

Body:
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

Body:
You should consider a 'do-while' loop, since you want to run the code once regardless of whether or not the condition is fulfilled. Then, at the end of the loop, you can check if the condition is fulfilled. If it is not fulfilled, it will run again. For example:

public static String[] positionQuery(int dim) {

    boolean errorEncountered = false;
    String[] coordinates;
    Scanner stdin = new Scanner(System.in);

    do {
        if(errorEncountered)
             System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        else {
            System.out.println("Provide origin and destination coordinates.");
            System.out.println("Enter two positions between A1-H8:");
        }
        String s1 = stdin.nextLine();
        coordinates = s1.split(" ");
        String origin = coordinates[0];
        String dest = coordinates[1];
        if(!validCoordinate(origin, dim) || !validCoordinate(dest,dim) || coordinates.length != 2) //makes sure there's only 2 coords
            errorEncountered = true;
        else
            errorEncountered = false;
    } while (errorEncountered);

    return coordinates;
}

In this example, I have taken the liberty of removing the Scanner test_in input, since you didn't use it.

I also noticed you were returning the String[] wrong. If you just want to return the String[] as generated by the split(), you should be returning that variable. Not making a new String[] (See the above example).

This loop (like all loops) could also be accomplished with a while(true) that breaks or returns for the right condition. However, these are sometimes considered bad practice (see Are "while(true)" loops so bad?) because when you learn to write more complicated code, a bunch of break's or return's can make the code very confusing and difficult to read. Thus, you're better-off getting in the habit of using booleans.


问:
How to Use Javascript and AJAX to Upload into Wasabi Storage
How would I use client-side browser Javascript with AJAX to upload a file into Wasabi Storage?</p>

答:
Pankaj at Wasabi Tech Support got back to me and said that this code snippet will work just fine. They recommend one download and use the Amazon AWS SDK for S3 because Wasabi is S3 API compliant.</p>

```<code><!DOCTYPE html>
<html>
<head>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.619.0.min.js"></script>
</head>
<body>

  <h1>Wasabi Upload Test</h1>
  <input type="file" id="wasabiupload" onchange="handleFile()" />

<script>

function handleFile() {
  // console.log("handle file - " + JSON.stringify(event, null, 2));
  var files = document.getElementById('wasabiupload').files;
  if (!files.length) {
    return alert('Please choose a file to upload first.');
  }
  var f = files[0];
  var fileName = f.name;

  const s3 = new AWS.S3({
    correctClockSkew: true,
    endpoint: 'https://s3.wasabisys.com', //use appropriate endpoint as per region of the bucket
    accessKeyId: 'Wasabi-Access-keys',
    secretAccessKey: 'Wasabi-Secret-Access-key',
    region: 'us-east-1'
    ,logger: console
  });

  console.log('Loaded');
  const uploadRequest = new AWS.S3.ManagedUpload({
    params: { Bucket: 'bucket-name', Key: 'file-name', Body: f },
    service: s3
  });

  uploadRequest.on('httpUploadProgress', function(event) {
    const progressPercentage = Math.floor(event.loaded * 100 / event.total);
    console.log('Upload progress ' + progressPercentage);
  });

  console.log('Configed and sending');

  uploadRequest.send(function(err) {
    if (err) {
      console.log('UPLOAD ERROR: ' + JSON.stringify(err, null, 2));
    } else {
      console.log('Good upload');
    }
  });

}
</script>
</body>
</html>
</code>```

Body:
Pankaj at Wasabi Tech Support got back to me and said that this code snippet will work just fine. They recommend one download and use the Amazon AWS SDK for S3 because Wasabi is S3 API compliant.

<!DOCTYPE html>
<html>
<head>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.619.0.min.js"></script>
</head>
<body>

  <h1>Wasabi Upload Test</h1>
  <input type="file" id="wasabiupload" onchange="handleFile()" />

<script>

function handleFile() {
  // console.log("handle file - " + JSON.stringify(event, null, 2));
  var files = document.getElementById('wasabiupload').files;
  if (!files.length) {
    return alert('Please choose a file to upload first.');
  }
  var f = files[0];
  var fileName = f.name;

  const s3 = new AWS.S3({
    correctClockSkew: true,
    endpoint: 'https://s3.wasabisys.com', //use appropriate endpoint as per region of the bucket
    accessKeyId: 'Wasabi-Access-keys',
    secretAccessKey: 'Wasabi-Secret-Access-key',
    region: 'us-east-1'
    ,logger: console
  });

  console.log('Loaded');
  const uploadRequest = new AWS.S3.ManagedUpload({
    params: { Bucket: 'bucket-name', Key: 'file-name', Body: f },
    service: s3
  });

  uploadRequest.on('httpUploadProgress', function(event) {
    const progressPercentage = Math.floor(event.loaded * 100 / event.total);
    console.log('Upload progress ' + progressPercentage);
  });

  console.log('Configed and sending');

  uploadRequest.send(function(err) {
    if (err) {
      console.log('UPLOAD ERROR: ' + JSON.stringify(err, null, 2));
    } else {
      console.log('Good upload');
    }
  });

}
</script>
</body>
</html>


问:
AND Operator cannot work with bool and string
I have a LINQ2SQL statement where I am using two criteria:

```<code>var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"
</code>```

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

答: You have a single equals sign r.Status = '"I", should be r.Status == '"I"

Body:
I have a LINQ2SQL statement where I am using two criteria:

var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?


问:
text-file manipulation in bash
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

```<code>cat data.txt | dot -Tpng > image.png
</code>```

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

答:
Try Awk.

awk 'BEGIN { print "digraph (" }
    1
    END { print ")" }' data.txt |
dot -Tpng > image.png
```

1 is a simple Awk shorthand for { print }.
The cat was not strictly necessary,

Title: text-file manipulation in bash

Body:
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

cat data.txt | dot -Tpng > image.png

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

Body:
Try Awk.

awk 'BEGIN { print "digraph (" }
    1
    END { print ")" }' data.txt |
dot -Tpng > image.png

1 is a simple Awk shorthand for { print }.
The cat was not strictly necessary,


问:
Most performant way to check if elements are overlapping
I know you can calculate if an element is overlapping another by comparing the top|bottom|right|left properties within the getBoundingClientRect method. However, you need to loop through the elements to do so. I'm curious to know what is the performant way of checking to see if an element is overlapping any other element. For example, checking to see if label one is overlaying any other element. Then checking to see if label two is overlapping any other element including label one without using a loop each time, or is this the only way?

const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
// dismiss -- just creating less CSS
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 1; i < points.length; i++) {
    if (!(
        rightPos(points[i]) < leftPos(points[i - 1]) ||
        leftPos(points[i]) > rightPos(points[i - 1]) ||
        btmPos(points[i]) < topPos(points[i - 1]) ||
        topPos(points[i]) > btmPos(points[i - 1])
      )) {
      points[i].innerHTML = `${points[i].innerHTML} C`;
      console.log(i);
    }
    if (i === points.length - 1) {
      return
    }
  }
}

overlayCheck();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}</code>```

Label 1

Label 2

Label 3

Label 4

Label 5

Label 6

```

答:
I figured out a way thru trial and error. I'll post this here for anyone else who could use it.

// dismiss -- just creating less CSS
const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

//function to check for overlapping
function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 0; i < points.length; i++) {
    for (let j = 0; j < points.length; j++) {
      let isOverlapping = !(
        rightPos(points[i]) < leftPos(points[j]) ||
        leftPos(points[i]) > rightPos(points[j]) ||
        btmPos(points[i]) < topPos(points[j]) ||
        topPos(points[i]) > btmPos(points[j])
      );

      if (isOverlapping && j !== i) {
        points[i].innerHTML = `${points[i].innerHTML} C`;
      }
    }
  }
}
overlayCheck();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}</code>```

Label 1

Label 2

Label 3

Label 4

Label 5

Label 6

```

Body:
I know you can calculate if an element is overlapping another by comparing the top|bottom|right|left properties within the getBoundingClientRect method. However, you need to loop through the elements to do so. I'm curious to know what is the performant way of checking to see if an element is overlapping any other element. For example, checking to see if label one is overlaying any other element. Then checking to see if label two is overlapping any other element including label one without using a loop each time, or is this the only way?

const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
// dismiss -- just creating less CSS
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 1; i < points.length; i++) {
    if (!(
        rightPos(points[i]) < leftPos(points[i - 1]) ||
        leftPos(points[i]) > rightPos(points[i - 1]) ||
        btmPos(points[i]) < topPos(points[i - 1]) ||
        topPos(points[i]) > btmPos(points[i - 1])
      )) {
      points[i].innerHTML = `${points[i].innerHTML} C`;
      console.log(i);
    }
    if (i === points.length - 1) {
      return
    }
  }
}

overlayCheck();

.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}

Label 1

Label 2

Label 3

Label 4

Label 5

Label 6

Body:
I figured out a way thru trial and error. I'll post this here for anyone else who could use it.

// dismiss -- just creating less CSS
const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

//function to check for overlapping
function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 0; i < points.length; i++) {
    for (let j = 0; j < points.length; j++) {
      let isOverlapping = !(
        rightPos(points[i]) < leftPos(points[j]) ||
        leftPos(points[i]) > rightPos(points[j]) ||
        btmPos(points[i]) < topPos(points[j]) ||
        topPos(points[i]) > btmPos(points[j])
      );

      if (isOverlapping && j !== i) {
        points[i].innerHTML = `${points[i].innerHTML} C`;
      }
    }
  }
}
overlayCheck();

.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}

<div class="parent">
  <div class="label cover">Label 1</div>
  <div class="label">Label 2</div>
  <div class="label">Label 3</div>
  <div class="label">Label 4</div>
  <div class="label">Label 5</div>
  <div class="label">Label 6</div>
</div>


答:
The best way to host Single Page Application is by the usage of Storage Account. Besides the huge cost saving, you can easily integrate it with CDN to fast the deliver of the assets to your end users.

Useful links:

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website

https://csharp.christiannagel.com/2018/08/08/angularwithazurestorage/

Title: Which azure service plan is best for hosting an SPA with high traffic

Body: SPA in Angular 8 needs hosting on the Azure web app. which will be the best plan Basic, Standard or Premium? or can we go with the Azure Storage approach?


问:
Merging nested object fields into a single nested array field in MongoDB Aggregation
As part of my aggregation pipeline I have the following scenario. This is the result of grouping previously unwound fields from each document (so in this case there are two documents with the same _id but with a different value for UniqueFieldName)

```<code>    TopLevelField: [
        {
            UniqueFieldName: "Values go here!"
        },
        {
            UniqueFieldName: "More values go here too!"
        }
    ]
</code>```

All I want to do is merge the nested object fields into one field and push all the values into that field as an array, like so.

```<code>    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
    }
</code>```

The idea is that I could have multiple fields with multiple values under each field grouped together for easier iteration.

```<code>    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
        SecondFieldName: [
             "This is text",
        ],
        AnotherOne: [
             "TEXT",
             "Here too!",
             "More values",
        ],
    }
</code>```

The problem I run into is that trying to use dot notation in the $group stage throws an error. It seems that mongo doesn't like to group with nested objects like this?

The easy solution is to just change the TopLevelField to some concatenation of the nested fields like this,

```<code>    TopLevelField-UniqueFieldName: [
         "Values go here!",
         "More values go here too!",
    ],
    TopLevelField-SecondFieldName: [
         "This is text",
    ],
    TopLevelField-AnotherOne: [
         "TEXT",
         "Here too!",
         "More values",
    ],
</code>```

But this is suboptimal for my use case. Is there a solution to this or do I need to rethink the entire pipeline?

答:
You can try this :

```<code>db.collection.aggregate([
    { $unwind: '$TopLevelField' },
    {
        $group: {
            _id: '', 'UniqueFieldName': { $push: '$TopLevelField.UniqueFieldName' },
            'UniqueFieldName2': { $push: '$TopLevelField.UniqueFieldName2' },
            'UniqueFieldName3': { $push: '$TopLevelField.UniqueFieldName3' },
            'UniqueFieldName4': { $push: '$TopLevelField.UniqueFieldName4' }
        }
    }, { $project: { _id: 0 } }, { $project: { 'TopLevelField': '$$ROOT' } }])
</code>```

Test : MongoDB-Playground

Body:
As part of my aggregation pipeline I have the following scenario. This is the result of grouping previously unwound fields from each document (so in this case there are two documents with the same _id but with a different value for UniqueFieldName)

    TopLevelField: [
        {
            UniqueFieldName: "Values go here!"
        },
        {
            UniqueFieldName: "More values go here too!"
        }
    ]

All I want to do is merge the nested object fields into one field and push all the values into that field as an array, like so.

    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
    }

The idea is that I could have multiple fields with multiple values under each field grouped together for easier iteration.

    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
        SecondFieldName: [
             "This is text",
        ],
        AnotherOne: [
             "TEXT",
             "Here too!",
             "More values",
        ],
    }

The problem I run into is that trying to use dot notation in the $group stage throws an error. It seems that mongo doesn't like to group with nested objects like this?

The easy solution is to just change the TopLevelField to some concatenation of the nested fields like this,

    TopLevelField-UniqueFieldName: [
         "Values go here!",
         "More values go here too!",
    ],
    TopLevelField-SecondFieldName: [
         "This is text",
    ],
    TopLevelField-AnotherOne: [
         "TEXT",
         "Here too!",
         "More values",
    ],

But this is suboptimal for my use case. Is there a solution to this or do I need to rethink the entire pipeline?

Body:
You can try this :

db.collection.aggregate([
    { $unwind: '$TopLevelField' },
    {
        $group: {
            _id: '', 'UniqueFieldName': { $push: '$TopLevelField.UniqueFieldName' },
            'UniqueFieldName2': { $push: '$TopLevelField.UniqueFieldName2' },
            'UniqueFieldName3': { $push: '$TopLevelField.UniqueFieldName3' },
            'UniqueFieldName4': { $push: '$TopLevelField.UniqueFieldName4' }
        }
    }, { $project: { _id: 0 } }, { $project: { 'TopLevelField': '$$ROOT' } }])

Test : MongoDB-Playground


问:
I want to make a link where the href is dependent on a js variable
I figured out the whole innerhtml thing but I don't know how to add variables into the href. I want it to make a link with the title being the title you enter and with the javascript that you enter to be in the href when you click "create".

  Bookmarklet Maker

  <input size="13" onkeypress="return searchKeyPress(event);" name="getTitle" type="text" id="getTitle" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Bookmarklet name" />

  <input size="40" onkeypress="return searchKeyPress(event);" name="geJs" type="text" id="getJs" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Javascript" />

  <button style="background-color: #252525;
  border: 2px;
  border-style: solid;
  border-color: white;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;
  margin: 4px 2px;
  cursor: pointer;" id="bookmarkletbutton" onclick="createBookmarklet()">Create</button>

```

答:
  Bookmarklet Maker

  <input size="13" name="getTitle" type="text" id="getTitle" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Bookmarklet name" />

  <input size="40" name="geJs" type="text" id="getJs" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Javascript" />

  <button style="background-color: #252525;
  border: 2px;
  border-style: solid;
  border-color: white;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;
  margin: 4px 2px;
  cursor: pointer;" id="bookmarkletbutton" onclick="createBookmarklet()">Create</button>

```

You were using the wrong id in getElementById in the last line. Also, use .href for changing href value. Hope this helps!

Body:
<div class="title">
  Bookmarklet Maker
  <br>
  <br>
  <input size="13" name="getTitle" type="text" id="getTitle" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Bookmarklet name" />
  <br>
  <input size="40" name="geJs" type="text" id="getJs" style="background-color: #252525;  border: 2px;  border-style: double;  border-color: white;  color: white;  padding: 15px 32px;  text-align: left;  text-decoration: none;  display: inline-block;  font-size: 16px;  font-weight: bold;  margin: 4px 2px;  cursor:;"
    placeholder="Javascript" />
  <br>
  <button style="background-color: #252525;
  border: 2px;
  border-style: solid;
  border-color: white;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;
  margin: 4px 2px;
  cursor: pointer;" id="bookmarkletbutton" onclick="createBookmarklet()">Create</button>
  <script>
    function createBookmarklet() {
      var title_input = document.getElementById('getTitle').value;
      var js_input = document.getElementById('getJs').value;
      document.getElementById('title').innerHTML = title_input;
      document.getElementById('title').href = js_input;
    }
  </script>
  <br>
  <br>
  <a class="link" href="" id="title"></a>
</div>

You were using the wrong id in getElementById in the last line. Also, use .href for changing href value. Hope this helps!


问:
Python- Wireless Controller & List of Addends/Values
Hardware: RPi4 4GB, SteelSeries Stratus Duo WiFi/BTLE wireless controller

Long Term Goal: Perform multiple tasks (i.e., move/zero the toolhead, start/pause/stop the program, etc.) using the wireless controller which will interface with the RPi that is running a server that controls a CNC router.

Short Term Goal: Determine which combination of buttons are being pressed without using an ungodly number of if/elif statements.

Summary: I have already figured out how to read the output from the wireless controller using PyUSB. I've altered/added code to that which was included with PyUSB to produce some human-readable results. The output is formatted in a list, with each item's value being determined by some sort of button combination. (I know it says "array", but Python appears to treat it as a list.)

This is the output when no buttons are pressed (Default):

```<code>array('B', [0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
</code>```

The first two values (...[0, 20,...]) seem to be some sort of identifiers, and those never change. Multiple buttons, however, utilize the same indexed location in the list. They all have different values, and are summed when pressed simultaneously. No combination of button values generate the same output for the indexed location. Examples:

Button A: array('B', [0, 20, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left: array('B', [0, 20, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left & A: array('B', [0, 20, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Here is my current program, and as you can see the if/elif statements are starting to get a little out of hand.:

```<code>#!/usr/bin/python
from __future__ import division

import usb.core
import usb.util
import time
import os
import sys
#import csv

USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS

USB_VENDOR  = 0x1038 # SteelSeries
USB_PRODUCT = 0x1430 # Stratus Duo

dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)

endpoint = dev[0][(0,0)][0]

if dev.is_kernel_driver_active(USB_IF) is True:
    dev.detach_kernel_driver(USB_IF)

usb.util.claim_interface(dev, USB_IF)

while True:
    control = None

    try:
        control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
        CtrlA = control[2]      #Directional Pad, Start/Select, L/R Stick Press
        CtrlB = control[3]      #Top Left/Top Right, Center, A, B, X, Y
        CtrlC = control[4]      #Left Trigger (0-255)
        CtrlD = control[5]      #Right Trigger (0-255)
        CtrlEH = control[6:10]  #Left Stick
        CtrlIL = control[10:14] #Right Stick
        print control
        if CtrlA ==0:
            print "No Input"
        elif CtrlA == 1:
            print "Directional Pad: Up"
        elif CtrlA == 2:
            print "Directional Pad: Down"
        elif CtrlA == 4:
            print "Directional Pad: Left"
        elif CtrlA == 8:
            print "Directional Pad: Right"
        elif CtrlA == 16:
            print "Right Center Button"
        elif CtrlA == 32:
            print "Left Center Button"
        elif CtrlA == 64:
            print "Left Stick Pressed"
        elif CtrlA == 128:
            print "Right Stick Pressed"
        elif CtrlA == 192:
            print "Right & Left Sticks Pressed"
        else:
            break

        if CtrlC == 0:
            print "Left Trigger: No Input"
        elif 1 <= CtrlC <=254:
            print "Left Trigger: " + "{:.0%}".format(CtrlC/255)
        elif CtrlC == 255:
            print "Left Trigger: Max"
        else:
            break

        if CtrlD == 0:
            print "Right Trigger: No Input"
        elif 1 <= CtrlD <=254:
            print "Right Trigger: " + "{:.0%}".format(CtrlD/255)
        elif CtrlD == 255:
            print "Right Trigger: Max"
        else:
            break

except:
pass

#Let Ctrl+C actually exit.
time.sleep(0.01)
</code>```

Again, my desired result would be for the program to determine the combination of buttons being pressed- For instance, if the value for control[3] is 17, is there a way to efficiently have the program determine that it is a combination of the assigned values of 16 and 1 (The 'A' button & the 'Top Left' button)?

I've looked into possibly using a CSV file, itertools(permutations, combinations, etc.), embedded lists, and other such possible solutions. At first glance, all of these appear to be somewhere in the ballpark of what I want to do. Unfortunately, none of these (at least by themselves) appear to accomplish the goal. This is a completely uncharted area of programming for me, and any guidance would be greatly appreciated.

答:
Here's what I'd do.

I'd assign each button its own tuple of position and value, like this:

buttons = [
    ('dir_up', 2, 1),
    ('dir_down', 2, 2),
    ('dir_left', 2, 4),
    ('dir_right', 2, 8),
    # ... etc, other buttons here
]
```

<p>Then you can see which buttons are actually pressed with a generator:</p>

<pre class="lang-py prettyprint-override"><code>def pressed_buttons(control):
    for button in buttons:
        name, control_pos, value = button
        # To check if the button was pressed, perform a binary masking
        if control[control_pos] & value == value:
            yield button
</code>```

P. S. For added clarity, you might find namedtuples or even enums useful.

Body:
Hardware: RPi4 4GB, SteelSeries Stratus Duo WiFi/BTLE wireless controller

Long Term Goal: Perform multiple tasks (i.e., move/zero the toolhead, start/pause/stop the program, etc.) using the wireless controller which will interface with the RPi that is running a server that controls a CNC router.

Short Term Goal: Determine which combination of buttons are being pressed without using an ungodly number of if/elif statements.

Summary: I have already figured out how to read the output from the wireless controller using PyUSB. I've altered/added code to that which was included with PyUSB to produce some human-readable results. The output is formatted in a list, with each item's value being determined by some sort of button combination. (I know it says "array", but Python appears to treat it as a list.)

This is the output when no buttons are pressed (Default):

array('B', [0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

The first two values (...[0, 20,...]) seem to be some sort of identifiers, and those never change. Multiple buttons, however, utilize the same indexed location in the list. They all have different values, and are summed when pressed simultaneously. No combination of button values generate the same output for the indexed location. Examples:

Button A: array('B', [0, 20, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left: array('B', [0, 20, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left & A: array('B', [0, 20, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Here is my current program, and as you can see the if/elif statements are starting to get a little out of hand.:

#!/usr/bin/python
from __future__ import division

import usb.core
import usb.util
import time
import os
import sys
#import csv

USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS

USB_VENDOR  = 0x1038 # SteelSeries
USB_PRODUCT = 0x1430 # Stratus Duo

dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)

endpoint = dev[0][(0,0)][0]

if dev.is_kernel_driver_active(USB_IF) is True:
    dev.detach_kernel_driver(USB_IF)

usb.util.claim_interface(dev, USB_IF)

while True:
    control = None

    try:
        control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
        CtrlA = control[2]      #Directional Pad, Start/Select, L/R Stick Press
        CtrlB = control[3]      #Top Left/Top Right, Center, A, B, X, Y
        CtrlC = control[4]      #Left Trigger (0-255)
        CtrlD = control[5]      #Right Trigger (0-255)
        CtrlEH = control[6:10]  #Left Stick
        CtrlIL = control[10:14] #Right Stick
        print control
        if CtrlA ==0:
            print "No Input"
        elif CtrlA == 1:
            print "Directional Pad: Up"
        elif CtrlA == 2:
            print "Directional Pad: Down"
        elif CtrlA == 4:
            print "Directional Pad: Left"
        elif CtrlA == 8:
            print "Directional Pad: Right"
        elif CtrlA == 16:
            print "Right Center Button"
        elif CtrlA == 32:
            print "Left Center Button"
        elif CtrlA == 64:
            print "Left Stick Pressed"
        elif CtrlA == 128:
            print "Right Stick Pressed"
        elif CtrlA == 192:
            print "Right & Left Sticks Pressed"
        else:
            break

        if CtrlC == 0:
            print "Left Trigger: No Input"
        elif 1 <= CtrlC <=254:
            print "Left Trigger: " + "{:.0%}".format(CtrlC/255)
        elif CtrlC == 255:
            print "Left Trigger: Max"
        else:
            break

        if CtrlD == 0:
            print "Right Trigger: No Input"
        elif 1 <= CtrlD <=254:
            print "Right Trigger: " + "{:.0%}".format(CtrlD/255)
        elif CtrlD == 255:
            print "Right Trigger: Max"
        else:
            break

except:
pass

#Let Ctrl+C actually exit.
time.sleep(0.01)

Again, my desired result would be for the program to determine the combination of buttons being pressed- For instance, if the value for control[3] is 17, is there a way to efficiently have the program determine that it is a combination of the assigned values of 16 and 1 (The 'A' button & the 'Top Left' button)?

I've looked into possibly using a CSV file, itertools(permutations, combinations, etc.), embedded lists, and other such possible solutions. At first glance, all of these appear to be somewhere in the ballpark of what I want to do. Unfortunately, none of these (at least by themselves) appear to accomplish the goal. This is a completely uncharted area of programming for me, and any guidance would be greatly appreciated.

Body:
Here's what I'd do.

I'd assign each button its own tuple of position and value, like this:

buttons = [
    ('dir_up', 2, 1),
    ('dir_down', 2, 2),
    ('dir_left', 2, 4),
    ('dir_right', 2, 8),
    # ... etc, other buttons here
]

Then you can see which buttons are actually pressed with a generator:

def pressed_buttons(control):
    for button in buttons:
        name, control_pos, value = button
        # To check if the button was pressed, perform a binary masking
        if control[control_pos] & value == value:
            yield button

P. S. For added clarity, you might find namedtuples or even enums useful.


答:
```<code>var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select r.ID && r.Status == "I";
</code>```

Title: AND Operator cannot work with bool and string


问:
Azure Traffic Manager monitoring status is 'degraded' for Azure Application Gateway
Azure Traffic Manager monitoring status for Endpoints(Azure Application Gateway/WAF)is degraded. Web app behind the Application gateway is healthy and able to access through Traffic Manager.

Any help will be appreciated.

thanks.

答:
I got the solution, this issue comes only if your listener is Multisites. If the listener is Basic for app gateway then it works as expected.

The solution, need to set custom header settings against the hostname. Like below:

```<code>hostname:web1.com,newheader:web2.com
</code>```

You also need to set the custom status code range.
Refer: https://sakaldeep.com.np/1156/troubleshooting-azure-traffic-manager-monitoring-status-is-degraded-for-azure

Body:
I got the solution, this issue comes only if your listener is Multisites. If the listener is Basic for app gateway then it works as expected.

The solution, need to set custom header settings against the hostname. Like below:

hostname:web1.com,newheader:web2.com

You also need to set the custom status code range.
Refer: https://sakaldeep.com.np/1156/troubleshooting-azure-traffic-manager-monitoring-status-is-degraded-for-azure


问:
CSS file blocked: MIME type mismatch (X-Content-Type-Options: nosniff)
I am developing an Angular 4 app and I want to apply some global styles.  Following the tutorial at the angular site, I've created a "styles.css" file in the root directory of my app, and I'm referring to that stylesheet in the index.html of my app:

```<code><link rel="stylesheet" type="text/css" href="styles.css">
</code>```

The angular app is successfully compiled:

```<code>$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.
</code>```

But when I visit http://localhost:4200 in a Chromium browser, the console shows an error at

```<code>GET http://localhost:4200/styles.css
</code>```

In a Firefox browser, the error is a bit more explicit:

```<code>GET
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
</code>```

Both files, index.html and styles.css are located in the root directory of my angular app.
I've tried to get more info about the problem :

```<code>nosniff
    Blocks a request if the requested type is

        "style" and the MIME type is not "text/css", or
        "script" and the MIME type is not a JavaScript MIME type.
</code>```

But I don't understand why it's bloking the request, since I've specified type="text/css" when referencing the stylesheet.

答:
This is solved my problem:</p>

```<code>app.use('/public', express.static(path.join(__dirname, "public")));
</code>```

Body:
I am developing an Angular 4 app and I want to apply some global styles.  Following the tutorial at the angular site, I've created a "styles.css" file in the root directory of my app, and I'm referring to that stylesheet in the index.html of my app:

<link rel="stylesheet" type="text/css" href="styles.css">

The angular app is successfully compiled:

$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.

But when I visit http://localhost:4200 in a Chromium browser, the console shows an error at

GET http://localhost:4200/styles.css

In a Firefox browser, the error is a bit more explicit:

GET
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

Both files, index.html and styles.css are located in the root directory of my angular app.
I've tried to get more info about the problem :

nosniff
    Blocks a request if the requested type is

        "style" and the MIME type is not "text/css", or
        "script" and the MIME type is not a JavaScript MIME type.

But I don't understand why it's bloking the request, since I've specified type="text/css" when referencing the stylesheet.

Body:
This is solved my problem:

app.use('/public', express.static(path.join(__dirname, "public")));


问:
Trouble with Finding Date Range in Pandas
I have a dataset which has a list of subjects, a start date, and an end date. I'm trying to do a loop so that for each subject I have a list of dates between the start date and end date. I've tried so many ways to do this based on previous posts but still having issues.

an example of the dataframe:

```<code>Participant #    Start_Date    End_Date
    1             23-04-19     25-04-19
</code>```

An example of the output I want:

```<code>Participant #      Range
      1           23-04-19
      1           24-04-19
      1           25-04-19
</code>```

Right now my code looks like this:

```<code>subjs_490 = tracksheet_490['Participant #']
for subj_490 in subjs_490:
  temp_a = tracksheet_490[tracksheet_490['Participant #'].isin([subj_490])]
  start = temp_a['Start_Date']
  end = temp_a['End_Date'
  start_dates = pd.to_datetime(pd.Series(start), format = '%d-%m-%y')
  end_dates = pd.to_datetime(pd.Series(end), format = '%d-%m-%y')
  date_range = pd.date_range(start_dates, end_dates).tolist()
</code>```

With this method I'm getting the following error:

Cannot convert input [1   2016-05-03 Name: Start_Date, dtype: datetime64[ns]] of type  to Timestamp

答:
Expanding ranges tends to be a slow process. You can create the date_range and then explode it to get what you want. Moving 'Participant #' to the index makes sure it's repeated for all rows that are exploded.

```<code>df = (df.set_index('Participant #')
        .apply(lambda x: pd.date_range(x.start_date, x.end_date), axis=1)  # :( slow
        .rename('Range')
        .explode()
        .reset_index())
</code>```

```<code>   Participant #      Range
0              1 2019-04-23
1              1 2019-04-24
2              1 2019-04-25
</code>```

If you can't use explode another option is to create a separate DataFrame for each row and then concat them all together.

```<code>pd.concat([pd.DataFrame({'Participant #': par, 'Range': pd.date_range(start, end)})
           for par,start,end in zip(df['Participant #'], df['start_date'], df['end_date'])],
          ignore_index=True)
</code>```

Body:
I have a dataset which has a list of subjects, a start date, and an end date. I'm trying to do a loop so that for each subject I have a list of dates between the start date and end date. I've tried so many ways to do this based on previous posts but still having issues.

an example of the dataframe:

Participant #    Start_Date    End_Date
    1             23-04-19     25-04-19

An example of the output I want:

Participant #      Range
      1           23-04-19
      1           24-04-19
      1           25-04-19

Right now my code looks like this:

subjs_490 = tracksheet_490['Participant #']
for subj_490 in subjs_490:
  temp_a = tracksheet_490[tracksheet_490['Participant #'].isin([subj_490])]
  start = temp_a['Start_Date']
  end = temp_a['End_Date'
  start_dates = pd.to_datetime(pd.Series(start), format = '%d-%m-%y')
  end_dates = pd.to_datetime(pd.Series(end), format = '%d-%m-%y')
  date_range = pd.date_range(start_dates, end_dates).tolist()

With this method I'm getting the following error:

Cannot convert input [1   2016-05-03 Name: Start_Date, dtype: datetime64[ns]] of type  to Timestamp

Body:
Expanding ranges tends to be a slow process. You can create the date_range and then explode it to get what you want. Moving 'Participant #' to the index makes sure it's repeated for all rows that are exploded.

df = (df.set_index('Participant #')
        .apply(lambda x: pd.date_range(x.start_date, x.end_date), axis=1)  # :( slow
        .rename('Range')
        .explode()
        .reset_index())

   Participant #      Range
0              1 2019-04-23
1              1 2019-04-24
2              1 2019-04-25

If you can't use explode another option is to create a separate DataFrame for each row and then concat them all together.

pd.concat([pd.DataFrame({'Participant #': par, 'Range': pd.date_range(start, end)})
           for par,start,end in zip(df['Participant #'], df['start_date'], df['end_date'])],
          ignore_index=True)


答:
Try replacing your = signs with ==

```<code>var query1 = from r in dt.Test
                            where r.ID == 92
                            && r.Status == "I"
                            select r.ID && r.Status == "I"
</code>```

Remember that = in C# is the assignment operator, and == is the equality operator. As someone who regularly flips between C# and VB.NET, I often come unstuck here!

Body:
Try replacing your = signs with ==

var query1 = from r in dt.Test
                            where r.ID == 92
                            && r.Status == "I"
                            select r.ID && r.Status == "I"

Remember that = in C# is the assignment operator, and == is the equality operator. As someone who regularly flips between C# and VB.NET, I often come unstuck here!


问:
Should Switch.System.Net.DontEnableSchSendAuxRecord have any effect in .NET Core 3.1?
I am migrating a .NET 4.6 application to .NET Core 3.1.
The application makes a TLS 1.0 connection to a legacy device that is not going to receive any updates (it doesn't support TLS 1.1 or TLS 1.2)

The issue that I'm facing is related to a mitigation introduced in https://support.microsoft.com/en-ca/help/3155464/ms16-065-description-of-the-tls-ssl-protocol-information-disclosure-vu

The workaround that I had in .NET 4.6 was to set the AppContext switch to true:

AppContext.SetSwitch("Switch.System.Net.DontEnableSchSendAuxRecord" , true);
```

This switch does not seem to be doing anything in .NET Core 3.1.The communication to the device breaks as it does not know how to handle the mitigation (Mitigation is to split the first application data to 1 byte then send the remaining data).

Would it be possible to disable the mitigation in .NET Core 3.1?

答:
AppContext.SetSwitch("Switch.System.Net.DontEnableSchSendAuxRecord" , true);
```

is not supported in .NET Core (currently 3.1) According to https://github.com/dotnet/runtime/issues/31660#issuecomment-581520442

From the link:

There is not. In general, .NET Core doesn't have those AppContext or registry key switches to temporarily turn off security fixes (such as SCH_SEND_AUX_RECORD) that .NET Framework did.

Body:
I am migrating a .NET 4.6 application to .NET Core 3.1.
The application makes a TLS 1.0 connection to a legacy device that is not going to receive any updates (it doesn't support TLS 1.1 or TLS 1.2)

The issue that I'm facing is related to a mitigation introduced in https://support.microsoft.com/en-ca/help/3155464/ms16-065-description-of-the-tls-ssl-protocol-information-disclosure-vu

The workaround that I had in .NET 4.6 was to set the AppContext switch to true:

AppContext.SetSwitch("Switch.System.Net.DontEnableSchSendAuxRecord" , true);

This switch does not seem to be doing anything in .NET Core 3.1.The communication to the device breaks as it does not know how to handle the mitigation (Mitigation is to split the first application data to 1 byte then send the remaining data).

Would it be possible to disable the mitigation in .NET Core 3.1?

Body:
AppContext.SetSwitch("Switch.System.Net.DontEnableSchSendAuxRecord" , true);

is not supported in .NET Core (currently 3.1) According to https://github.com/dotnet/runtime/issues/31660#issuecomment-581520442

From the link:

There is not. In general, .NET Core doesn't have those AppContext or registry key switches to temporarily turn off security fixes (such as SCH_SEND_AUX_RECORD) that .NET Framework did.


问:
How to apply like, to search for email addresses, in a URN filter?
I need to search e-mail address from sender with asterisk.

e.g.  Joseph.The.First@hismail.com   ->  filter The@hismail.com

I have been inspired with code found on Microsoft or StackOverflow.

```<code>strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%sketch%'"
</code>```

This works for E-mails where subject contains sketch.

I modified URN schema to urn:schemas:httpmail:sentitems

```<code>strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:from LIKE" & " = *The*"
</code>```

Nothing found in current mailbox folder.

答:
It is an invalid query: you are missing single quotes around the value and you are also using LIKE and = at the same time. Try

```<code>@SQL="urn:schemas:httpmail:from" LIKE '%The*'
</code>```

Body:
I need to search e-mail address from sender with asterisk.

e.g.  Joseph.The.First@hismail.com   ->  filter The@hismail.com

I have been inspired with code found on Microsoft or StackOverflow.

strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%sketch%'"

This works for E-mails where subject contains sketch.

I modified URN schema to urn:schemas:httpmail:sentitems

strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:from LIKE" & " = *The*"

Nothing found in current mailbox folder.

Body:
It is an invalid query: you are missing single quotes around the value and you are also using LIKE and = at the same time. Try

@SQL="urn:schemas:httpmail:from" LIKE '%The*'


问:
Bash Scripting - Exiting While Loop When User Input = "done"
How do you exit a while loop in bash when user input detects "done"?

The objective is to have users input restaurant names and when they type done, the while loop escapes and and it randomly spits out a random restaurant within the array? As of right now, it only escapes when CTRL + D but this also closes the terminal

P.S: I've only been playing with bash for about 2 hours!

```<code>echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  rest_array=("${rest_array[@]}" $restaurants)
done

echo Eat at ${rest_array[$rand]}
</code>```

答:
Use break to exit the loop in bash

```<code>echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  if [[ "$restaurants" == "done" ]]; then
     break
  fi
  rest_array+=("$restaurants")
done

echo Eat at ${rest_array[$rand]}
</code>```

Body:
How do you exit a while loop in bash when user input detects "done"?

The objective is to have users input restaurant names and when they type done, the while loop escapes and and it randomly spits out a random restaurant within the array? As of right now, it only escapes when CTRL + D but this also closes the terminal

P.S: I've only been playing with bash for about 2 hours!

echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  rest_array=("${rest_array[@]}" $restaurants)
done

echo Eat at ${rest_array[$rand]}

Body:
Use break to exit the loop in bash

echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  if [[ "$restaurants" == "done" ]]; then
     break
  fi
  rest_array+=("$restaurants")
done

echo Eat at ${rest_array[$rand]}


问:
React & Jest: How to write a test for a component that depends on external function

The component in picture 1 has a function that needs a third parameter so that the component can work properly and display data in the UI, I wrote unit test for the paginate function. However, test success while paginate function is missing the third parameter when it's called
How do I write a test to alert me whenever I modify the paginate.js itself and the component breaks?

paginate.js:

```<code>export const paginate = (posts, currentPage, numberPerPage) => {
 const firstIndex = numberPerPage * currentPage;
 const lastIndex = firstIndex + numberPerPage;
 const currentPosts = posts.slice(firstIndex, lastIndex);
 return currentPosts;
};

export const getPages = (posts, numberPerPage) => {
 const numberOfPages = Math.ceil(posts.length / numberPerPage);
 let pages = [];
 for (let i = 0; i < numberOfPages; i++) {
   pages.push(i);
 }
 return pages;
};
</code>```

test for paginate.js:

```<code>import { paginate, getPages } from "../utils/paginate";

describe("paginate function", () => {
  it("do pagination", () => {
    const posts = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15"
    ];
    const expectedRes1 = ["1", "2", "3", "4", "5", "6"];
    const expectedRes2 = ["7", "8", "9", "10", "11", "12"];
    const expectedRes3 = ["13", "14", "15"];

    expect(paginate(posts, 0, 6)).toEqual(expectedRes1);
    expect(paginate(posts, 1, 6)).toEqual(expectedRes2);
    expect(paginate(posts, 2, 6)).toEqual(expectedRes3);

    expect(getPages(posts, 6)).toEqual([0, 1, 2]);
  });
});
</code>```

BlogContainer.js:

```<code>import React, { Component } from "react";
import BlogPost from "./BlogPost";
import CardColumns from "react-bootstrap/CardColumns";
import { paginate } from "../../utils/paginate";

export default class BlogContainer extends Component {
  render() {
    const currentPosts = paginate(this.props.posts, this.props.currentPage);
    return (
      <CardColumns>
        {currentPosts.map(post => {
          return (
            <BlogPost
              key={post.id}
              title={post.title}
              body={post.body}
              picture="image.jpg"
            ></BlogPost>
          );
        })}
      </CardColumns>
    );
  }
}
</code>```

答:
If you don't provide an argument, it will default to undefined.

To fix this, you can add a check at the top.

export const paginate = (posts, currentPage, numberPerPage) => {
  if (!posts || !currentPage || !numberPerPage) {
    // Return your error
  }
  ...
}
```

The reason it keeps working is because when numberPerPage is undefined.

const firstIndex = undefined * currentPage; results in NaN

const lastIndex = NaN + numberPerPage; results in NaN

const currentPosts = posts.slice(NaN, NaN); results in []

return currentPosts;

Body:
The component in picture 1 has a function that needs a third parameter so that the component can work properly and display data in the UI, I wrote unit test for the paginate function. However, test success while paginate function is missing the third parameter when it's called
How do I write a test to alert me whenever I modify the paginate.js itself and the component breaks?

paginate.js:

export const paginate = (posts, currentPage, numberPerPage) => {
 const firstIndex = numberPerPage * currentPage;
 const lastIndex = firstIndex + numberPerPage;
 const currentPosts = posts.slice(firstIndex, lastIndex);
 return currentPosts;
};

export const getPages = (posts, numberPerPage) => {
 const numberOfPages = Math.ceil(posts.length / numberPerPage);
 let pages = [];
 for (let i = 0; i < numberOfPages; i++) {
   pages.push(i);
 }
 return pages;
};

test for paginate.js:

import { paginate, getPages } from "../utils/paginate";

describe("paginate function", () => {
  it("do pagination", () => {
    const posts = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15"
    ];
    const expectedRes1 = ["1", "2", "3", "4", "5", "6"];
    const expectedRes2 = ["7", "8", "9", "10", "11", "12"];
    const expectedRes3 = ["13", "14", "15"];

    expect(paginate(posts, 0, 6)).toEqual(expectedRes1);
    expect(paginate(posts, 1, 6)).toEqual(expectedRes2);
    expect(paginate(posts, 2, 6)).toEqual(expectedRes3);

    expect(getPages(posts, 6)).toEqual([0, 1, 2]);
  });
});

BlogContainer.js:

import React, { Component } from "react";
import BlogPost from "./BlogPost";
import CardColumns from "react-bootstrap/CardColumns";
import { paginate } from "../../utils/paginate";

export default class BlogContainer extends Component {
  render() {
    const currentPosts = paginate(this.props.posts, this.props.currentPage);
    return (
      <CardColumns>
        {currentPosts.map(post => {
          return (
            <BlogPost
              key={post.id}
              title={post.title}
              body={post.body}
              picture="image.jpg"
            ></BlogPost>
          );
        })}
      </CardColumns>
    );
  }
}

Body:
If you don't provide an argument, it will default to undefined.

To fix this, you can add a check at the top.

export const paginate = (posts, currentPage, numberPerPage) => {
  if (!posts || !currentPage || !numberPerPage) {
    // Return your error
  }
  ...
}

The reason it keeps working is because when numberPerPage is undefined.

const firstIndex = undefined * currentPage; results in NaN

const lastIndex = NaN + numberPerPage; results in NaN

const currentPosts = posts.slice(NaN, NaN); results in []

return currentPosts;


问:
Textview moving higher than expected on keyboardWillShowNotification for Iphone X
on a function I have titled handleKeyboardWillShow, my input textfield is moving higher than expected. It is my intention for the textfield to be pinned to the top of the keyboard view. I have also added the code to the creation of the text field that seems to be causing the issue.

Creation of the textField variable

```<code>  lazy var inputTextField: UITextField = {
    let tf = UITextField()
    tf.placeholder = "Enter message..."
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.delegate = self
    return tf
}()
</code>```

My view did load function

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
    collectionView.alwaysBounceVertical = true
    collectionView.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellId)
    collectionView.backgroundColor = .white
    collectionView.keyboardDismissMode = .interactive
    becomeFirstResponder()
    setUpInputComponents()
    setUpKeyboardObserver()

}
</code>```

View will disappear is where I remove the observers

```<code> override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    //MARK: IMPORTANT FOR SHOWING AND HIDING KEYBOARD TO AVOID MEMORY LEAKS
    NotificationCenter.default.removeObserver(self)
}

func setUpKeyboardObserver(){
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func handleKeyboardWillShow(notification:NSNotification){
    let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
            let keyboardDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
    let safeLayoutGuideBot = UIApplication.shared.keyWindow?.safeAreaInsets.bottom
    let height =  (keyboardFrame?.height)! - safeLayoutGuideBot!
    containerViewBottomAnchor?.constant = -height
    UIView.animate(withDuration: keyboardDuration!, animations: {
        self.view.layoutIfNeeded()
    })
}

@objc func handleKeyboardWillHide(notification:NSNotification){
    let keyboardDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
    containerViewBottomAnchor?.constant = 0
    UIView.animate(withDuration: keyboardDuration!, animations: {
        self.view.layoutIfNeeded()
    })
}
</code>```

This is where the layout for the textView in question and container view are set up.

```<code>var containerViewBottomAnchor: NSLayoutConstraint?

func setUpInputComponents(){
    let containerView = UIView()
    containerView.translatesAutoresizingMaskIntoConstraints = false
    containerView.backgroundColor = .white
    view.addSubview(containerView)

    containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    containerViewBottomAnchor =  containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    containerViewBottomAnchor?.isActive = true
    containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true

    containerView.addSubview(sendButton)
    sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
    sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
    sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

    containerView.addSubview(inputTextField)
    inputTextField.leftAnchor.constraint(equalToSystemSpacingAfter: containerView.leftAnchor, multiplier: 8).isActive = true
    inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true
    inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

    containerView.addSubview(seperatorLineView)
    seperatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
    seperatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
    seperatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
    seperatorLineView.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
}
</code>```

答:
Perhaps this fix was a hack, but I resolved it by implementing the following

```<code>        containerViewBottomAnchor?.constant -= (keyboardFrame?.height)! - 100
</code>```

Statically subtracting the value of 100 from the keyboard frame height.

Body:
on a function I have titled handleKeyboardWillShow, my input textfield is moving higher than expected. It is my intention for the textfield to be pinned to the top of the keyboard view. I have also added the code to the creation of the text field that seems to be causing the issue.

Creation of the textField variable

  lazy var inputTextField: UITextField = {
    let tf = UITextField()
    tf.placeholder = "Enter message..."
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.delegate = self
    return tf
}()

My view did load function

    override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
    collectionView.alwaysBounceVertical = true
    collectionView.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellId)
    collectionView.backgroundColor = .white
    collectionView.keyboardDismissMode = .interactive
    becomeFirstResponder()
    setUpInputComponents()
    setUpKeyboardObserver()

}

View will disappear is where I remove the observers

 override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    //MARK: IMPORTANT FOR SHOWING AND HIDING KEYBOARD TO AVOID MEMORY LEAKS
    NotificationCenter.default.removeObserver(self)
}

func setUpKeyboardObserver(){
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func handleKeyboardWillShow(notification:NSNotification){
    let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
            let keyboardDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
    let safeLayoutGuideBot = UIApplication.shared.keyWindow?.safeAreaInsets.bottom
    let height =  (keyboardFrame?.height)! - safeLayoutGuideBot!
    containerViewBottomAnchor?.constant = -height
    UIView.animate(withDuration: keyboardDuration!, animations: {
        self.view.layoutIfNeeded()
    })
}

@objc func handleKeyboardWillHide(notification:NSNotification){
    let keyboardDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
    containerViewBottomAnchor?.constant = 0
    UIView.animate(withDuration: keyboardDuration!, animations: {
        self.view.layoutIfNeeded()
    })
}

This is where the layout for the textView in question and container view are set up.

var containerViewBottomAnchor: NSLayoutConstraint?

func setUpInputComponents(){
    let containerView = UIView()
    containerView.translatesAutoresizingMaskIntoConstraints = false
    containerView.backgroundColor = .white
    view.addSubview(containerView)

    containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    containerViewBottomAnchor =  containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    containerViewBottomAnchor?.isActive = true
    containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true

    containerView.addSubview(sendButton)
    sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
    sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
    sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

    containerView.addSubview(inputTextField)
    inputTextField.leftAnchor.constraint(equalToSystemSpacingAfter: containerView.leftAnchor, multiplier: 8).isActive = true
    inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true
    inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

    containerView.addSubview(seperatorLineView)
    seperatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
    seperatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
    seperatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
    seperatorLineView.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
}

Body:
Perhaps this fix was a hack, but I resolved it by implementing the following

        containerViewBottomAnchor?.constant -= (keyboardFrame?.height)! - 100

Statically subtracting the value of 100 from the keyboard frame height.


问:
How to mount a configMap as a volume mount in a Stateful Set
I don't see an option to mount a configMap as volume in the statefulset , as per https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#statefulset-v1-apps only PVC can be associated with "StatefulSet" . But PVC does not have option for configMaps.</p>

答:
Here is a minimal example:

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: example
spec:
  selector:
    matchLabels:
      app: example
  serviceName: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
        - name: example
          image: nginx:stable-alpine
          volumeMounts:
            - mountPath: /config
              name: example-config
      volumes:
        - name: example-config
          configMap:
            name: example-configmap
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-configmap
data:
  a: "1"
  b: "2"
</code>```

In the container, you can find the files a and b under /config, with the contents 1 and 2, respectively.

Some explanation:
You do not need a PVC to mount the configmap as a volume to your pods. PersistentVolumeClaims are persistent drives, which you can read from/write to. An example for their usage is a database, such as Postgres.

ConfigMaps on the other hand are read-only key-value structures that are stored inside Kubernetes (in its etcd store), which are to store the configuration for your application. Their values can be mounted as environment variables or as files, either individually or altogether.

Body:
Here is a minimal example:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: example
spec:
  selector:
    matchLabels:
      app: example
  serviceName: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
        - name: example
          image: nginx:stable-alpine
          volumeMounts:
            - mountPath: /config
              name: example-config
      volumes:
        - name: example-config
          configMap:
            name: example-configmap
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-configmap
data:
  a: "1"
  b: "2"

In the container, you can find the files a and b under /config, with the contents 1 and 2, respectively.

Some explanation:
You do not need a PVC to mount the configmap as a volume to your pods. PersistentVolumeClaims are persistent drives, which you can read from/write to. An example for their usage is a database, such as Postgres.

ConfigMaps on the other hand are read-only key-value structures that are stored inside Kubernetes (in its etcd store), which are to store the configuration for your application. Their values can be mounted as environment variables or as files, either individually or altogether.


问:
Python 3, getting file not found error on absolute path
I'm trying to write a binary file i'm downloading from The Movie Database. I can successfully save the file if it's on the same folder the .py file is, but cannot save it on a location outside it even after the containing directory is created by the script and using absolute path:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/home/gabriel/Desktop/movies/w185/tt2024544.jpeg'
</code>```

Pice of code:

```<code>filepath    =   os.path.join(webDir,size,imdbid + '.' + filetype);
f           =   open(filepath, "wb");
</code>```

I'm puzzled. Any tips?

Thanks!

答:
I had the same issue and it turned out that a directory in my absolute path was not existing. One can easily check with:

```<code>import os
path = os.path.split(filepath)[0]
print('check for path', os.path.exists(path))
</code>```

Body:
I'm trying to write a binary file i'm downloading from The Movie Database. I can successfully save the file if it's on the same folder the .py file is, but cannot save it on a location outside it even after the containing directory is created by the script and using absolute path:

FileNotFoundError: [Errno 2] No such file or directory: '/home/gabriel/Desktop/movies/w185/tt2024544.jpeg'

Pice of code:

filepath    =   os.path.join(webDir,size,imdbid + '.' + filetype);
f           =   open(filepath, "wb");

I'm puzzled. Any tips?

Thanks!

Body:
I had the same issue and it turned out that a directory in my absolute path was not existing. One can easily check with:

import os
path = os.path.split(filepath)[0]
print('check for path', os.path.exists(path))


问:
Screening for duplicates in a tuple - Python
I am trying to create a function, non_duplicates(), that screens for duplicates for a given tuple x, and returns False if there is a duplicate, or returns True if there isn't any.

I am doing this by a for loop nested within another to iterate over the items twice to compare all the items with each other. I added a conditional that checks if the two items are equal, while their indices are not.

The problem is that the code is giving an equal index for different items for some reason, where I made sure that the index is linked with the iteration.

The answer for non_duplicates(((0,0),(0,0))) is the same as non_duplicates(((0,0),(5,5))), both are giving True while it should not for the former.

When I checked ((0,0),(0,0)), the indices are "0,0    0,0    0,0    0,0", while for ((0,0),(5,5)), the indices are "0,0    0,1    1,0    1,1".

That is why the condition are not being met.

def non_duplicates(x):
    y = 0
    for i, j in x:
        x1 = (i,j)
        for k, l in x:
            x2 = (k,l)
            if (x1 == x2 and x.index(x1) != x.index(x2)):
                y = y + 1
    y = y/len(x)
    if y == 0:
        answer = True
    if y > 0:
        answer = False
    return answer
```

答:
If I understand the question correctly, you can try:

def non_duplicates(x):
    return len(set(x)) == len(x)
```