问:
Parsing Input File into 2D Array Yielding Random Values
For a project i'm doing, I'm required to load an input file into a 2 dimensional array for subsequent processing. The file is an "image" of 0's and 1's and looks like this:

```<code># p01image1.txt -- Sample Image #1

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
</code>```

However, when I try to put the input into the 2D Array, it ends up putting some 0's and then arbitrary numbers in the array instead like this:

```<code>0 0 0 0 984466800 32767 -885601504 32728 -885601504 32728
984466800 32767 0 0 -885602528 32728 984466728 32767 -885398176 32728
-885604352 32728 -885510269 32728 -890784124 32728 110527148 0 -885443879 32728
110527148 0 157536133 0 -885510071 32728 -885443893 32728 -890789612 32728
0 0 -885607168 32728 1 0 -967018754 23765 -885399056 32728
-1 0 -885399056 32728 -885509698 32728 -1 0 -889561112 32728
-964725194 23765 -885585425 32728 0 0 0 0 0 0
0 0 0 0 0 0 -890828992 32728 -885397576 32728
-885399296 32728 984467457 32767 984466984 32767 984466992 32767 0 0
0 0 0 0 985621032 32767 0 32 0 0
</code>```

I've never had this issue before with putting values into an array from an input file and wasn't sure if someone could give any insight to what I might be doing wrong. I'm still relatively new to c++ so I apologize in advance.

My function for opening the input file is:

```<code>// ****************************************
// Program Title: Project 1
// Project File: Project01.cpp
// Name: Noah Sickels
// Course Section: CPE-212-02
// Due Date: 2/14/22
// Program Description: Image Manipulation Program
// ****************************************
#include <bits/stdc++.h>

void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS])
// LoadImage() must open the image file for input and load the image into a
// two-dimensional array for subsequent processing.  If the file does not open,
// then print error message and exit the program by invoking the function exit(1)
//
// First parameter is a string that will hold the name of the input file
// Second parameter is a two-dimensional array of integers representing the image
//
// Note: Correct operation of this function is critical!!  If one cannot
//       correctly load images into the array from the file, then one
//       cannot test the image processing operations.
//
{
    ifstream inFile;
    inFile.open(imagefile);

    for(int i = 0; i < MAXROWS; i++) {
        for(int j = 0; j < MAXCOLS; j++) {
            if(! (inFile >> image[i][j])){
                cout << "Error reading from file, terminating program..." << endl;
                exit(1);
            }
        }
    }
    inFile.close();

    for (int i = 0; i < MAXROWS; i++) {
        for (int j = 0; j < MAXCOLS; j++) {
            cout << image[i][j] << " "; //space between columns
            }
        cout << endl; //newlines for rows
    }
}  // End LoadImage()
/***********************************************************************/
void FlipHorizontal(int image[MAXROWS][MAXCOLS])
// FlipHorizontal() - must flip the image horizontally.  For example,
// column zero exchanged with column N-1, column one exchanged with column N-2, etc.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp;
    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS / 2; j++){
           temp = image[i][j];
           image[i][j] = image[i][MAXCOLS - j - 1];
           image[i][MAXCOLS - j - 1] = temp;
        }
    }
}  // End FlipHorizontal()
/***********************************************************************/
void FlipVertical(int image[MAXROWS][MAXCOLS])
// FlipVertical() - must flip the image Vertically.  For example,
// row zero exchanged with row N-1, row one exchanged with row N-2, etc.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp;
    for(int i = 0; i < MAXROWS / 2; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp = image[i][j];
            image[i][j] = image[MAXROWS - 1 - i][j];
            image[MAXROWS - i - 1][j] = temp;
        }
    }
}  // End FlipVertical()
/***********************************************************************/
void Transpose(int image[MAXROWS][MAXCOLS])
// Transpose() - must flip the image across the primary diagonal row = column as
// with a matrix transpose
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];
    for(int i = 0; i < MAXROWS; i++) {
        for(int j = 0; j < MAXCOLS; j++) {
            temp[j][i] = image[i][j];
        }
    }
}  // End Transpose()
/***********************************************************************/
void RotateCW(int image[MAXROWS][MAXCOLS])
// RotateCW() - must rotate the image 90 degrees clockwise.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp[i][j] = image[MAXROWS - j - 1][i];
        }
    }

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            image[i][j] = temp[i][j];
        }
    }
}  // End RotateCW()
/***********************************************************************/
void RotateCCW(int image[MAXROWS][MAXCOLS])
// RotateCCW() - must rotate the image 90 degrees counter clockwise.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp[i][j] = image[MAXROWS - j - 1][MAXROWS - i - 1];
        }
    }

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            image[i][j] = temp[i][j];
        }
    }
}  // End RotateCCW()
/***********************************************************************/
</code>```

The main.cpp file that we are required to use is here:

```<code>//
// main.cpp --  Project01, CPE212 Fall 2010 -- C++ Review Project
//
// Driver program for Image Processing Program which is used to test each
// image processing operation.
//
// DO NOT SUBMIT OR SUBMIT THIS FILE
//

// List of allowed include files appear below
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;                    // Global using declaration

// Global Constants -- you may use these global constants in your code
const int MAXROWS = 10;                 // Maximum number of rows in image
const int MAXCOLS = 10;                 // Maximum number of columns in image

// Function Prototypes for functions included at the end of main.cpp
void Print(const int image[MAXROWS][MAXCOLS]);
void Bars();

// Function Prototypes for the functions you must implement in project01.cpp
void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS]);
void FlipHorizontal(int image[MAXROWS][MAXCOLS]);
void FlipVertical(int image[MAXROWS][MAXCOLS]);
void RotateCW(int image[MAXROWS][MAXCOLS]);
void RotateCCW(int image[MAXROWS][MAXCOLS]);
void Transpose(int image[MAXROWS][MAXCOLS]);

// Start of main() function

int main (int argc, char * const argv[])      // Command-line arguments (more on this later)
{
  ifstream inputs;                // Input file stream variable for test file
  char op, ch;                    // Hold operation and optional char input from test file
  string  comment;                            // Holds comment string input from test file
  int image[MAXROWS][MAXCOLS];                // Array of integers representing image
  string imagefile;                           // Name of image file

  // Output usage message if test input file name is not provided
  if (argc != 2)
  {
    cout << "Usage:\n  project01  <inputfile>\n";
    return 1;
  }

  // Attempt to open test input file -- terminate if file does not open
  inputs.open(argv[1]);
  if (!inputs)
  {
    cout << "Error - unable to open input file" << endl;
    return 1;
  }

  // Process comment line from input file
  getline(inputs, comment);                    // Input file header comment
  cout << endl << comment << endl << endl;     // Output file header comment

  // Below is primary loop that processes each operation appearing within the test file.
  // Starts with an initial priming read of first operation

  inputs >> op;         // Attempt to input first test operation from file

  while (inputs)                // While Not-EOF
  {
    switch (op)                 // Process operation input from test file
    {
      case '#':   // Test file comment
                      getline(inputs, comment);      // Input and echo the comment appearing in the test file
                      cout << '#' << comment << endl;
                      break;

      case 'p':   // Print Grid
                      Print(image);                  // Function definition appears at the end of this file
                      break;

      case 'b':   // Print Bars
                      Bars();                        // Function definition appears at the end of this file
                      break;

      case 'i':   // Load Image
                      inputs >> imagefile;           // Input name of imagefile from test file
                      LoadImage(imagefile, image);   // Implement this function in project01.cpp
                      break;

          case '+':   // Rotate Image Clockwise 90 Degrees
                      RotateCW(image);               // Implement this function in project01.cpp
                      break;

          case '-':   // Rotate Image Counterclockwise 90 Degrees
                      RotateCCW(image);              // Implement this function in project01.cpp
                      break;

      case 'v':   // Flip Image Vertical
                      FlipVertical(image);           // Implement this function in project01.cpp
                      break;

      case 'h':   // Flip Image Horizontal
                      FlipHorizontal(image);         // Implement this function in project01.cpp
                      break;

      case 't':   // Transpose Image Across Major Diagonal
                      Transpose(image);              // Implement this function in project01.cpp
                      break;

      default:    // Error
                      cout << "Error - unrecognized operation '" << op << "'" << endl;
                      cout << "Terminating now..." << endl;
                      return 1;
                      break;
    }
    cout << endl;

    inputs >> op;                                // Attempt to input next command
  }

  return 0;
}

/************** Implementation of Print() and Bars() functions ********************/

// DO NOT MODIFY THIS CODE

void Print(const int image[MAXROWS][MAXCOLS])
// Print() -- outputs image row-by-row in desired format substituting
// * for 1 and - for 0.
{
    for(int r=0; r < MAXROWS; r++)               // Loop to visit each row in image
    {
        for(int c=0; c < MAXCOLS; c++)       // Loop to output every element on current row
        {
            if (image[r][c] == 1)        // Output appropriate symbol
            {
                cout << '*';
            }
            else if (image[r][c] == 0)
            {
                cout << '-';
            }
            else
            {
                cout << 'X';
            }
        }
        cout << endl;
    }

}  // End Print()

void Bars()
// Bars() -- prints two horizontal rows of bars
{
    cout << "#################################################################" << endl;
    cout << "#################################################################" << endl;
}  // End Bars()

/************** DO NOT DELETE *************/
// The preprocessor directive below will import the function definitions
// from the file project01.cpp and place them at the end of this file creating an
// Expanded Source File which is forwarded to the compiler for compilation.

#include "project01.cpp"

/**************  End of main.cpp  ***************/

</code>```

答: I figured out the problem, it was my own dumb mistake. The issue was the text line at the beginning that was causing the array to give those values. Since we are not allowed to use the limits function, so I used getline() to ignore the first line in the file and the array copied correctly.</p>

Body:
For a project i'm doing, I'm required to load an input file into a 2 dimensional array for subsequent processing. The file is an "image" of 0's and 1's and looks like this:

# p01image1.txt -- Sample Image #1

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

However, when I try to put the input into the 2D Array, it ends up putting some 0's and then arbitrary numbers in the array instead like this:

0 0 0 0 984466800 32767 -885601504 32728 -885601504 32728
984466800 32767 0 0 -885602528 32728 984466728 32767 -885398176 32728
-885604352 32728 -885510269 32728 -890784124 32728 110527148 0 -885443879 32728
110527148 0 157536133 0 -885510071 32728 -885443893 32728 -890789612 32728
0 0 -885607168 32728 1 0 -967018754 23765 -885399056 32728
-1 0 -885399056 32728 -885509698 32728 -1 0 -889561112 32728
-964725194 23765 -885585425 32728 0 0 0 0 0 0
0 0 0 0 0 0 -890828992 32728 -885397576 32728
-885399296 32728 984467457 32767 984466984 32767 984466992 32767 0 0
0 0 0 0 985621032 32767 0 32 0 0

I've never had this issue before with putting values into an array from an input file and wasn't sure if someone could give any insight to what I might be doing wrong. I'm still relatively new to c++ so I apologize in advance.

My function for opening the input file is:

// ****************************************
// Program Title: Project 1
// Project File: Project01.cpp
// Name: Noah Sickels
// Course Section: CPE-212-02
// Due Date: 2/14/22
// Program Description: Image Manipulation Program
// ****************************************
#include <bits/stdc++.h>

void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS])
// LoadImage() must open the image file for input and load the image into a
// two-dimensional array for subsequent processing.  If the file does not open,
// then print error message and exit the program by invoking the function exit(1)
//
// First parameter is a string that will hold the name of the input file
// Second parameter is a two-dimensional array of integers representing the image
//
// Note: Correct operation of this function is critical!!  If one cannot
//       correctly load images into the array from the file, then one
//       cannot test the image processing operations.
//
{
    ifstream inFile;
    inFile.open(imagefile);

    for(int i = 0; i < MAXROWS; i++) {
        for(int j = 0; j < MAXCOLS; j++) {
            if(! (inFile >> image[i][j])){
                cout << "Error reading from file, terminating program..." << endl;
                exit(1);
            }
        }
    }
    inFile.close();

    for (int i = 0; i < MAXROWS; i++) {
        for (int j = 0; j < MAXCOLS; j++) {
            cout << image[i][j] << " "; //space between columns
            }
        cout << endl; //newlines for rows
    }
}  // End LoadImage()
/***********************************************************************/
void FlipHorizontal(int image[MAXROWS][MAXCOLS])
// FlipHorizontal() - must flip the image horizontally.  For example,
// column zero exchanged with column N-1, column one exchanged with column N-2, etc.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp;
    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS / 2; j++){
           temp = image[i][j];
           image[i][j] = image[i][MAXCOLS - j - 1];
           image[i][MAXCOLS - j - 1] = temp;
        }
    }
}  // End FlipHorizontal()
/***********************************************************************/
void FlipVertical(int image[MAXROWS][MAXCOLS])
// FlipVertical() - must flip the image Vertically.  For example,
// row zero exchanged with row N-1, row one exchanged with row N-2, etc.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp;
    for(int i = 0; i < MAXROWS / 2; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp = image[i][j];
            image[i][j] = image[MAXROWS - 1 - i][j];
            image[MAXROWS - i - 1][j] = temp;
        }
    }
}  // End FlipVertical()
/***********************************************************************/
void Transpose(int image[MAXROWS][MAXCOLS])
// Transpose() - must flip the image across the primary diagonal row = column as
// with a matrix transpose
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];
    for(int i = 0; i < MAXROWS; i++) {
        for(int j = 0; j < MAXCOLS; j++) {
            temp[j][i] = image[i][j];
        }
    }
}  // End Transpose()
/***********************************************************************/
void RotateCW(int image[MAXROWS][MAXCOLS])
// RotateCW() - must rotate the image 90 degrees clockwise.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp[i][j] = image[MAXROWS - j - 1][i];
        }
    }

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            image[i][j] = temp[i][j];
        }
    }
}  // End RotateCW()
/***********************************************************************/
void RotateCCW(int image[MAXROWS][MAXCOLS])
// RotateCCW() - must rotate the image 90 degrees counter clockwise.
//
// First parameter is a two-dimensional array of integers representing the image
//
{
    int temp[MAXROWS][MAXCOLS];

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            temp[i][j] = image[MAXROWS - j - 1][MAXROWS - i - 1];
        }
    }

    for(int i = 0; i < MAXROWS; i++){
        for(int j = 0; j < MAXCOLS; j++){
            image[i][j] = temp[i][j];
        }
    }
}  // End RotateCCW()
/***********************************************************************/

The main.cpp file that we are required to use is here:

//
// main.cpp --  Project01, CPE212 Fall 2010 -- C++ Review Project
//
// Driver program for Image Processing Program which is used to test each
// image processing operation.
//
// DO NOT SUBMIT OR SUBMIT THIS FILE
//

// List of allowed include files appear below
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;                    // Global using declaration

// Global Constants -- you may use these global constants in your code
const int MAXROWS = 10;                 // Maximum number of rows in image
const int MAXCOLS = 10;                 // Maximum number of columns in image

// Function Prototypes for functions included at the end of main.cpp
void Print(const int image[MAXROWS][MAXCOLS]);
void Bars();

// Function Prototypes for the functions you must implement in project01.cpp
void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS]);
void FlipHorizontal(int image[MAXROWS][MAXCOLS]);
void FlipVertical(int image[MAXROWS][MAXCOLS]);
void RotateCW(int image[MAXROWS][MAXCOLS]);
void RotateCCW(int image[MAXROWS][MAXCOLS]);
void Transpose(int image[MAXROWS][MAXCOLS]);

// Start of main() function

int main (int argc, char * const argv[])      // Command-line arguments (more on this later)
{
  ifstream inputs;                // Input file stream variable for test file
  char op, ch;                    // Hold operation and optional char input from test file
  string  comment;                            // Holds comment string input from test file
  int image[MAXROWS][MAXCOLS];                // Array of integers representing image
  string imagefile;                           // Name of image file

  // Output usage message if test input file name is not provided
  if (argc != 2)
  {
    cout << "Usage:\n  project01  <inputfile>\n";
    return 1;
  }

  // Attempt to open test input file -- terminate if file does not open
  inputs.open(argv[1]);
  if (!inputs)
  {
    cout << "Error - unable to open input file" << endl;
    return 1;
  }

  // Process comment line from input file
  getline(inputs, comment);                    // Input file header comment
  cout << endl << comment << endl << endl;     // Output file header comment

  // Below is primary loop that processes each operation appearing within the test file.
  // Starts with an initial priming read of first operation

  inputs >> op;         // Attempt to input first test operation from file

  while (inputs)                // While Not-EOF
  {
    switch (op)                 // Process operation input from test file
    {
      case '#':   // Test file comment
                      getline(inputs, comment);      // Input and echo the comment appearing in the test file
                      cout << '#' << comment << endl;
                      break;

      case 'p':   // Print Grid
                      Print(image);                  // Function definition appears at the end of this file
                      break;

      case 'b':   // Print Bars
                      Bars();                        // Function definition appears at the end of this file
                      break;

      case 'i':   // Load Image
                      inputs >> imagefile;           // Input name of imagefile from test file
                      LoadImage(imagefile, image);   // Implement this function in project01.cpp
                      break;

          case '+':   // Rotate Image Clockwise 90 Degrees
                      RotateCW(image);               // Implement this function in project01.cpp
                      break;

          case '-':   // Rotate Image Counterclockwise 90 Degrees
                      RotateCCW(image);              // Implement this function in project01.cpp
                      break;

      case 'v':   // Flip Image Vertical
                      FlipVertical(image);           // Implement this function in project01.cpp
                      break;

      case 'h':   // Flip Image Horizontal
                      FlipHorizontal(image);         // Implement this function in project01.cpp
                      break;

      case 't':   // Transpose Image Across Major Diagonal
                      Transpose(image);              // Implement this function in project01.cpp
                      break;

      default:    // Error
                      cout << "Error - unrecognized operation '" << op << "'" << endl;
                      cout << "Terminating now..." << endl;
                      return 1;
                      break;
    }
    cout << endl;

    inputs >> op;                                // Attempt to input next command
  }

  return 0;
}

/************** Implementation of Print() and Bars() functions ********************/

// DO NOT MODIFY THIS CODE

void Print(const int image[MAXROWS][MAXCOLS])
// Print() -- outputs image row-by-row in desired format substituting
// * for 1 and - for 0.
{
    for(int r=0; r < MAXROWS; r++)               // Loop to visit each row in image
    {
        for(int c=0; c < MAXCOLS; c++)       // Loop to output every element on current row
        {
            if (image[r][c] == 1)        // Output appropriate symbol
            {
                cout << '*';
            }
            else if (image[r][c] == 0)
            {
                cout << '-';
            }
            else
            {
                cout << 'X';
            }
        }
        cout << endl;
    }

}  // End Print()

void Bars()
// Bars() -- prints two horizontal rows of bars
{
    cout << "#################################################################" << endl;
    cout << "#################################################################" << endl;
}  // End Bars()

/************** DO NOT DELETE *************/
// The preprocessor directive below will import the function definitions
// from the file project01.cpp and place them at the end of this file creating an
// Expanded Source File which is forwarded to the compiler for compilation.

#include "project01.cpp"

/**************  End of main.cpp  ***************/


来源: stackexchange

问:
Is it possible to use ?? operator in this case?
Suppose situation is the following:

```<code>dynamic? _rsomeFunc() {
    final smth = someGetFunction(); //may return null
    return smth != null ? someObject.fromJson(jsonDecode(smth)) : null;
}
</code>```

is it possible to write it via => in single line function? cause this approach is seems to be not perfect one. I tried it via ?? but it didn't help. Any suggestion?

答:
Thanks for references provided by @jamesdlin. For now (2022/02/10) in Dart 2.16 there is no such opportunity;

Hope they will add it.

ContentLicense: CC BY-SA 4.0

Body:
Suppose situation is the following:

dynamic? _rsomeFunc() {
    final smth = someGetFunction(); //may return null
    return smth != null ? someObject.fromJson(jsonDecode(smth)) : null;
}

is it possible to write it via => in single line function? cause this approach is seems to be not perfect one. I tried it via ?? but it didn't help. Any suggestion?


问:
python parsing with bs4 an xml to get a list of elements
I have an xml file containing data in this form:

```<code><head xml:id="_2ebf9c0003">\n\nTECHNICAL FIELD</head>\n
<p n="0001" xml:id="_2ebf9c0004">whatever</p>
<p n="0002" xml:id="_2ebf9c0004">whatever</p>
<... other tags and data...>
<head xml:id="_2ebf9c0003">\n\nTITLE</head>\n
</code>```

I know how to get particular elements like:

```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup(PDM_description, 'lxml')
title_element = soup.title$
importing all p elements
paras = soup.findAll('p')
</code>```

The question is how can I add an OR inside the query to get a list of "p" or "head" elements? More general how to get all the elements with tags belonging to a list.

PSEUDO CODE:

```<code>paras = soup.findAll('p' OR 'head')
</code>```

答:
You are close to your goal, just add a list with tags to your find_all():

```<code>soup.find_all(['p','head'])
</code>```

Note: In new code use find_all() instead of older findAll() syntax

Body:
I have an xml file containing data in this form:

\n\nTECHNICAL FIELD\n

whatever

whatever

<... other tags and data...>
\n\nTITLE\n

I know how to get particular elements like:

from bs4 import BeautifulSoup
soup = BeautifulSoup(PDM_description, 'lxml')
title_element = soup.title$
importing all p elements
paras = soup.findAll('p')

The question is how can I add an OR inside the query to get a list of "p" or "head" elements? More general how to get all the elements with tags belonging to a list.

PSEUDO CODE:

paras = soup.findAll('p' OR 'head')

Body:
You are close to your goal, just add a list with tags to your find_all():

soup.find_all(['p','head'])

Note: In new code use find_all() instead of older findAll() syntax


答:
Find the Position of the last -1 starting at the right= and only keep up until this point:

```<code>lapply(dt$solution_resp, \(x) head(x, Position(identity, x=="-1", right=TRUE)) )
</code>```

In the circumstance where there could be rows without a -1 at all:

```<code>lapply(dt$solution_resp, \(x)
  head(x, pmin(Position(identity, x=="-1", right=TRUE), Inf, na.rm=TRUE)))

#[[1]]
#[1] "-1" "1"  "1"  "1"  "1"  "1"  "-1"
#
#[[2]]
#[1] "1"  "-1" "1"  "-1" "1"  "-1"
#
#[[3]]
#[1] "-1" "1"  "1"  "1"  "1"  "-1" "1"  "-1"
#...
</code>```

Title: In R: shorten list from behind till a certain value

Body:
Suppose i have many and larger lists than in this example.

ID <- c(2,2,2,2,5,5,5,5,9,9,9,9)
Rounds <- c(0,1,2,3,0,1,2,3,0,1,2,3)
solution <- c(as.character('[[-1,1,1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,-1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,1,-1],[1,-1,-1,-1]]') )
solution_resp <- c(as.character('[[-1,1,1,1],[1,1,-1,1]]'),as.character('[[1,-1,1,-1],[1,-1,1,1]]'),as.character('[[-1,1,1,1],[1,-1,1,-1]]'))

dt <- data.frame(ID,Rounds,solution,solution_resp)

dt$solution <- gsub('],[',',', dt$solution, fixed=TRUE)
dt$solution <- gsub('[[',''  , dt$solution, fixed=TRUE)
dt$solution <- gsub(']]',''  , dt$solution, fixed=TRUE)

dt$solution <- as.list(strsplit(dt$solution, ","))

dt$solution_resp <- gsub('],[',',', dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub('[[',''  , dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub(']]',''  , dt$solution_resp, fixed=TRUE)

dt$solution_resp <- as.list(strsplit(dt$solution_resp, ","))

Looks like this:

   ID Rounds                    solution             solution_resp
1   2      0  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
2   2      1 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
3   2      2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4   2      3  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
5   5      0 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
6   5      1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7   5      2  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
8   5      3 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
9   9      0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10  9      1  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
11  9      2 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
12  9      3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1

In the lists dt$solution_resp I would like to drop all 1 from behind until the first -1 appears (counting from right to left).

In the example this would mean shortening the lists by taking off the last element in first row (and every third row). In the second row (and every third) the list shall be shorted by two elements. The third row remains as it is because there is a -1 at the last position already.

Then, I want the dt$solution lists to have the same length.

Solution:

   ID Rounds                    solution             solution_resp
1   2      0  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
2   2      1 -1, 1, -1, -1, 1, -1         1, -1, 1, -1, 1, -1
3   2      2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4   2      3  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
5   5      0 -1, 1, -1, -1, 1, -1         1, -1, 1, -1, 1, -1
6   5      1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7   5      2  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
8   5      3 -1, 1, -1, -1, 1, -1,        1, -1, 1, -1, 1, -1
9   9      0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10  9      1  -1, 1, 1, -1, 1, -1, 1,    -1, 1, 1, 1, 1, 1, -1
11  9      2 -1, 1, -1, -1, 1, -1,        1, -1, 1, -1, 1, -1
12  9      3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1

Body:
Find the Position of the last -1 starting at the right= and only keep up until this point:

lapply(dt$solution_resp, \(x) head(x, Position(identity, x=="-1", right=TRUE)) )

In the circumstance where there could be rows without a -1 at all:

lapply(dt$solution_resp, \(x)
  head(x, pmin(Position(identity, x=="-1", right=TRUE), Inf, na.rm=TRUE)))

#[[1]]
#[1] "-1" "1"  "1"  "1"  "1"  "1"  "-1"
#
#[[2]]
#[1] "1"  "-1" "1"  "-1" "1"  "-1"
#
#[[3]]
#[1] "-1" "1"  "1"  "1"  "1"  "-1" "1"  "-1"
#...


问:
SQL User Function (and performance): combining SELECT and IF in multiple RETURN statements
The reason for my question is in part due to performance concerns. See note at end.

Is it possible to do something like this:

create function fn_x()
returns table
as
begin
if @Something1
    return select distinct y.val, x.* from x join y on x.a = y.a where y.val = @val
else if @Something2
    return select distinct z.val, x.* from x join z on x.a = z.a where z.val = @val
else
    return select @val val, x.* from x
end
```

<p>The alternative would be something like this:</p>

<pre class="lang-sql prettyprint-override"><code>return
            select distinct y.val, x.* from x join y on x.a = y.a where @Something1 and y.val = @val
union all   select distinct z.val, x.* from x join z on x.a = z.a where @Something2 and z.val = @val
union all   select '' val, x.* from x where not @Something1 and not @Something2
</code>```

or like this:

return
    select  @val val, x.*
    from    x
    where   (not @Something1 and not @Something2)
    or      (@Something1 and exists(select * from y where x.a = y.a and y.val = @val))
    or      (@Something2 and exists(select * from z where x.a = z.a and z.val = @val))
```

Assume "x" is a very large table used frequently. My concern is that the alternatives will slow my queries down.

(I'm using SQL Server 2008 R2)

EDIT: Why do I need a single function? The filter is based on external settings (perhaps not ideal but required). In short, the function is there to replace the table. Instead of using select * from x I must now use select * from fn_x(). Tables "y" and "z" represent permission tables, "@val" represents a user ID, and "@Something1" and "@Something2" represent external settings.

答:
You have to use the alternatives because of syntax: you can have one return only with an in-line table valued function.

Personally, I'd say different JOINs means separate functions...

ContentLicense: CC BY-SA 3.0

Body:
The reason for my question is in part due to performance concerns. See note at end.

Is it possible to do something like this:

create function fn_x()
returns table
as
begin
if @Something1
    return select distinct y.val, x.* from x join y on x.a = y.a where y.val = @val
else if @Something2
    return select distinct z.val, x.* from x join z on x.a = z.a where z.val = @val
else
    return select @val val, x.* from x
end

The alternative would be something like this:

return
            select distinct y.val, x.* from x join y on x.a = y.a where @Something1 and y.val = @val
union all   select distinct z.val, x.* from x join z on x.a = z.a where @Something2 and z.val = @val
union all   select '' val, x.* from x where not @Something1 and not @Something2

or like this:

return
    select  @val val, x.*
    from    x
    where   (not @Something1 and not @Something2)
    or      (@Something1 and exists(select * from y where x.a = y.a and y.val = @val))
    or      (@Something2 and exists(select * from z where x.a = z.a and z.val = @val))

Assume "x" is a very large table used frequently. My concern is that the alternatives will slow my queries down.

(I'm using SQL Server 2008 R2)

EDIT: Why do I need a single function? The filter is based on external settings (perhaps not ideal but required). In short, the function is there to replace the table. Instead of using select * from x I must now use select * from fn_x(). Tables "y" and "z" represent permission tables, "@val" represents a user ID, and "@Something1" and "@Something2" represent external settings.


问:
SwiftUI: How to disable scrolling in List without disabling content
I have a list in SwiftUI declared as follows:

```<code>List {
  Text("Test")
  Text("Test)
  ...
  Toggle(...)
}
</code>```

I'd like to make this list unscrollable without using .disabled(true), as I'd like the toggle to be interactable. How can I accomplish this?

答:
Put this below the list:</p>
```<code>                .onAppear {

                    UITableView.appearance().isScrollEnabled = false

                }

</code>```

Body:
I have a list in SwiftUI declared as follows:

List {
  Text("Test")
  Text("Test)
  ...
  Toggle(...)
}

I'd like to make this list unscrollable without using .disabled(true), as I'd like the toggle to be interactable. How can I accomplish this?

Body:
Put this below the list:

                .onAppear {

                    UITableView.appearance().isScrollEnabled = false

                }


问:
How to get the tallest height of a div in every 3
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

```<code>var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);
</code>```

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

   function logicCall() {

    var maxHeight = 0;
       $(".grid-item .inner .content").each(function() {
        if ($(this).outerHeight() > maxHeight) {
        maxHeight = $(this).outerHeight();
        }
       }).height(maxHeight);

   }

    logicCall();

</script>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here for 3rd item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>4th Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>5th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>6th item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>8th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>9th item</p>
</div>
</div>
</div></code>```

答:
Try this</p>
```<code>let $gridItems = $(".grid-item .inner .content");
for(let i=0; i<$gridItems.length; i+=3){
    let $row = $gridItems.slice(i, i+3);
    let maxHeight = Math.max(...$row.map(function(){return $(this).height()}).get());
    $row.height(maxHeight);
}
</code>```

Body:
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}

Content goes here

Content goes here, so this one is gonna be taller than the 1st and 3rd one...

Content goes here for 3rd item

4th Content goes here

5th item is this one

6th item

7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,

8th item is this one

9th item

Body:
Try this

let $gridItems = $(".grid-item .inner .content");
for(let i=0; i<$gridItems.length; i+=3){
    let $row = $gridItems.slice(i, i+3);
    let maxHeight = Math.max(...$row.map(function(){return $(this).height()}).get());
    $row.height(maxHeight);
}


问:
Pandas Modin ray library fails to startup
I am trying to accelerate my pandas data processing using modin

```<code>import os
os.environ["MODIN_ENGINE"] = "ray"
import modin.pandas as pd

df = pd.read_csv(r"C:\Users\Harshad\Documents\Files\Data\Pre-processed\data.csv", low_memory=False)
</code>```

I get the below warnings and error:

```<code>UserWarning: Ray execution environment not yet initialized. Initializing...
To remove this warning, run the following python code before doing dataframe operations:

    import ray
    ray.init()

Traceback (most recent call last):
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 240, in __init__
    self.redis_password)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\services.py", line 328, in wait_for_node
    raise TimeoutError("Timed out while waiting for node to startup.")
TimeoutError: Timed out while waiting for node to startup.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Harshad/Documents/Code/data.py", line 18, in <module>
    low_memory=False)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 135, in read_csv
    return _read(**kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 58, in _read
    Engine.subscribe(_update_engine)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\config\pubsub.py", line 213, in subscribe
    callback(cls)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\__init__.py", line 127, in _update_engine
    initialize_ray()
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\core\execution\ray\common\utils.py", line 185, in initialize_ray
    ray.init(**ray_init_kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\worker.py", line 922, in init
    ray_params=ray_params)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 243, in __init__
    "The current node has not been updated within 30 "
Exception: The current node has not been updated within 30 seconds, this could happen because of some of the Ray processes failed to startup.
</code>```

While I have clearly re-run the code with more time than 30 seconds between them.

When I run it the first time after installing modin and ray, it run fairly well with just the below warnings:

```<code>UserWarning: Ray execution environment not yet initialized. Initializing...
To remove this warning, run the following python code before doing dataframe operations:

    import ray
    ray.init()
</code>```

Then I modified the code to:

```<code>import os
os.environ["MODIN_ENGINE"] = "ray"
import modin.pandas as pd
import ray
ray.init()
df = pd.read_csv(r"C:\Users\Harshad\Documents\Files\Data\Pre-processed\data.csv", low_memory=False)
</code>```

I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 240, in __init__
    self.redis_password)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\services.py", line 328, in wait_for_node
    raise TimeoutError("Timed out while waiting for node to startup.")
TimeoutError: Timed out while waiting for node to startup.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Harshad/Documents/Code/data.py", line 18, in <module>
    low_memory=False)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 135, in read_csv
    return _read(**kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 58, in _read
    Engine.subscribe(_update_engine)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\config\pubsub.py", line 213, in subscribe
    callback(cls)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\__init__.py", line 127, in _update_engine
    initialize_ray()
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\core\execution\ray\common\utils.py", line 185, in initialize_ray
    ray.init(**ray_init_kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\worker.py", line 922, in init
    ray_params=ray_params)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 243, in __init__
    "The current node has not been updated within 30 "
Exception: The current node has not been updated within 30 seconds, this could happen because of some of the Ray processes failed to startup
</code>```

When I looked into the Github for this issue, it turns out to be a bug

How do I resolve these warnings and errors?

Edit: I restarted my pycharm environment which allowed one cycle of rerun. This indicates that its a Pycharm/environment issue?

How can I resolve this issue?

答:
Try initing ray before you import modin:

```<code>import os
os.environ["MODIN_ENGINE"] = "ray"
import ray
ray.init()
import modin.pandas as pd
</code>```

Body:
I am trying to accelerate my pandas data processing using modin

import os
os.environ["MODIN_ENGINE"] = "ray"
import modin.pandas as pd

df = pd.read_csv(r"C:\Users\Harshad\Documents\Files\Data\Pre-processed\data.csv", low_memory=False)

I get the below warnings and error:

UserWarning: Ray execution environment not yet initialized. Initializing...
To remove this warning, run the following python code before doing dataframe operations:

    import ray
    ray.init()

Traceback (most recent call last):
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 240, in __init__
    self.redis_password)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\services.py", line 328, in wait_for_node
    raise TimeoutError("Timed out while waiting for node to startup.")
TimeoutError: Timed out while waiting for node to startup.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Harshad/Documents/Code/data.py", line 18, in <module>
    low_memory=False)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 135, in read_csv
    return _read(**kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 58, in _read
    Engine.subscribe(_update_engine)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\config\pubsub.py", line 213, in subscribe
    callback(cls)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\__init__.py", line 127, in _update_engine
    initialize_ray()
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\core\execution\ray\common\utils.py", line 185, in initialize_ray
    ray.init(**ray_init_kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\worker.py", line 922, in init
    ray_params=ray_params)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 243, in __init__
    "The current node has not been updated within 30 "
Exception: The current node has not been updated within 30 seconds, this could happen because of some of the Ray processes failed to startup.

While I have clearly re-run the code with more time than 30 seconds between them.

When I run it the first time after installing modin and ray, it run fairly well with just the below warnings:

UserWarning: Ray execution environment not yet initialized. Initializing...
To remove this warning, run the following python code before doing dataframe operations:

    import ray
    ray.init()

Then I modified the code to:

import os
os.environ["MODIN_ENGINE"] = "ray"
import modin.pandas as pd
import ray
ray.init()
df = pd.read_csv(r"C:\Users\Harshad\Documents\Files\Data\Pre-processed\data.csv", low_memory=False)

I get this error:

Traceback (most recent call last):
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 240, in __init__
    self.redis_password)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\services.py", line 328, in wait_for_node
    raise TimeoutError("Timed out while waiting for node to startup.")
TimeoutError: Timed out while waiting for node to startup.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Harshad/Documents/Code/data.py", line 18, in <module>
    low_memory=False)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 135, in read_csv
    return _read(**kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\io.py", line 58, in _read
    Engine.subscribe(_update_engine)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\config\pubsub.py", line 213, in subscribe
    callback(cls)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\pandas\__init__.py", line 127, in _update_engine
    initialize_ray()
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\modin\core\execution\ray\common\utils.py", line 185, in initialize_ray
    ray.init(**ray_init_kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\_private\client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\worker.py", line 922, in init
    ray_params=ray_params)
  File "C:\Users\Harshad\Documents\pythonProject\venv\lib\site-packages\ray\node.py", line 243, in __init__
    "The current node has not been updated within 30 "
Exception: The current node has not been updated within 30 seconds, this could happen because of some of the Ray processes failed to startup

When I looked into the Github for this issue, it turns out to be a bug

How do I resolve these warnings and errors?

Edit: I restarted my pycharm environment which allowed one cycle of rerun. This indicates that its a Pycharm/environment issue?

How can I resolve this issue?

Body:
Try initing ray before you import modin:

import os
os.environ["MODIN_ENGINE"] = "ray"
import ray
ray.init()
import modin.pandas as pd


问:
How to increase the clip size of a vb.net graphic
I'm trying to get familiar with graphics in vb.net and want to draw just a straight line going from the top left to the bottom right of my form Form1 without using the Form1_Paint method but by using Button1

However, the line is only drawn about a quarter of the way and stops as shown in the picture:

I think I need to increase the Clip of the Graphics Object z and I tried the following but it doesn't work. I also tried decreasing the Clip size and that worked as expected.

```<code> Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        z.Clip.MakeInfinite()
        z.DrawLine(pen1, 0, 0, Me.Size.Width, Me.Size.Height)

    End Sub
</code>```

pen1 and z are initialized at the start of the program as follows:

```<code>Dim z As Graphics = CreateGraphics()
Dim pen1 = New Pen(Color.Black, 3)
</code>```

I also tried using different set values for the x2 and y2 but nothing managed to be drawn outside of the box apart from using Form1_paint.

答:
It has nothing to do with the clip, and everything to do with WHEN you called CreateGraphics(). At the point that the graphics was created, the form was not fully initialized and it is using the incorrect size.

When you use CreateGraphics() or create a Pen, you should explicitly Dispose() of them as soon as you're done. This is best accomplished via a Using block:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using z As Graphics = CreateGraphics()
        Using pen1 = New Pen(Color.Black, 3)
            z.DrawLine(pen1, 0, 0, Me.ClientSize.Width, Me.ClientSize.Height)
        End Using
    End Using
End Sub
</code>```

In general, though, using CreateGraphics() in this manner is almost always the INCORRECT approach. The line drawn this way is TEMPORARY. Minimize the form and restore it and the line will be gone.

Body:
I'm trying to get familiar with graphics in vb.net and want to draw just a straight line going from the top left to the bottom right of my form Form1 without using the Form1_Paint method but by using Button1

However, the line is only drawn about a quarter of the way and stops as shown in the picture:

I think I need to increase the Clip of the Graphics Object z and I tried the following but it doesn't work. I also tried decreasing the Clip size and that worked as expected.

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        z.Clip.MakeInfinite()
        z.DrawLine(pen1, 0, 0, Me.Size.Width, Me.Size.Height)

    End Sub

pen1 and z are initialized at the start of the program as follows:

Dim z As Graphics = CreateGraphics()
Dim pen1 = New Pen(Color.Black, 3)

I also tried using different set values for the x2 and y2 but nothing managed to be drawn outside of the box apart from using Form1_paint.

Body:
It has nothing to do with the clip, and everything to do with WHEN you called CreateGraphics(). At the point that the graphics was created, the form was not fully initialized and it is using the incorrect size.

When you use CreateGraphics() or create a Pen, you should explicitly Dispose() of them as soon as you're done. This is best accomplished via a Using block:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using z As Graphics = CreateGraphics()
        Using pen1 = New Pen(Color.Black, 3)
            z.DrawLine(pen1, 0, 0, Me.ClientSize.Width, Me.ClientSize.Height)
        End Using
    End Using
End Sub

In general, though, using CreateGraphics() in this manner is almost always the INCORRECT approach. The line drawn this way is TEMPORARY. Minimize the form and restore it and the line will be gone.


问:
Runtime Code Coverage Tools
I know that there are a number of tools for analysing .NET code and calculating the coverage, plus identifying classes/methods/properties etc that are never going to be hit.

However, I am trying to clean-up a legacy application that I am certain contains an amount of unused code - however a lot of code is accessed via some arbitrary and complex reflection tecniques that will disguise the intent to the compiler - thererfore any coverage tool that only analyses the compiled code is unlikely to generate any reliable reports on code useage within this application.

Are there any tools that work rather like profilers, whereby they listen to a running application and log what classes/methods/properties are actually hit and generate the coverage based on this data.

I hope Ive made everything clear - thanks in anticipation

答: Clover.NET can do this. But it is commercial and I didn't manage to find a link to the .NET version (I've used it several year ago).</p>

Title: Runtime Code Coverage Tools


问:
How to parameterize precision of float on printf format
I have a C program that output values to stdout from measure. I use printf to display them and the format allows me to change the precision

```<code> printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3);
</code>```

My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a #define to have it on a precise location and it will apply on each printf at compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is:

```<code>f"{s_0:.{prec}f}"
</code>```

答:
One way would be to do a #define (as you guessed) like this:

```<code>#define PFLT "%.5f"

printf("Scan=%d S_0=" PFLT " S_1=" PFLT " S_2=" PFLT " S_3=" PFLT, scanId, S0, S1, S2, S3);
</code>```

Then to change the precision you just need to alter the #define and recompile.

Body:
I have a C program that output values to stdout from measure. I use printf to display them and the format allows me to change the precision

 printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3);

My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a #define to have it on a precise location and it will apply on each printf at compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is:

f"{s_0:.{prec}f}"

Body:
One way would be to do a #define (as you guessed) like this:

#define PFLT "%.5f"

printf("Scan=%d S_0=" PFLT " S_1=" PFLT " S_2=" PFLT " S_3=" PFLT, scanId, S0, S1, S2, S3);

Then to change the precision you just need to alter the #define and recompile.


问:
Flutter error: "CocoaPods not installed or not in valid state."
Could the problem be that Android Studio can't find the path to CocoaPods?

I'm trying to test my app on my iPhone from Android Studio. The error I get is

```<code>Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.
</code>```

I ran gem list and the list of installed gems include:

```<code>gem list

cocoapods (1.11.2)
cocoapods-core (1.11.2)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.5.1)
cocoapods-plugins (1.0.0)
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
cocoapods-try (1.2.0)
</code>```

I ran

```<code>sudo gem uninstall cocoapods && sudo gem install cocoapods
</code>```

I ran

```<code>flutter clean
</code>```

I restarted Android Studio.

I ran File > Invalidate Caches… > Invalidate and Restart.

I ran

```<code>cd ios
pod install
</code>```

This threw this error:

```<code>[!] CocoaPods did not set the base configuration of your project because your project already has a custom config set. In order for CocoaPods integration to work at all, please either set the base configurations of the target `Runner` to `Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig` or include the `Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig` in your build configuration (`Flutter/Release.xcconfig`).
</code>```

The Stack Overflow answers about that error message say to fix the issue in Xcode. But when I try to open my Android Studio project in Xcode I get this error:

```<code>Could not open file. (/Users/TDK/StudioProjects/Kabbalah)
</code>```

Here's an odd thing. When I uninstall cocoapods they don't go away:

```<code>sudo gem uninstall cocoapods
Remove executables:
        pod, sandbox-pod

in addition to the gem? [Yn]
Removing pod
Removing sandbox-pod
Successfully uninstalled cocoapods-1.11.2
➜  Kabbalah git:(main) ✗ gem list

*** LOCAL GEMS ***

abbrev (default: 0.1.0)
activesupport (6.1.4.4)
addressable (2.8.0)
algoliasearch (1.27.5)
atomos (0.1.3)
base64 (default: 0.1.0)
benchmark (default: 0.1.1)
bigdecimal (default: 3.0.0)
bundler (default: 2.2.32)
bundler-unload (1.0.2)
CFPropertyList (3.0.5)
cgi (default: 0.2.1)
claide (1.1.0, 1.0.3)
cocoapods (1.11.2)
cocoapods-core (1.11.2)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.5.1)
cocoapods-plugins (1.0.0)
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
cocoapods-try (1.2.0)

</code>```

What do I do next? In case this wasn't obvious, I don't know how to use Xcode.

答: The bug is fixed in Bumblebee 2021.1.1 Patch #1 (released 2022 February 9).</p>

Body:
Could the problem be that Android Studio can't find the path to CocoaPods?

I'm trying to test my app on my iPhone from Android Studio. The error I get is

Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I ran gem list and the list of installed gems include:

gem list

cocoapods (1.11.2)
cocoapods-core (1.11.2)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.5.1)
cocoapods-plugins (1.0.0)
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
cocoapods-try (1.2.0)

I ran

sudo gem uninstall cocoapods && sudo gem install cocoapods

I ran

flutter clean

I restarted Android Studio.

I ran File > Invalidate Caches… > Invalidate and Restart.

I ran

cd ios
pod install

This threw this error:

[!] CocoaPods did not set the base configuration of your project because your project already has a custom config set. In order for CocoaPods integration to work at all, please either set the base configurations of the target `Runner` to `Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig` or include the `Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig` in your build configuration (`Flutter/Release.xcconfig`).

The Stack Overflow answers about that error message say to fix the issue in Xcode. But when I try to open my Android Studio project in Xcode I get this error:

Could not open file. (/Users/TDK/StudioProjects/Kabbalah)

Here's an odd thing. When I uninstall cocoapods they don't go away:

sudo gem uninstall cocoapods
Remove executables:
        pod, sandbox-pod

in addition to the gem? [Yn]
Removing pod
Removing sandbox-pod
Successfully uninstalled cocoapods-1.11.2
➜  Kabbalah git:(main) ✗ gem list

*** LOCAL GEMS ***

abbrev (default: 0.1.0)
activesupport (6.1.4.4)
addressable (2.8.0)
algoliasearch (1.27.5)
atomos (0.1.3)
base64 (default: 0.1.0)
benchmark (default: 0.1.1)
bigdecimal (default: 3.0.0)
bundler (default: 2.2.32)
bundler-unload (1.0.2)
CFPropertyList (3.0.5)
cgi (default: 0.2.1)
claide (1.1.0, 1.0.3)
cocoapods (1.11.2)
cocoapods-core (1.11.2)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.5.1)
cocoapods-plugins (1.0.0)
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
cocoapods-try (1.2.0)

What do I do next? In case this wasn't obvious, I don't know how to use Xcode.


问:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"
I am pushing my docker image to AWS ECS. And, I am getting following error:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Here is the full output:

```<code>The push refers to repository [myaddress.dkr.ecr.us-east-1.amazonaws.com/myrepositoryname]
3d4763f6944c: Layer already exists
5d22ab3cff2d: Layer already exists
080db391ad2c: Layer already exists
7030a45b5de7: Layer already exists
5d98bab77a5b: Layer already exists
f08694a3abdb: Layer already exists
c4cfb93dc085: Layer already exists
1a38a1227cbb: Layer already exists
caa05d68a0ed: Layer already exists
891119e77426: Layer already exists
1f912505da6e: Layer already exists
f1e810a48819: Layer already exists
a47630fbce4f: Layer already exists
09fc3edb847c: Layer already exists
6b60013e5875: Pushing [==================================================>]  323.9MB/323.9MB
d6335a641f5e: Layer already exists
5c33df241050: Layer already exists
ffc4c11463ee: Layer already exists
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"
</code>```

Is there any solution for the above issue? I tried to build an image again and also increased allocated memory in docker.

答:
i had the same problem when i was trying to save my docker image with

```<code>docker save mipscrosscompilation -o mipsCrossCompilation.tar
</code>```

i found that the problem is in one of the commits. So i merged the layers of my image following this https://stackoverflow.com/a/56118557/9546063
i created a new version of the image by merging the layers the i could save it successfully.

Greetings,

Body:
I am pushing my docker image to AWS ECS. And, I am getting following error:
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Here is the full output:

The push refers to repository [myaddress.dkr.ecr.us-east-1.amazonaws.com/myrepositoryname]
3d4763f6944c: Layer already exists
5d22ab3cff2d: Layer already exists
080db391ad2c: Layer already exists
7030a45b5de7: Layer already exists
5d98bab77a5b: Layer already exists
f08694a3abdb: Layer already exists
c4cfb93dc085: Layer already exists
1a38a1227cbb: Layer already exists
caa05d68a0ed: Layer already exists
891119e77426: Layer already exists
1f912505da6e: Layer already exists
f1e810a48819: Layer already exists
a47630fbce4f: Layer already exists
09fc3edb847c: Layer already exists
6b60013e5875: Pushing [==================================================>]  323.9MB/323.9MB
d6335a641f5e: Layer already exists
5c33df241050: Layer already exists
ffc4c11463ee: Layer already exists
file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4"

Is there any solution for the above issue? I tried to build an image again and also increased allocated memory in docker.

Body:
i had the same problem when i was trying to save my docker image with

docker save mipscrosscompilation -o mipsCrossCompilation.tar

i found that the problem is in one of the commits. So i merged the layers of my image following this https://stackoverflow.com/a/56118557/9546063
i created a new version of the image by merging the layers the i could save it successfully.

Greetings,


问:
New to Python requests library, getting '[Errno 61] Connection refused'
I've searched high and low and can't find a fix that seems to fit my use case. I've had some Python3 install issues on my M1 mac but think it's now running okay.

Just trying to learn / work with the requests library, but when I try to run this very simple python code:

```<code>import requests

response = requests.get("https://api.open-notify.org/this-api-doesnt-exist")
print(response.status_code)
</code>```

I get the below error...

Any advice on how to fix this? I'm pulling my hair out.

Thank you!

```<code>/Users/myname/venv/python310/bin/python /Users/myname/Documents/2022_api/api01.py
Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 386, in _make_request
    self._validate_conn(conn)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn
    conn.connect()
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 358, in connect
    conn = self._new_conn()
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/adapters.py", line 440, in send
    resp = conn.urlopen(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.open-notify.org', port=443): Max retries exceeded with url: /this-api-doesnt-exist (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/Documents/2022_api/api01.py", line 3, in <module>
    response = requests.get("https://api.open-notify.org/this-api-doesnt-exist")
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.open-notify.org', port=443): Max retries exceeded with url: /this-api-doesnt-exist (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused'))

Process finished with exit code 1
</code>```

答:
Connection Refused means that the host (api.open-notify.org) is not listening on the port (https is on port 443) in your request.

I tried connecting to port 80 (plain http) instead and that worked for me:

>>> response = requests.get("http://api.open-notify.org/this-api-doesnt-exist")
>>> print(response.status_code)
404
```
<p>For laughs, I tried connecting to the base url</p>
```>>> response = requests.get("http://api.open-notify.org")
>>> print(response.status_code)
500
>>> response
<Response [500]>
>>> response.text
'\r\n<title>500 Internal Server Error</title>\r\n\r\n
500 Internal Server Error
\r\n
nginx/1.10.3\r\n\r\n\r\n'
```

Body:
I've searched high and low and can't find a fix that seems to fit my use case. I've had some Python3 install issues on my M1 mac but think it's now running okay.

Just trying to learn / work with the requests library, but when I try to run this very simple python code:

import requests

response = requests.get("https://api.open-notify.org/this-api-doesnt-exist")
print(response.status_code)

I get the below error...

Any advice on how to fix this? I'm pulling my hair out.

Thank you!

/Users/myname/venv/python310/bin/python /Users/myname/Documents/2022_api/api01.py
Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 386, in _make_request
    self._validate_conn(conn)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn
    conn.connect()
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 358, in connect
    conn = self._new_conn()
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/adapters.py", line 440, in send
    resp = conn.urlopen(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.open-notify.org', port=443): Max retries exceeded with url: /this-api-doesnt-exist (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myname/Documents/2022_api/api01.py", line 3, in <module>
    response = requests.get("https://api.open-notify.org/this-api-doesnt-exist")
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "/Users/myname/venv/python310/lib/python3.10/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.open-notify.org', port=443): Max retries exceeded with url: /this-api-doesnt-exist (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10f5a0850>: Failed to establish a new connection: [Errno 61] Connection refused'))

Process finished with exit code 1

Body:
Connection Refused means that the host (api.open-notify.org) is not listening on the port (https is on port 443) in your request.

I tried connecting to port 80 (plain http) instead and that worked for me:

>>> response = requests.get("http://api.open-notify.org/this-api-doesnt-exist")
>>> print(response.status_code)
404

For laughs, I tried connecting to the base url

>>> response = requests.get("http://api.open-notify.org")
>>> print(response.status_code)
500
>>> response
<Response [500]>
>>> response.text
'<html>\r\n<head><title>500 Internal Server Error</title></head>\r\n<body bgcolor="white">\r\n<center><h1>500 Internal Server Error</h1></center>\r\n<hr><center>nginx/1.10.3</center>\r\n</body>\r\n</html>\r\n'


问:
Check if series of numbers is between two columns in pandas dataframe
I am trying to classify genomic locations, and I have DataFrame like the following, with all locations and their respective classification types. The Type column does not have unique classifications, but each row will have a unique combination of Chr, Low, High.

```<code>pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
</code>```

I then have my sample set that needs to be classified like the DataFrame below.

```<code>pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})
</code>```

To classify the data, for each location in the sample set, the Chromosome position found within the Chr column must match a Chr value found within the reference DataFrame and the Loc value must be >= the Low value and <= the High value. If this happens, that row should then be labeled with the respective Type in the reference DataFrame. In the example I provide, the sample set should be labeled like the following.

```<code>pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325],
    'Type':['Foo','None','None']
})
</code>```

which looks like:

```<code>   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None
</code>```

答:
You can try apply() to check for each row if the conditions return a Type like this:

```<code># Create your data frames
cat = pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
test = pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})

# Check if there is type for each row
test['Type'] = test.apply(lambda x: cat[(cat['Chr']==x['Chr']) & (cat['Low'] < x['Loc']) & (cat['High'] > x['Loc'])]['Type'], axis=1)

test
</code>```

Output:

```<code>    Chr Loc Type
0   1   125 Foo
1   1   325 NaN
2   5   325 NaN
</code>```

Body:
I am trying to classify genomic locations, and I have DataFrame like the following, with all locations and their respective classification types. The Type column does not have unique classifications, but each row will have a unique combination of Chr, Low, High.

pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})

I then have my sample set that needs to be classified like the DataFrame below.

pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})

To classify the data, for each location in the sample set, the Chromosome position found within the Chr column must match a Chr value found within the reference DataFrame and the Loc value must be >= the Low value and <= the High value. If this happens, that row should then be labeled with the respective Type in the reference DataFrame. In the example I provide, the sample set should be labeled like the following.

pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325],
    'Type':['Foo','None','None']
})

which looks like:

   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None

Body:
You can try apply() to check for each row if the conditions return a Type like this:

# Create your data frames
cat = pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
test = pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})

# Check if there is type for each row
test['Type'] = test.apply(lambda x: cat[(cat['Chr']==x['Chr']) & (cat['Low'] < x['Loc']) & (cat['High'] > x['Loc'])]['Type'], axis=1)

test

Output:

    Chr Loc Type
0   1   125 Foo
1   1   325 NaN
2   5   325 NaN


问:
Getting Sonarqube to show a code Coverage score for a simple Java/JUnit/Maven project with Jacoco plugin
I'm practicing on a very small Java/JUnit/Maven project with the Jacoco plugin to practice with the Code Coverage feature of Sonarqube.

The core code for the example is small. Here is the class under test:

```<code>package com.somebody.sonarqube;

public class Calculator {

    // Method to add two numbers
    public int addNumbers(int one, int two) {
        return one + two;
    }

    // Method to subtract two numbers
    public int subtractNumbers(int one, int two) {
        return one - two;
    }
}
</code>```

And here are the unit tests:

```<code>package com.somebody.sonarqube;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAddNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(10, myCalc.addNumbers(5, 5));
    }

    @Test
    public void testSubtractNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(5, myCalc.subtractNumbers(10, 5));
    }

}
</code>```

The two methods in the class under test are covered by the two unit tests respectively, so as far as "Code Coverage" is concerned, that Sonarqube score should be 100%.

When trying to get this score after running my "clean test sonar:sonar" Maven build targets, I'm getting 0% instead:

So the part I'm having the most trouble with is getting the various components in the pom.xml file working together. At this time there's a warning at the <systemPropertyVariables> block at the bottom that reports Invalid plugin configuration: systemPropertyVariables. Here's the full pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.somebody.sonarqube</groupId>
   <artifactId>HelloSonarqube</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>HelloSonarqube</name>
   <description>Small example of Sonarqube and JUnit tests.</description>

   <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13.2</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.sonarsource.scanner.maven</groupId>
         <artifactId>sonar-maven-plugin</artifactId>
         <version>3.9.1.2184</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
            <configuration>
               <release>11</release>
            </configuration>
         </plugin>
         <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.7</version>
            <executions>
               <execution>
                  <id>prepare-agent</id>
                  <goals>
                     <goal>prepare-agent</goal>
                  </goals>
               </execution>
               <execution>
                  <id>report</id>
                  <phase>prepare-package</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
               </execution>
               <execution>
                  <id>post-unit-test</id>
                  <phase>test</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
                  <configuration>
                     <dataFile>target/jacoco.exec</dataFile>
                     <outputDirectory>target/jacoco-ut</outputDirectory>
                  </configuration>
               </execution>
            </executions>
            <configuration>
               <systemPropertyVariables>
                  <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
               </systemPropertyVariables>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>
</code>```

I've tried a lot of variations to this, including changing JUnit 4 to version 5 (I'd be interested to hear about issues on this too). From my reading I generally understand that the Eclipse/JUnit lifecycle is not fully working harmoniously with the Maven lifecycle by default, hence it's missing something. The solutions I've seen/tried are quite specific to certain project setups, and  I have tried manually setting "arguments" and other changes. Would be really thrilled to see your opinions on this having spent a number of hours playing with different versions.

答:
I was able to finally answer the question based upon a similar example I just found on this GitHub project:
https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonarqube-scanner-maven/maven-basic

In short, they used "clean verify sonar:sonar" rather than "clean test sonar:sonar" Maven build targets. The change triggered the code coverage plugin that I was looking for to publish code coverage scores in the Sonarqube dashboard.

As an aside, the warning message I also shared regarding <systemPropertyVariables> was not critical to solving the problem, and I decided to go without that part of the code, and still get all the reports in the Sonarqube dashboard I was looking for.

Body:
I'm practicing on a very small Java/JUnit/Maven project with the Jacoco plugin to practice with the Code Coverage feature of Sonarqube.

The core code for the example is small. Here is the class under test:

package com.somebody.sonarqube;

public class Calculator {

    // Method to add two numbers
    public int addNumbers(int one, int two) {
        return one + two;
    }

    // Method to subtract two numbers
    public int subtractNumbers(int one, int two) {
        return one - two;
    }
}

And here are the unit tests:

package com.somebody.sonarqube;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAddNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(10, myCalc.addNumbers(5, 5));
    }

    @Test
    public void testSubtractNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(5, myCalc.subtractNumbers(10, 5));
    }

}

The two methods in the class under test are covered by the two unit tests respectively, so as far as "Code Coverage" is concerned, that Sonarqube score should be 100%.

When trying to get this score after running my "clean test sonar:sonar" Maven build targets, I'm getting 0% instead:

So the part I'm having the most trouble with is getting the various components in the pom.xml file working together. At this time there's a warning at the <systemPropertyVariables> block at the bottom that reports Invalid plugin configuration: systemPropertyVariables. Here's the full pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.somebody.sonarqube</groupId>
   <artifactId>HelloSonarqube</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>HelloSonarqube</name>
   <description>Small example of Sonarqube and JUnit tests.</description>

   <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13.2</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.sonarsource.scanner.maven</groupId>
         <artifactId>sonar-maven-plugin</artifactId>
         <version>3.9.1.2184</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
            <configuration>
               <release>11</release>
            </configuration>
         </plugin>
         <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.7</version>
            <executions>
               <execution>
                  <id>prepare-agent</id>
                  <goals>
                     <goal>prepare-agent</goal>
                  </goals>
               </execution>
               <execution>
                  <id>report</id>
                  <phase>prepare-package</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
               </execution>
               <execution>
                  <id>post-unit-test</id>
                  <phase>test</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
                  <configuration>
                     <dataFile>target/jacoco.exec</dataFile>
                     <outputDirectory>target/jacoco-ut</outputDirectory>
                  </configuration>
               </execution>
            </executions>
            <configuration>
               <systemPropertyVariables>
                  <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
               </systemPropertyVariables>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

I've tried a lot of variations to this, including changing JUnit 4 to version 5 (I'd be interested to hear about issues on this too). From my reading I generally understand that the Eclipse/JUnit lifecycle is not fully working harmoniously with the Maven lifecycle by default, hence it's missing something. The solutions I've seen/tried are quite specific to certain project setups, and  I have tried manually setting "arguments" and other changes. Would be really thrilled to see your opinions on this having spent a number of hours playing with different versions.


答:
You could try this:

```<code>df2 = df2.assign(Type=None)

for l in df2["Loc"]:
    i = list(df2["Loc"]).index(l)
    if df1["Low"][i] < l < df1["High"][i]:
        df2["Type"][i] = df1["Type"][i]
</code>```

Output:

```<code>   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None
</code>```

Title: Check if series of numbers is between two columns in pandas dataframe

Body:
You could try this:

df2 = df2.assign(Type=None)

for l in df2["Loc"]:
    i = list(df2["Loc"]).index(l)
    if df1["Low"][i] < l < df1["High"][i]:
        df2["Type"][i] = df1["Type"][i]

Output:

   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None