问:
Missing html in requests response python

I am trying to move to the next page till the 'next' button exists at this link 'https://www.cbp.gov/contact/find-broker-by-port/4901?page=1'. I realized that the requests response doesn't have the button in it hence BeautifulSoup cannot find it. I tried adding headers/user-agent to requests but the element still doesn't appear. As far as I can tell, there is no Javascript generating content on this page. Here is the code. What am I missing?

```<code>def second_links(second_links_list=[], page2_num=0):
  try:
    with open('port.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[-1]
        page2 = requests.get(row.format(page2_num))
        soup2 = BeautifulSoup(page2.content, 'html')
        results2 = soup2.find(id='region-content')
        table2cells = results2.find_all('td', class_='views-field views-field-title views-align-center')
        for cell in table2cells:
          cell2link = cell.find('a', href=True)
          second_links_list.append('https://www.cbp.gov'+cell2link['href'])

      next2_page = results2.find('li', class_='pager-next')
      if next2_page:
        page2_num += 1
        second_links(second_links_list, page2_num)
    return second_links_list
  except requests.exceptions.ConnectionError:
    page2.status_code = 'connection refused'
</code>```

答:
import requests
import pandas as pd

def main(url):
    with requests.Session() as req:
        allin = []
        for item in range(3):
            r = req.get(url.format(item))
            df = pd.read_html(r.content)[0]
            allin.append(df)
        new = pd.concat(allin)
        print(new)
        new.to_csv("data.csv", index=False)

main("https://www.cbp.gov/contact/find-broker-by-port/4901?page={}")
```

```                                         Broker Name Broker Filer Code
0                                    AXIOM TRADE INC               BTL
1                      DE LA CRUZ CUSTOMS BROKER INC               ENM
2                          ECI CUSTOMS BROKERAGE INC               BGZ
3                                   EDWIN SEDA PEREZ               9JD
4                 EXPEDITORS INT'L (PUERTO RICO) INC               ES9
5                                     GRISEL PADILLA               MU8
6                    INTEGRITY CUSTOMS BROKERAGE LLC               9QB
7                    INTER-WORLD CUSTOMS BROKERS INC               N35
8                               JAIME MADURO SANTANA               ALA
9                                      JOSE G FLORES               256
0                                JOSE M RAMOS GARCIA               97Q
1                                    JOSE R BERMUDEZ               9HD
2                                        JUAN GARCIA               9ST
3                   JULIO CACERES DBA TRADEWORKS INC               97D
4                          JULIO RODRIGUEZ USCB CORP               EWV
5                                     MANUEL A RAMOS               G68
6                            MANUEL RAMOS-GANDIA INC               CDX
7                                   NESTOR REYES INC               508
8                               NORBERTO DAVID COLON               BLC
9                  P R INTERNATIONAL CUSTOMS BROKERS               D05
0                                      PANALPINA INC               554
1                                PEDRO L CARMONA INC               BWV
2                           PEDRO L SITIRICHE-TORRES               E9T
3  RADIX GROUP INTERNATIONAL INC DBA DHL GLOBAL F...               336
4                   RANK SHIPPING OF PUERTO RICO INC               D84
5                           RENE ORTIZ-VILLAFANE INC               438
6                         ROSA MARINA FLORES-ALVAREZ               NZ5
7                     UPS SUPPLY CHAIN SOLUTIONS INC               UPS
```

Body:
I am trying to move to the next page till the 'next' button exists at this link 'https://www.cbp.gov/contact/find-broker-by-port/4901?page=1'. I realized that the requests response doesn't have the button in it hence BeautifulSoup cannot find it. I tried adding headers/user-agent to requests but the element still doesn't appear. As far as I can tell, there is no Javascript generating content on this page. Here is the code. What am I missing?

def second_links(second_links_list=[], page2_num=0):
  try:
    with open('port.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[-1]
        page2 = requests.get(row.format(page2_num))
        soup2 = BeautifulSoup(page2.content, 'html')
        results2 = soup2.find(id='region-content')
        table2cells = results2.find_all('td', class_='views-field views-field-title views-align-center')
        for cell in table2cells:
          cell2link = cell.find('a', href=True)
          second_links_list.append('https://www.cbp.gov'+cell2link['href'])

      next2_page = results2.find('li', class_='pager-next')
      if next2_page:
        page2_num += 1
        second_links(second_links_list, page2_num)
    return second_links_list
  except requests.exceptions.ConnectionError:
    page2.status_code = 'connection refused'

Body:
import requests
import pandas as pd

def main(url):
    with requests.Session() as req:
        allin = []
        for item in range(3):
            r = req.get(url.format(item))
            df = pd.read_html(r.content)[0]
            allin.append(df)
        new = pd.concat(allin)
        print(new)
        new.to_csv("data.csv", index=False)

main("https://www.cbp.gov/contact/find-broker-by-port/4901?page={}")

                                         Broker Name Broker Filer Code
0                                    AXIOM TRADE INC               BTL
1                      DE LA CRUZ CUSTOMS BROKER INC               ENM
2                          ECI CUSTOMS BROKERAGE INC               BGZ
3                                   EDWIN SEDA PEREZ               9JD
4                 EXPEDITORS INT'L (PUERTO RICO) INC               ES9
5                                     GRISEL PADILLA               MU8
6                    INTEGRITY CUSTOMS BROKERAGE LLC               9QB
7                    INTER-WORLD CUSTOMS BROKERS INC               N35
8                               JAIME MADURO SANTANA               ALA
9                                      JOSE G FLORES               256
0                                JOSE M RAMOS GARCIA               97Q
1                                    JOSE R BERMUDEZ               9HD
2                                        JUAN GARCIA               9ST
3                   JULIO CACERES DBA TRADEWORKS INC               97D
4                          JULIO RODRIGUEZ USCB CORP               EWV
5                                     MANUEL A RAMOS               G68
6                            MANUEL RAMOS-GANDIA INC               CDX
7                                   NESTOR REYES INC               508
8                               NORBERTO DAVID COLON               BLC
9                  P R INTERNATIONAL CUSTOMS BROKERS               D05
0                                      PANALPINA INC               554
1                                PEDRO L CARMONA INC               BWV
2                           PEDRO L SITIRICHE-TORRES               E9T
3  RADIX GROUP INTERNATIONAL INC DBA DHL GLOBAL F...               336
4                   RANK SHIPPING OF PUERTO RICO INC               D84
5                           RENE ORTIZ-VILLAFANE INC               438
6                         ROSA MARINA FLORES-ALVAREZ               NZ5
7                     UPS SUPPLY CHAIN SOLUTIONS INC               UPS


来源: stackexchange

问:
Defining for loop iterator before the for loop?
Recently I'd been criticized for structuring my for loops like so:

```<code>var i:MovieClip;
for each(i in array)
{
    // be awesome
}
</code>```

Or,

```<code>var i:uint = 0;
for(i; i<10; i++)
{
    // be more awesome
}
</code>```

This reads better for me personally, yet I'm being attacked for it. Is there any difference?

答:
Old Answer

Yes: The way you're doing it, the variable lives on after the loop ends. Making sure the variable doesn't exist outside of the scope of the loop ensures that you never accidentally refer to it outside the loop.

Update:

At least that's how most languages do it. However, in ActionScript the for loop variable is in the scope of the parent! So there really is no difference in ActionScript.

ContentLicense: CC BY-SA 3.0

Body:
Recently I'd been criticized for structuring my for loops like so:

var i:MovieClip;
for each(i in array)
{
    // be awesome
}

Or,

var i:uint = 0;
for(i; i<10; i++)
{
    // be more awesome
}

This reads better for me personally, yet I'm being attacked for it. Is there any difference?


问:
Share a unique version of google colab doc?
Does anyone know how exactly I can share a unique version of a google colab doc? I have a colab sheet on my Google Drive and I want to allow for someone to access the file, run, make edits, etc. However, I don't want any of the edits made to be on my version of the doc.

I've searched everywhere...

答:
To share a link to your notebook that allows editing but does not modify your copy, first open the notebook in playground mode using the command palette. (Tools menu -> Command palette)

Then, select the 'Open in playground' command.

This will reload the notebook with a new URL that you can share, allowing others to modify and execute an ephemeral copy of the notebook without modifying the original. If they attempt to save, they will be prompted to create a copy in their own Drive.

ContentLicense: CC BY-SA 4.0


问:
How to pass template arguments via constructor?
I'm looking for a way to pass the template arguments of a template-based class (the main class of the FastLED library on Arduino, to be specific) via the constructor of my own class (which should basically wrap the FastLED library). I want to specify the template arguments necessary to initialize FastLED in the main function, so that all pre-configuration before compiling (i.e. the #defines in the third code block below) works via constants in the main file. How can I achieve this?

Currently, my class looks like this:

LEDState.h:

```<code>#pragma once
#include "FastLED.h"
FASTLED_USING_NAMESPACE

class LEDState {
  private:
    CRGB* _leds;
    CRGB* _pixels;
    const uint16_t _pixel_count;
    const uint16_t _led_count;
    const uint8_t _mapmode;

  public:
    LEDState(const uint16_t pixel_count, const uint8_t mapmode);
    void show();
};
</code>```

LEDState.cpp:

```<code>#include "LEDState.h"

LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
: _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count * (_mapmode & 0x0f))
{
  _leds = (CRGB*)malloc(_led_count * sizeof(CRGB));
  _pixels = (CRGB*)malloc(_pixel_count * sizeof(CRGB));
  FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(_leds, _led_count);
}

void LEDState::show() {
  for( int p = 0; p < _pixel_count; p++ ) {
    _leds[p] = _pixels[p];
  }
  FastLED.show();
}
</code>```

My problem is that I did not find a way to pass the template arguments <CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> via the constructor of LEDState.

Is there a way to initialize my wrapper class and the wrapped FastLED library from my main file? I'm imagining my main.ino file like this:

```<code>#include "LEDState.h"

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

LEDState state = LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(led_count, map_mode);

void setup() {
}

void loop() {
  LEDState.show();
}
</code>```

(with APA102 and GRB being constants from the FastLED library.)

Is something like this possible at all?

(I'm not confident that I know the right vocabulary to search for a solution, leave alone using the right terminology in this question. Everything I found either wasn't a solution to my problem or I didn't understand that it was a solution. I'm coming from "plain Arduino C"; and my knowledge about C++ templates is roughly at: I can work my way through patching existing template code, but I don't know how to create a template.)

EDIT: With the comments and first answers, I guess that I need my class to also be templated. I tried copying the template argument list from the FastLED library (see link above), resulting in this class definition:

```<code>template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder COLOR_ORDER>
class LEDState {
  ...
}
</code>```

(ESPIChipsets and EOrder are defined by FastLED)

Now the compiler complains with

```<code>LEDState.cpp:3:1: error: invalid use of template-name 'LEDState' without an argument list
 LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
 ^
</code>```

What else do I need to make it compile?

答:
No. What you want to do is not possible.

Your question is related to this, and the same answer applies.

What you want to do would be achieved by a class template. For instance:

```<code>template<std::size_t N> class foo { /* interface*/ };
</code>```

which you can then instantiate pretty similarly as you wanted:

```<code>foo<10> bar;
/* Use bar */
</code>```

Body:
I'm looking for a way to pass the template arguments of a template-based class (the main class of the FastLED library on Arduino, to be specific) via the constructor of my own class (which should basically wrap the FastLED library). I want to specify the template arguments necessary to initialize FastLED in the main function, so that all pre-configuration before compiling (i.e. the #defines in the third code block below) works via constants in the main file. How can I achieve this?

Currently, my class looks like this:

LEDState.h:

#pragma once
#include "FastLED.h"
FASTLED_USING_NAMESPACE

class LEDState {
  private:
    CRGB* _leds;
    CRGB* _pixels;
    const uint16_t _pixel_count;
    const uint16_t _led_count;
    const uint8_t _mapmode;

  public:
    LEDState(const uint16_t pixel_count, const uint8_t mapmode);
    void show();
};

LEDState.cpp:

#include "LEDState.h"

LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
: _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count * (_mapmode & 0x0f))
{
  _leds = (CRGB*)malloc(_led_count * sizeof(CRGB));
  _pixels = (CRGB*)malloc(_pixel_count * sizeof(CRGB));
  FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(_leds, _led_count);
}

void LEDState::show() {
  for( int p = 0; p < _pixel_count; p++ ) {
    _leds[p] = _pixels[p];
  }
  FastLED.show();
}

My problem is that I did not find a way to pass the template arguments <CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> via the constructor of LEDState.

Is there a way to initialize my wrapper class and the wrapped FastLED library from my main file? I'm imagining my main.ino file like this:

#include "LEDState.h"

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

LEDState state = LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(led_count, map_mode);

void setup() {
}

void loop() {
  LEDState.show();
}

(with APA102 and GRB being constants from the FastLED library.)

Is something like this possible at all?

(I'm not confident that I know the right vocabulary to search for a solution, leave alone using the right terminology in this question. Everything I found either wasn't a solution to my problem or I didn't understand that it was a solution. I'm coming from "plain Arduino C"; and my knowledge about C++ templates is roughly at: I can work my way through patching existing template code, but I don't know how to create a template.)

EDIT: With the comments and first answers, I guess that I need my class to also be templated. I tried copying the template argument list from the FastLED library (see link above), resulting in this class definition:

template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder COLOR_ORDER>
class LEDState {
  ...
}

(ESPIChipsets and EOrder are defined by FastLED)

Now the compiler complains with

LEDState.cpp:3:1: error: invalid use of template-name 'LEDState' without an argument list
 LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
 ^

What else do I need to make it compile?

Body:
No. What you want to do is not possible.

Your question is related to this, and the same answer applies.

What you want to do would be achieved by a class template. For instance:

template<std::size_t N> class foo { /* interface*/ };

which you can then instantiate pretty similarly as you wanted:

foo<10> bar;
/* Use bar */


问:
Root View Controller I can't assign it to class
I have this view Controller but't I can't assign to any class enter image description here</p>

答:
What class are you trying to assign? Make sure that it inherits from UITableViewController, otherwise it won't be able to assign it. It must be
something like this:</p>

```<code>class YourClass: UITableViewController {
//Class implementation
}
</code>```

Body:
What class are you trying to assign? Make sure that it inherits from UITableViewController, otherwise it won't be able to assign it. It must be
something like this:

class YourClass: UITableViewController {
//Class implementation
}


问:
How can I reduce Stanford parser time of execution?
Good Morning,

I am using Stanford part of speech for my application, and I need to parse many text files (can go to 20 files). However I noticed that stanford takes a lot of time (sometimes 30min or more), the problem is that Stanford automatically builds the syntax tree, even when I don't need it.
Have anyone face this problem before? what can I do to reduce the parsing time of stanford?

Any help is welcome,
Regards.

答: If you just want part of speech, not parse trees, you should run a (sequence model) part of speech tagger, such as the Stanford POS Tagger, which is orders of magnitude faster).  See the Stanford Parser FAQ.  (If you want fast tagging, use the  left3words-wsj-0-18.tagger model of the Stanford POS Tagger.)


问:
JS Plugin to avoid copy from pdf
I am looking for a JS Plugin that let me to show
    1. PDF Document in Web browser
    2. (Most Important)Text in that PDF must not be copied by other

I have tried using PDFObject that allowed me to embed PDF Document into my
HTML document
here is a code

```<code> <div id="pdf" style="height: 500px;">
<script>
    var options = {
    height: "500px",
    pdfOpenParams: {
        view: 'FitBV,left',
        pagemode: 'bookmarks',
        search: '',
        allowcopy:false //doesnot exist
    }
};

    PDFObject.embed("sample-3pp.pdf",document.getElementById("pdf"),options)
</script>
</code>```

in this 'allowcopy' parameter doesnot exist in acrobat sdk (parameters for opening documentation) i am looking for
such kind of a usecase/parameter that puts to be false and someone cannot copy my content.

答:
Well you can do 2 things to prevent others to copy your PDF content.

1. Use a webview/iframe for the PDF.

 There are a lot of tools online that will also give you a option to protect your pdf online. Just google it.
For example: flippingbook, locklizard and similer third-party tools.

OR

2. Disable copy/cut via JAVASCRIPT and also disable seleting with CSS...

The javascript to disable copy/cut functions (for the whole body tag):

```<code><script type="text/javascript">
  $(document).ready(function () {
      $('body').bind('cut copy', function (e) {
          e.preventDefault();
      });
  });
</script>
</code>```

The css that disables the SELECTING of content (for the class noSelect):

```<code>.noSelect {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
     -khtml-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
}
</code>```

I think this is what you were searching. I hope this will help you further.

Update:
Also adding "#toolbar=0&navpanes=0&scrollbar=0" to the embed pdf would disable download/save buttons. Disabling the right-click would also be a TODO here since users will probably still be able to download if it is allowed to use the right-click... You can do this with JAVASCRIPT:

```<code> window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
}, false);
</code>```

However smart users can still bypass this option...

Title: JS Plugin to avoid copy from pdf

Body:
I am looking for a JS Plugin that let me to show
    1. PDF Document in Web browser
    2. (Most Important)Text in that PDF must not be copied by other

I have tried using PDFObject that allowed me to embed PDF Document into my
HTML document
here is a code

in this 'allowcopy' parameter doesnot exist in acrobat sdk (parameters for opening documentation) i am looking for
such kind of a usecase/parameter that puts to be false and someone cannot copy my content.

Body:
Well you can do 2 things to prevent others to copy your PDF content.

1. Use a webview/iframe for the PDF.

 There are a lot of tools online that will also give you a option to protect your pdf online. Just google it.
For example: flippingbook, locklizard and similer third-party tools.

OR

2. Disable copy/cut via JAVASCRIPT and also disable seleting with CSS...

The javascript to disable copy/cut functions (for the whole body tag):

<script type="text/javascript">
  $(document).ready(function () {
      $('body').bind('cut copy', function (e) {
          e.preventDefault();
      });
  });
</script>

The css that disables the SELECTING of content (for the class noSelect):

.noSelect {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
     -khtml-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
}

I think this is what you were searching. I hope this will help you further.

Update:
Also adding "#toolbar=0&navpanes=0&scrollbar=0" to the embed pdf would disable download/save buttons. Disabling the right-click would also be a TODO here since users will probably still be able to download if it is allowed to use the right-click... You can do this with JAVASCRIPT:

 window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
}, false);

However smart users can still bypass this option...


问:
Can't seem to import queue into python
I'm following a tutorial on how to create queues in python

But i can't get past the first hurdle:

When I try to import the queue module and try and create a queue

```<code>import queue

# Initializing a queue
qW = queue.Queue(maxsize=20)

# qsize() give the maxsize of the Queue
print(qW.qsize())
</code>```

I get this error

```<code>AttributeError: partially initialized module 'queue' has no attribute 'Queue' (most likely due to a circular import)
</code>```

答: You likely used the same name for a file in your script folder </p>

Title: Can't seem to import queue into python

Body:
I'm following a tutorial on how to create queues in python

But i can't get past the first hurdle:

When I try to import the queue module and try and create a queue

import queue

# Initializing a queue
qW = queue.Queue(maxsize=20)

# qsize() give the maxsize of the Queue
print(qW.qsize())

I get this error

AttributeError: partially initialized module 'queue' has no attribute 'Queue' (most likely due to a circular import)


答:
You seem to actually want a class template. Here is how you create one in C++</p>

```<code>#include <iostream>

template < class T >
class my_class {

    public:
        typedef T type;

        my_class() {
            std::cout << sizeof( type ) << '\n';
        }

};

int main()
{
    auto A = my_class< double >();
    auto B = my_class< float >();
    auto C = my_class< char >();

    return 0;
}
</code>```

Title: How to pass template arguments via constructor?

Body:
You seem to actually want a class template. Here is how you create one in C++

#include <iostream>

template < class T >
class my_class {

    public:
        typedef T type;

        my_class() {
            std::cout << sizeof( type ) << '\n';
        }

};

int main()
{
    auto A = my_class< double >();
    auto B = my_class< float >();
    auto C = my_class< char >();

    return 0;
}


问:
Intellij disable new line before annotated field for Kotlin
IntelliJ autoformat keeps adding a blank lines between class field declarations having annotations.
Do you know how to disable it?
This happens for kotlin files since does not work like that for java files.

Example, between each var intellij adds a blank line each time I execute autoformat.

```<code>class Resign : UnitTest() {
    @InjectMocks
    private lateinit var resignService: ResignServiceImpl

    @Mock
    private lateinit var actionAccess: ActionAccess

    @Mock
    private lateinit var userReportConverter: UserReportConverter

    ....
}
</code>```

答:
Go to Settings > Editor > Code style > Kotlin > Wrapping and Braces.

Change Property annotations to "Do not wrap" or "Wrap if long".

Body:
IntelliJ autoformat keeps adding a blank lines between class field declarations having annotations.
Do you know how to disable it?
This happens for kotlin files since does not work like that for java files.

Example, between each var intellij adds a blank line each time I execute autoformat.

class Resign : UnitTest() {
    @InjectMocks
    private lateinit var resignService: ResignServiceImpl

    @Mock
    private lateinit var actionAccess: ActionAccess

    @Mock
    private lateinit var userReportConverter: UserReportConverter

    ....
}


问:
Possible to extend static SQL statements with dynamic parts?
I'd like to create a Oracle package where I have a procedure that executes some dynamic SQL. This is no problem if I'm doing it all dynamic with EXECUTE IMMEDIATE but it would be better if the static parts of the query could be coded static (to have compile time checking).

Example of fully dynamic query:

```<code>-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM <here some joins> WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;
</code>```

Example of what I tried to make the FROM-part static:

```<code>-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM my_package.my_function(:param1, :param2) WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

FUNCTION my_function(
  i_param1 IN VARCHAR2,
  i_param2 IN NUMBER
)
RETURN SYS_REFCURSOR
AS
  v_cursor SYS_REFCURSOR;
BEGIN
  -- Open a cursor for different queries depending on params.
  IF i_param2 = 1 THEN
      OPEN v_cursor FOR <some static query>;
  ELSE
      OPEN v_cursor FOR <some other static query>;
  END IF;
  RETURN v_cursor;
END;
</code>```

This doesn't work because it's not possible to select from a SYS_REFCURSOR (at least that's what I found with Google).

Is there any way to reach this goal?

edit: As requested, here are some examples:

Static queries:

```<code>SELECT a.*, ca.CUS_ID FROM adresses a INNER JOIN customer_adresses ca ON (ca.adr_id = a.adr_id);
SELECT p.*, cp.CUS_ID FROM persons p INNER JOIN customer_persons cp ON (cp.per_id = p.per_id);
</code>```

Then they are extended dynamically like the following examples:

```<code>-- Checks if there is an adress in the customer where the zip is null.
SELECT count(*) FROM <static adresses query> q WHERE q.cus_id = :param1 AND a.zip IS NULL;
-- Checks if there is at least one person in the customer.
SELECT count(*) FROM <static persons query> q WHERE q.cus_id = :param1;
</code>```

答:
You can have compile time checking of expressions with Oracle expression filter.

It's probably more complicated than the other solutions, but if you really need to verify your conditions it can be helpful.

Body:
I'd like to create a Oracle package where I have a procedure that executes some dynamic SQL. This is no problem if I'm doing it all dynamic with EXECUTE IMMEDIATE but it would be better if the static parts of the query could be coded static (to have compile time checking).

Example of fully dynamic query:

-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM <here some joins> WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

Example of what I tried to make the FROM-part static:

-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM my_package.my_function(:param1, :param2) WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

FUNCTION my_function(
  i_param1 IN VARCHAR2,
  i_param2 IN NUMBER
)
RETURN SYS_REFCURSOR
AS
  v_cursor SYS_REFCURSOR;
BEGIN
  -- Open a cursor for different queries depending on params.
  IF i_param2 = 1 THEN
      OPEN v_cursor FOR <some static query>;
  ELSE
      OPEN v_cursor FOR <some other static query>;
  END IF;
  RETURN v_cursor;
END;

This doesn't work because it's not possible to select from a SYS_REFCURSOR (at least that's what I found with Google).

Is there any way to reach this goal?

edit: As requested, here are some examples:

Static queries:

SELECT a.*, ca.CUS_ID FROM adresses a INNER JOIN customer_adresses ca ON (ca.adr_id = a.adr_id);
SELECT p.*, cp.CUS_ID FROM persons p INNER JOIN customer_persons cp ON (cp.per_id = p.per_id);

Then they are extended dynamically like the following examples:

-- Checks if there is an adress in the customer where the zip is null.
SELECT count(*) FROM <static adresses query> q WHERE q.cus_id = :param1 AND a.zip IS NULL;
-- Checks if there is at least one person in the customer.
SELECT count(*) FROM <static persons query> q WHERE q.cus_id = :param1;


问:
Setting locale in moment.js not working despite using the locale file
There is a setLocale method in a dependency of a project, and I call this method from the project on locale change. However, the locale doesn't seem to change.

```<code>import moment from 'moment';
import 'moment/locale/de';

export const setLocale = locale => {
    console.log(`Locale to be set: ${locale}`)
    moment.locale(locale);
    console.log(moment.locale())
};
</code>```

Output in console

I'm using moment-js v2.26.0in the dependency and 2.24.0 in the main project.

Same happens if I set locale explicitly.

However, changing the locale works in the main project works just fine.

答:
From official documentation

Note: There is a bug that prevents moment.locale from being loaded.

```<code>var moment = require('moment');
moment.locale('cs');
console.log(moment.locale()); // en
</code>```

use workaround below

```<code>var moment = require('moment');
require('moment/locale/cs');
console.log(moment.locale()); // cs
</code>```

Body:
There is a setLocale method in a dependency of a project, and I call this method from the project on locale change. However, the locale doesn't seem to change.

import moment from 'moment';
import 'moment/locale/de';

export const setLocale = locale => {
    console.log(`Locale to be set: ${locale}`)
    moment.locale(locale);
    console.log(moment.locale())
};

Output in console

I'm using moment-js v2.26.0in the dependency and 2.24.0 in the main project.

Same happens if I set locale explicitly.

However, changing the locale works in the main project works just fine.

Body:
From official documentation

Note: There is a bug that prevents moment.locale from being loaded.

var moment = require('moment');
moment.locale('cs');
console.log(moment.locale()); // en

use workaround below

var moment = require('moment');
require('moment/locale/cs');
console.log(moment.locale()); // cs


答:
Make sure your current file or any other file in your current working directory is not named as queue.py
Python is probably importing that instead of the standard library.</p>

Title: Can't seem to import queue into python


问:
watch network with nightwatch
I'm using nightwatch to test the frontend of an application.
I'm testing that some buttons are clickable or not.

Is it possible with nightwatch, to know if there was a network
request made by the click, or more generally, to watch the network.

答:
Here is the solution to capture the XHR traffic:

https://github.com/Bugazelle/nightwatch-capture-network-traffic

How it is working

Take advantage of the ajaxListener.js

The js is forked from https://gist.github.com/icodejs/3183154

This hack will make all the XHR requests as a warn log to console

```<code>    {
        "type": "response",
        "syncMode": this.syncMode,
        "method": this.method,
        "url": this.url,
        "requestData": this.requestData,
        "readyState": this.readyState,
        "responseText": this.responseText,
        "responseCode": this.status,
        "responseHeader": this.getAllResponseHeaders()
    }
</code>```

Then take advantage of Nightwatch API .getLog

The .getLog could capture the console warn logs for us

Title: watch network with nightwatch

Body:
Here is the solution to capture the XHR traffic:

https://github.com/Bugazelle/nightwatch-capture-network-traffic

How it is working

Take advantage of the ajaxListener.js

The js is forked from https://gist.github.com/icodejs/3183154

This hack will make all the XHR requests as a warn log to console

    {
        "type": "response",
        "syncMode": this.syncMode,
        "method": this.method,
        "url": this.url,
        "requestData": this.requestData,
        "readyState": this.readyState,
        "responseText": this.responseText,
        "responseCode": this.status,
        "responseHeader": this.getAllResponseHeaders()
    }

Then take advantage of Nightwatch API .getLog

The .getLog could capture the console warn logs for us


问:
bash: choose default from case when enter is pressed in a "select" prompt
I'm prompting questions in a bash script like this:

```<code>optionsAudits=("Yep" "Nope")
    echo "Include audits?"
    select opt in "${optionsAudits[@]}"; do
        case $REPLY in
            1) includeAudits=true; break ;;
            2) includeAudits=false; break ;;
            "\n") echo "You pressed enter"; break ;; # <--- doesn't work
            *) echo "What's that?"; exit;;
        esac
    done
</code>```

How can I select a default option when enter is pressed? The "\n" case does not catch the enter key.

答:
This will do what you are asking for.</p>

```<code>options=("option 1" "option 2");
while :
do
    echo "Select your option:"
    i=1;
    for opt in  "${options[@]}"; do
        echo "$i) $opt";
        let i++;
    done

    read reply
    case $reply in
        "1"|"${options[0]}"|"")
          doSomething1();
          break;;
        "2"|"${options[1]}")
          doSomething2();
          break;;
        *)
          echo "Invalid choice. Please choose 1 or 2";;
    esac
done
</code>```

Body:
I'm prompting questions in a bash script like this:

optionsAudits=("Yep" "Nope")
    echo "Include audits?"
    select opt in "${optionsAudits[@]}"; do
        case $REPLY in
            1) includeAudits=true; break ;;
            2) includeAudits=false; break ;;
            "\n") echo "You pressed enter"; break ;; # <--- doesn't work
            *) echo "What's that?"; exit;;
        esac
    done

How can I select a default option when enter is pressed? The "\n" case does not catch the enter key.

Body:
This will do what you are asking for.

options=("option 1" "option 2");
while :
do
    echo "Select your option:"
    i=1;
    for opt in  "${options[@]}"; do
        echo "$i) $opt";
        let i++;
    done

    read reply
    case $reply in
        "1"|"${options[0]}"|"")
          doSomething1();
          break;;
        "2"|"${options[1]}")
          doSomething2();
          break;;
        *)
          echo "Invalid choice. Please choose 1 or 2";;
    esac
done


问:
html camera video stream doesnt show in android webview
I have a website that I converted to an apk using android studio. The app works fine, however when i try to use a camera it shows this image:
screenshot

The camera stream shows in the browser on my phone.
When i google about this the solutions are using old deprecated code from before androidx and dont work anymore.I cant get this solution to work How do I fix this?

```<code>mainactivity:
package name;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.Intent;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String ShowOrHideWebViewInitialUse = "show";
    private WebView webview ;
    private ProgressBar spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webview = findViewById(R.id.webView);
        spinner = findViewById(R.id.progressBar1);
        webview.setWebViewClient(new CustomWebViewClient());

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        webview.loadUrl("url");

    }

    private class CustomWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webview, String url, Bitmap favicon) {

            if (ShowOrHideWebViewInitialUse.equals("show")) {
                webview.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webview.canGoBack()) {
                        webview.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="name">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAMERA2" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.intent.action.CAMERA_BUTTON" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:exported="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

activity main xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="name"> <WebView
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:id="@+id/webView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:visibility="gone" />
    <ProgressBar
        android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_centerInParent="true" />
<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />

    <!-- This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<LinearLayout
    android:id="@+id/fullscreen_content_controls"
    style="?metaButtonBarStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center_horizontal"
    android:background="@color/black_overlay"
    android:orientation="horizontal"
    tools:ignore="UselessParent">

</LinearLayout>
</FrameLayout>
</RelativeLayout>
</code>```

答:
Try specifying a WebChromeClient with onPermissionRequest

The following would grant permission for everything

```<code>
webview.setWebChromeClient(new WebChromeClient() {

   @Override
   public void onPermissionRequest(final PermissionRequest request) {
       request.grant(request.getResources());
   }

 });
</code>```

Body:
I have a website that I converted to an apk using android studio. The app works fine, however when i try to use a camera it shows this image:
screenshot

The camera stream shows in the browser on my phone.
When i google about this the solutions are using old deprecated code from before androidx and dont work anymore.I cant get this solution to work How do I fix this?

mainactivity:
package name;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.Intent;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String ShowOrHideWebViewInitialUse = "show";
    private WebView webview ;
    private ProgressBar spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webview = findViewById(R.id.webView);
        spinner = findViewById(R.id.progressBar1);
        webview.setWebViewClient(new CustomWebViewClient());

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        webview.loadUrl("url");

    }

    private class CustomWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webview, String url, Bitmap favicon) {

            if (ShowOrHideWebViewInitialUse.equals("show")) {
                webview.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webview.canGoBack()) {
                        webview.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="name">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAMERA2" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.intent.action.CAMERA_BUTTON" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:exported="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity main xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="name"> <WebView
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:id="@+id/webView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:visibility="gone" />
    <ProgressBar
        android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_centerInParent="true" />
<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<LinearLayout
    android:id="@+id/fullscreen_content_controls"
    style="?metaButtonBarStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center_horizontal"
    android:background="@color/black_overlay"
    android:orientation="horizontal"
    tools:ignore="UselessParent">

</LinearLayout>
</FrameLayout>
</RelativeLayout>

Body:
Try specifying a WebChromeClient with onPermissionRequest

The following would grant permission for everything

webview.setWebChromeClient(new WebChromeClient() {

   @Override
   public void onPermissionRequest(final PermissionRequest request) {
       request.grant(request.getResources());
   }

 });


问:
Making assembly function inline in x64 Visual Studio
I know that MSVC compiler in x64 mode does not support inline assembly snippets of code, and in order to use assembly code you have to define your function in some external my_asm_funcs.asm file like that:

```<code>my_asm_func PROC
    mov rax, rcx
    ret
my_asm_func ENDP
</code>```

And then in your .c or .h file you define a header for the function like that:

```<code>int my_asm_func(int x);
</code>```

Although that solution answers many concerns, but I am still interested in making that assembly code function to be inline, in other words - after compilation I don't want any "calls" to my_asm_func, I just want this piece of assembly to be glued into my final compiled code. I tried declaring the function with inline and __forceinline keywords, but nothing seems to be helping. Is there still any way to do what I want?

答:
Since the title mentions Visual Studio and not MSVC, I recommend installing Clang via the Visual Studio Installer. It can be used just like MSVC without needing to configure custom build tasks or anything and it supports inline assembly with Intel syntax and variables as operands.

Just select "LLVM (clang-cl)" in Platform Toolset from the General section of the property pages in your project and you're good to go.

Body:
I know that MSVC compiler in x64 mode does not support inline assembly snippets of code, and in order to use assembly code you have to define your function in some external my_asm_funcs.asm file like that:

my_asm_func PROC
    mov rax, rcx
    ret
my_asm_func ENDP

And then in your .c or .h file you define a header for the function like that:

int my_asm_func(int x);

Although that solution answers many concerns, but I am still interested in making that assembly code function to be inline, in other words - after compilation I don't want any "calls" to my_asm_func, I just want this piece of assembly to be glued into my final compiled code. I tried declaring the function with inline and __forceinline keywords, but nothing seems to be helping. Is there still any way to do what I want?


问:
How to make tslint accept variable name with "_" at the beginning
I have a require of customer that say to need "_" symbol. I added this like that:

```<code>public _someVariable: string;
</code>```

but tslint say variable name must be in lowerCamelCase, PascalCase or UPPER_CASE (variable-name).

I want remove alerts while keeping the tslint config and this is my tslint config:

```<code>"variable-name": {
  "options": [
    "ban-keywords",
    "check-format",
    "allow-pascal-case"
  ]
},
</code>```

答:
Set allow-leading-underscore.

```<code>"variable-name": {
  "options": [
    "ban-keywords",
    "check-format",
    "allow-pascal-case",
    "allow-leading-underscore"
  ]
},
</code>```

https://palantir.github.io/tslint/rules/variable-name/

Body:
I have a require of customer that say to need "_" symbol. I added this like that:

public _someVariable: string;

but tslint say variable name must be in lowerCamelCase, PascalCase or UPPER_CASE (variable-name).

I want remove alerts while keeping the tslint config and this is my tslint config:

"variable-name": {
  "options": [
    "ban-keywords",
    "check-format",
    "allow-pascal-case"
  ]
},

Body:
Set allow-leading-underscore.

"variable-name": {
  "options": [
    "ban-keywords",
    "check-format",
    "allow-pascal-case",
    "allow-leading-underscore"
  ]
},

https://palantir.github.io/tslint/rules/variable-name/


问:
Equalize row count between columns in Python Pandas DataFrame

My Problem

I'm working on sentiment analysis using ML models.

I have a dataset of Amazon reviews from 1 to 5 stars.

```<code>print(df.groupby('overall').count())

overall    reviewText
1.0          108725
2.0           82139
3.0          142257
4.0          347041
5.0         1009026
</code>```

These results are biased, with 59% of them being 5-stars. I'm afraid if I train my model with this dataset, it will learn quickly to be biased towards rating a sentiment of 'Positive'.

I would like to equalize all of these rows so each 'overall' rating has an equal number of 'reviewText'

My Current Solution

Here is my current solution

```<code>one_star_ratings = df.loc[df['overall'] == 1.0][0:80000]
two_star_ratings =  df.loc[df['overall'] == 2.0][0:80000]
three_star_ratings = df.loc[df['overall'] == 3.0][0:80000]
four_star_ratings =  df.loc[df['overall'] == 4.0][0:80000]
five_star_ratings = df.loc[df['overall'] == 5.0][0:80000]

df2 = pd.concat([one_star_ratings, two_star_ratings, three_star_ratings, four_star_ratings,
five_star_ratings])
</code>```

This works, but it is a naive solution.

My question

I will encounter this issue frequently while working with datasets, and I am trying to find a better solution. Assume I had 100 categories, and not just 5. How can I better solve this problem without writing 100+ lines of code to do it?

答:
You could use groupby().head() for this:

```<code>n_sample = 80000
df2 = df.groupby('overall').head(n_sample)
</code>```

If you want to sample randomly:

```<code>df2 = df.sample(frac=1).groupby('overall').head(n_sample)
</code>```

You can also use sample to randomly select the data:

```<code>df2 = df.groupby('overall')apply(lambda x: x.sample(n=n_sample))
</code>```

Body:
My Problem

I'm working on sentiment analysis using ML models.

I have a dataset of Amazon reviews from 1 to 5 stars.

print(df.groupby('overall').count())

overall    reviewText
1.0          108725
2.0           82139
3.0          142257
4.0          347041
5.0         1009026

These results are biased, with 59% of them being 5-stars. I'm afraid if I train my model with this dataset, it will learn quickly to be biased towards rating a sentiment of 'Positive'.

I would like to equalize all of these rows so each 'overall' rating has an equal number of 'reviewText'

My Current Solution

Here is my current solution

one_star_ratings = df.loc[df['overall'] == 1.0][0:80000]
two_star_ratings =  df.loc[df['overall'] == 2.0][0:80000]
three_star_ratings = df.loc[df['overall'] == 3.0][0:80000]
four_star_ratings =  df.loc[df['overall'] == 4.0][0:80000]
five_star_ratings = df.loc[df['overall'] == 5.0][0:80000]

df2 = pd.concat([one_star_ratings, two_star_ratings, three_star_ratings, four_star_ratings,
five_star_ratings])

This works, but it is a naive solution.

My question

I will encounter this issue frequently while working with datasets, and I am trying to find a better solution. Assume I had 100 categories, and not just 5. How can I better solve this problem without writing 100+ lines of code to do it?

Body:
You could use groupby().head() for this:

n_sample = 80000
df2 = df.groupby('overall').head(n_sample)

If you want to sample randomly:

df2 = df.sample(frac=1).groupby('overall').head(n_sample)

You can also use sample to randomly select the data:

df2 = df.groupby('overall')apply(lambda x: x.sample(n=n_sample))


问:
Controlling mouse with Python
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>

答:
very easy
1- install pakage :

```<code>pip install mouse
</code>```

2- add library to project :

```<code>import mouse
</code>```

3- use it for example :

```<code>mouse.right_click()
</code>```

in this url describe all function that you can use it :

https://github.com/boppreh/mouse

Title: Controlling mouse with Python

Body:
very easy
1- install pakage :

pip install mouse

2- add library to project :

import mouse

3- use it for example :

mouse.right_click()

in this url describe all function that you can use it :

https://github.com/boppreh/mouse


问:
Show JSON as TableView Section and TableView row in Swift 4.2 without Decodable?
I have below JSON response array with key "events"

```<code>{
  "events": [
 {
  "name": "event foo",
  "date": "2020-05-22",
  "time": "7:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test "
},
{
  "name": "event bar",
  "date": "2020-05-22",
  "time": "7:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test2"
},
{
  "name": "event foobar",
  "date": "2020-05-24",
  "time": "11:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test3"
},
{
  "name": "event foobar",
  "date": "2020-05-24",
  "time": "11:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test3"
 }
]
}
</code>```

I want to show above JSON response in TableView as :
"date" key should be TableView Section grouped and Rows as "name" key

Could some help me how will i do that thanks in advance.

答:
First things first, you'll need to create a Model, so that you can transform your JSON into usable objects. To do that, good practice is to use the Codable protocol, which will automatically map your JSON keys to a struct/class variable

```<code>struct Event: Codable {
    var name: String!
    var date: String!
    var time: String!
    var am_or_pm: String!
    var day: String!
    var description: String!
}

struct Events: Codable {
    var events: [Event]!
}
</code>```

Now that you have the model that will be generated from the JSON, you need to decode your JSON into your model. There are plenty of ways to do it, I like to use JSONEncoder/JSONDecoder.
So, let's say your JSON string is stored in the variable myJsonString, you would need to

```<code>if let jsonData = myJsonString.data(using: .utf8) {
    do {
        let events = try JSONDecoder().decode(Events.self, from: jsonData)
    } catch {
        print("Error decoding json!", error.localizedDescription)
    }
} else {
    print("Failed to get bytes from string!")
}
</code>```

We can, now turn that code block into a function that returns Events, or nil, if it fails to decode the string.

```<code>func getEvents(from jsonString: String) -> Events? {
    guard let jsonData = myJsonString.data(using: .utf8) else { return nil }
    return try? JSONDecoder().decode(Events.self, from: jsonData)
}
</code>```

Cool! We can easily get our events based on a JSON string now! All we gotta do next is populate the tableView!
To do that, we can create a few functions in our Events struct that will return just what we need to populate our section. The first function will return the sections for our tableView, and the second will return all items for a given section. Let's modify the Events struct

```<code>struct Events: Codable {
    var events: [Event]!

    func getSections() -> [String] {
        return Array(Set(self.events.map { $0.date }))
    }

    func getItems(forSection dateSection: String) -> [Section] {
        return self.events.filter {$0.date == dateSection}
    }
}
</code>```

Now, in your TableView datasource class, you need to use the model we created. I`ll do an example for you

```<code>class YourTableView: UIViewController, UITableViewDataSource, UITableViewDelegate {
    // This is loaded from the getEvents function!
    var events: Events!

   func numberOfSections (in tableView: UITableView) -> Int {
        return self.events.getSections().count
    }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let dateSection = self.events.getSections()[section]
        return self.events.getItems(forSection: dateSection ).count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dateSection = self.events.getSections()[indexPath.section]
        let currentEvent = self.getItems(forSection: dateSection)

         // Build your cell using currentEvent
    }
}
</code>```

You are probably getting those JSONs from the web, so you have to handle a "loading" state, where you are returning the JSON from the API. That can easily be done by turning the events var into a optional, setting it when you get your JSON and reloading data from your tableView

Body:
I have below JSON response array with key "events"

{
  "events": [
 {
  "name": "event foo",
  "date": "2020-05-22",
  "time": "7:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test "
},
{
  "name": "event bar",
  "date": "2020-05-22",
  "time": "7:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test2"
},
{
  "name": "event foobar",
  "date": "2020-05-24",
  "time": "11:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test3"
},
{
  "name": "event foobar",
  "date": "2020-05-24",
  "time": "11:00",
  "am_or_pm": "PM",
  "day": "Saturday",
  "description": "test3"
 }
]
}

I want to show above JSON response in TableView as :
"date" key should be TableView Section grouped and Rows as "name" key

Could some help me how will i do that thanks in advance.

Body:
First things first, you'll need to create a Model, so that you can transform your JSON into usable objects. To do that, good practice is to use the Codable protocol, which will automatically map your JSON keys to a struct/class variable

struct Event: Codable {
    var name: String!
    var date: String!
    var time: String!
    var am_or_pm: String!
    var day: String!
    var description: String!
}

struct Events: Codable {
    var events: [Event]!
}

Now that you have the model that will be generated from the JSON, you need to decode your JSON into your model. There are plenty of ways to do it, I like to use JSONEncoder/JSONDecoder.
So, let's say your JSON string is stored in the variable myJsonString, you would need to

if let jsonData = myJsonString.data(using: .utf8) {
    do {
        let events = try JSONDecoder().decode(Events.self, from: jsonData)
    } catch {
        print("Error decoding json!", error.localizedDescription)
    }
} else {
    print("Failed to get bytes from string!")
}

We can, now turn that code block into a function that returns Events, or nil, if it fails to decode the string.

func getEvents(from jsonString: String) -> Events? {
    guard let jsonData = myJsonString.data(using: .utf8) else { return nil }
    return try? JSONDecoder().decode(Events.self, from: jsonData)
}

Cool! We can easily get our events based on a JSON string now! All we gotta do next is populate the tableView!
To do that, we can create a few functions in our Events struct that will return just what we need to populate our section. The first function will return the sections for our tableView, and the second will return all items for a given section. Let's modify the Events struct

struct Events: Codable {
    var events: [Event]!

    func getSections() -> [String] {
        return Array(Set(self.events.map { $0.date }))
    }

    func getItems(forSection dateSection: String) -> [Section] {
        return self.events.filter {$0.date == dateSection}
    }
}

Now, in your TableView datasource class, you need to use the model we created. I`ll do an example for you

class YourTableView: UIViewController, UITableViewDataSource, UITableViewDelegate {
    // This is loaded from the getEvents function!
    var events: Events!

   func numberOfSections (in tableView: UITableView) -> Int {
        return self.events.getSections().count
    }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let dateSection = self.events.getSections()[section]
        return self.events.getItems(forSection: dateSection ).count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dateSection = self.events.getSections()[indexPath.section]
        let currentEvent = self.getItems(forSection: dateSection)

         // Build your cell using currentEvent
    }
}

You are probably getting those JSONs from the web, so you have to handle a "loading" state, where you are returning the JSON from the API. That can easily be done by turning the events var into a optional, setting it when you get your JSON and reloading data from your tableView


问:
Too many connections using Hibernate and mysql
I am using Hibernate 3 and mysql sever 5.5 for myweb application with spring 3.0

I am getting exception as Too many connections......

My java file where I create session is as follows:

```<code>public class DBConnection {

    static{

    }

    public Session getSession(){

         Session session = null;
         SessionFactory sessionFactory= null;
         sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        return session;

    }

}
</code>```

and I call this method where I need session

as

```<code>Session session=new DBConnection().getSession();
</code>```

and after

```<code>transaction.commit();
</code>```

I close session by using

```<code>session.close();
</code>```

please help me in solving problem.......

my hibernate.cfg.xml is :

```<code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
<property name="hibernate.connection.username">root</property>

  <property name="hibernate.connection.password">lax</property>
  <property name="hibernate.connection.pool_size">100</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name=""></property>

  <property name="hibernate.connection.release_mode">on_close</property>

</session-factory>
</hibernate-configuration>
</code>```

答:
I was facing the same issues with Hibernate mysql conenctions
The following two things helped fix my connection problems

```<code>import javax.inject.Singleton;

@Singleton
public class DBConnection {
private static SessionFactory factory;
static public Session getSession() {
    if (factory == null) {
        System.out.println("--------New connection----");

        factory = new Configuration().configure("hibernate.cfg.xml")
                .addAnnotatedClass(SomeClass.class)
                .buildSessionFactory();
    }
    //System.out.println("--------old connection----");

    return factory.openSession();
}

    // Call this during shutdown
    public static void close() {
        factory.close();
    }
}
</code>```

Create a singleton class for getting a DBConnection

Do not forget to perform session.close() when your query is complete

Also in "hibernate.cfg.xml"
add this line

<hibernate-configuration>
    <session-factory>
    ....
    <property name="connection.pool_size">100</property>
    ....
    </session-factory>
</hibernate-configuration>

under

Body:
I am using Hibernate 3 and mysql sever 5.5 for myweb application with spring 3.0

I am getting exception as Too many connections......

My java file where I create session is as follows:

public class DBConnection {

    static{

    }

    public Session getSession(){

         Session session = null;
         SessionFactory sessionFactory= null;
         sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        return session;

    }

}

and I call this method where I need session

as

Session session=new DBConnection().getSession();

and after

transaction.commit();

I close session by using

session.close();

please help me in solving problem.......

my hibernate.cfg.xml is :

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
<property name="hibernate.connection.username">root</property>

  <property name="hibernate.connection.password">lax</property>
  <property name="hibernate.connection.pool_size">100</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name=""></property>

  <property name="hibernate.connection.release_mode">on_close</property>

</session-factory>
</hibernate-configuration>

Body:
I was facing the same issues with Hibernate mysql conenctions
The following two things helped fix my connection problems

import javax.inject.Singleton;

@Singleton
public class DBConnection {
private static SessionFactory factory;
static public Session getSession() {
    if (factory == null) {
        System.out.println("--------New connection----");

        factory = new Configuration().configure("hibernate.cfg.xml")
                .addAnnotatedClass(SomeClass.class)
                .buildSessionFactory();
    }
    //System.out.println("--------old connection----");

    return factory.openSession();
}

    // Call this during shutdown
    public static void close() {
        factory.close();
    }
}

Create a singleton class for getting a DBConnection

Do not forget to perform session.close() when your query is complete

Also in "hibernate.cfg.xml"
add this line

<hibernate-configuration>
    <session-factory>
    ....
    <property name="connection.pool_size">100</property>
    ....
    </session-factory>
</hibernate-configuration>

under


问:
How to vertically stretch an image responsively?
I am trying to implement a sidemenu with a background image but I don't understand how to make it responsive also vertically...
I have this image https://ibb.co/Pzyyyh2 whose size is 320x1000px. It's a very tall white image that a certain point becomes black.
I'd like to have this black detail to stay always at a certain point of my sidemenu (the transition from white to black should start before the social link part).

As you can see here, on iPhone X emulator, it works as expected: https://ibb.co/C7Nm6b7.
While on another device such as Moto G4 this happens: https://ibb.co/S7tQwJV

答:
You don't need the white part of the image, if what you're trying to show is the black, then just use the black. If your image is an svg, it will always expand/contract properly, without visible pixelation. The rest of the footer should have a background-color equal to that of your img.

If you want to use skew, then make a first div (the parent/wrapper), then place it right before your footer area. Then inside the wrapper, add the skew-div. Make the parent have overflow:hidden so the excess of the skew-siv  doesn't become visible past the borders of the parent.

Like this:

Then, inside your 'magic-div', you'd have the following:

The parent gets width: 100%; and overflow:hidden;. The child skew div inside gets width:100%; too. If you're using background with an svg as suggested earlier, the background-size rule should be 100% auto or cover, depending on the scenario (the widths you're covering + the angle of your skew). Give it a try and let us know how it went.


问:
Add an empty div on a certain index of a v-for loop
I'm passing in an array of product items via a computed variable in to a collection item component on a collection page. After the third product I'd like there to be an empty collection item, ie. a collection item template but with no product content inside. If anyone would have any ideas how I could achieve this in Vue.js I'd be most grateful.</p>

```<code>collection page:

        <collection-item
          v-for="product in products"
          :collection-item="product"
        ></collection-item>
</code>```

答:
you can wrap your <collection-item inside a template, and v-for loop that, then add a v-if condition onto your collection-item

```<code><template>
  <section>
    <template v-for="(row, index) in rows">
      <collection v-if="index !== 3" :key="index"></collection>
      <div v-else :key="index">something else if needed or remove</div>
    </template>
  </section>
</template>
</code>```

codesandbox:

https://codesandbox.io/s/cocky-wood-qglqe?file=/pages/index.vue:0-216

Body:
I'm passing in an array of product items via a computed variable in to a collection item component on a collection page. After the third product I'd like there to be an empty collection item, ie. a collection item template but with no product content inside. If anyone would have any ideas how I could achieve this in Vue.js I'd be most grateful.

collection page:

        <collection-item
          v-for="product in products"
          :collection-item="product"
        ></collection-item>

Body:
you can wrap your <collection-item inside a template, and v-for loop that, then add a v-if condition onto your collection-item

<template>
  <section>
    <template v-for="(row, index) in rows">
      <collection v-if="index !== 3" :key="index"></collection>
      <div v-else :key="index">something else if needed or remove</div>
    </template>
  </section>
</template>

codesandbox:

https://codesandbox.io/s/cocky-wood-qglqe?file=/pages/index.vue:0-216


问:
What is the difference between ":" and "=" for default values of named arguments in class constructors and function arguments
Consider an animal class, which has two fields - totalLegs and type.

class Animal {
  final int totalLegs;
  final String type;
}
```

<p>Let's say that <code>totalLegs</code> defaults to 4 and <code>type</code> default to "cat". We can set the default values for the fields two different ways:</p>

<ol>
<li>Using "="</li>
</ol>

<pre class="lang-dart prettyprint-override"><code>class Animal {
  ...

  Animal({this.totalLegs = 4, this.type = 'cat'});
}
</code>```

Using ":"

class Animal {
  ...

  Animal({this.totalLegs: 4, this.type: 'cat'});
}
```

Do both ways behave the same? What is the difference? Or, if there is no difference, why isn't there only one way to set default values?

答: They are the same, but the : one was deprecated. It was replaced with =. I think the deprecated one wasn't removed for some backward compatibility reasons. But the = is now recommended to use instead of :, and the future of it is not assured. It could get removed in the future versions of Dart, or it won't.

Body:
Consider an animal class, which has two fields - totalLegs and type.

class Animal {
  final int totalLegs;
  final String type;
}

Let's say that totalLegs defaults to 4 and type default to "cat". We can set the default values for the fields two different ways:

Using "="

class Animal {
  ...

  Animal({this.totalLegs = 4, this.type = 'cat'});
}

Using ":"

class Animal {
  ...

  Animal({this.totalLegs: 4, this.type: 'cat'});
}

Do both ways behave the same? What is the difference? Or, if there is no difference, why isn't there only one way to set default values?


问:
How do I query in GQL using the entity key
How do I write a query against the entity key using GQL in the Google App Engine Data Viewer ?

In the viewer, the first column (Id/Name) displays as name=_1, in the detail view it shows the key as

```<code>Decoded entity key: Programme: name=_1
Entity key: agtzcG9...................
</code>```

This query does not work:

```<code>SELECT * FROM Programme where name = '_1'
</code>```

答:
For numeric IDs, a form similar to the query-by-name works:

```<code>SELECT * from Programme where __key__ = KEY('Programme', 1234567)
</code>```

I found this form especially useful in the Admin Console.

ContentLicense: CC BY-SA 2.5

Body:
How do I write a query against the entity key using GQL in the Google App Engine Data Viewer ?

In the viewer, the first column (Id/Name) displays as name=_1, in the detail view it shows the key as

Decoded entity key: Programme: name=_1
Entity key: agtzcG9...................

This query does not work:

SELECT * FROM Programme where name = '_1'

Body:
For numeric IDs, a form similar to the query-by-name works:

SELECT * from Programme where __key__ = KEY('Programme', 1234567)

I found this form especially useful in the Admin Console.


问:
DolphinDB database select last N rows
I have a DolphinDB segment table t, and I would like to do a query like this:

```<code>select LAST N ROWS from t context by sym
</code>```

How do I write this query correctly?

答:
A negative limit number in conjunction with context-by clause will output last N rows for each group.</p>

```<code>select * from t context by sym limit -5
</code>```

Title: DolphinDB database select last N rows

Body:
I have a DolphinDB segment table t, and I would like to do a query like this:

select LAST N ROWS from t context by sym

How do I write this query correctly?

Body:
A negative limit number in conjunction with context-by clause will output last N rows for each group.

select * from t context by sym limit -5


问:
how can i print a condition in blade from jquery via ajax?
i´m trying to make a condition via ajax in my code wich show a button when user is 'admin', simple in blade, but it doesn´t work printing from jquery.

-- js code --

```<code>codigo += '<tr>...<td class=""><input name="incertidumbre'+[i]+'" class="pl-2 font-weight-bolder sinbordeimpar" value="'+puntos[i].incertidumbre+'" disabled></td>';
        codigo += @if(Auth::user() && Auth::user()->rol == "admin")
        codigo += '<td><input class="btn btn-sm btn-outline-secondary" type="button" value="Editar" name="btnedit_Punto'+puntos[i].id+'" id="btnGuardar_Punto'+puntos[i].id+'">';
        codigo += '<input hidden="hidden" class="btn btn-sm btn-outline-secondary" type="button" value="Guardar" name="btnedit_Punto'+puntos[i].id+'" id="btnGuardar_Punto'+puntos[i].id+'"></td>';
        codigo += @endif
        codigo += '</tr>'
</code>```

}

```<code>      $('#prueba').html(codigo);
    };
</code>```

result is "Uncaught SyntaxError: Invalid or unexpected token"

How should i send "var codigo" to blade view for a correct condition in it??

答:
There is solution you can use.
Change your js file extension to be blade.php. The rest of the content can be the same, remember to add in <?php
Then in your javascript code portion, you can now assign whatever you want to be variable such as const isAdmin = {{Auth::user()->rol=='admin'}}.
Also, bear in mind that you have to use @include now instead of adding as ascript

Body:
i´m trying to make a condition via ajax in my code wich show a button when user is 'admin', simple in blade, but it doesn´t work printing from jquery.

-- js code --

codigo += '
...<input name="incertidumbre'+[i]+'" class="pl-2 font-weight-bolder sinbordeimpar" value="'+puntos[i].incertidumbre+'" disabled>	';
        codigo += @if(Auth::user() && Auth::user()->rol == "admin")
        codigo += '<input class="btn btn-sm btn-outline-secondary" type="button" value="Editar" name="btnedit_Punto'+puntos[i].id+'" id="btnGuardar_Punto'+puntos[i].id+'">';
        codigo += '<input hidden="hidden" class="btn btn-sm btn-outline-secondary" type="button" value="Guardar" name="btnedit_Punto'+puntos[i].id+'" id="btnGuardar_Punto'+puntos[i].id+'">	';
        codigo += @endif
        codigo += '
'

}

      $('#prueba').html(codigo);
    };

result is "Uncaught SyntaxError: Invalid or unexpected token"

How should i send "var codigo" to blade view for a correct condition in it??


问:
Which template tag to include an image stored using django-storage[dropbox]
I try to build my first application with Django, and use django-storage to store my media on dropbox:

```<code>DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
DROPBOX_OAUTH2_TOKEN = ---- mytoken ----
DROPBOX_ROOT_PATH = 'media'
</code>```

It works well to upload and display the images using the models directly (e.g. {{ object.photo.url }} in the html template works)

However, how can I create a link to the image in the template if I have no object.

Something like

```<code><img  src="{{media_url}}myimage.jpg">
</code>```

does not work as it links to localhost (on my local server). Is it needed to redefine media_url or is there another tag to use?

答:
I am not sure about the existence of any tag to use in the case of accessing the image from dropbox. I would solve this issue using custom filters in Django since it is the case of distinguishing between local and remote and forming the right URL to pass to the src attribute.

You can read from the docs here on how custom filter works. Essentially, you would need a custom function that prepends the remote/local URL.

Using a function like this for e.g.

```<code>@register.filter
@stringfilter
def prepend(str):
    url = "" #defien your remote url here
    return "{}{}".format(url, str)
</code>```

You then make calls from the template to this function which would give you the correct url (as you defined it).

Body:
I try to build my first application with Django, and use django-storage to store my media on dropbox:

DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
DROPBOX_OAUTH2_TOKEN = ---- mytoken ----
DROPBOX_ROOT_PATH = 'media'

It works well to upload and display the images using the models directly (e.g. {{ object.photo.url }} in the html template works)

However, how can I create a link to the image in the template if I have no object.

Something like

does not work as it links to localhost (on my local server). Is it needed to redefine media_url or is there another tag to use?

Body:
I am not sure about the existence of any tag to use in the case of accessing the image from dropbox. I would solve this issue using custom filters in Django since it is the case of distinguishing between local and remote and forming the right URL to pass to the src attribute.

You can read from the docs here on how custom filter works. Essentially, you would need a custom function that prepends the remote/local URL.

Using a function like this for e.g.

@register.filter
@stringfilter
def prepend(str):
    url = "" #defien your remote url here
    return "{}{}".format(url, str)

You then make calls from the template to this function which would give you the correct url (as you defined it).


问:
Pandas - Join multiple rows into one row with more columns
I've done some searching and can't find this.  I may not be using the correct wording.

This is what I want to do:

```<code>id, C1, C2
0,   1,  2
1,   2,  3
2,   2,  4
3,   5,  6
4,   7,  8
5,   9, 10
6,  11, 12
7,  13, 14
</code>```

Into this (x rows (in this case 3) into 1 row with multiple columns):

```<code>id, C1, C2, C1_1, C2_1, C1_2, C2_2
0,   1,  2,    3,    4,    5,    6
1,   7,  8,    9,   10,   11,   12
2,  13, 14,  Nan,  Nan,  NaN,  NaN
</code>```

it's okay if i need to drop the rows that would result in NaN.

I could write some kind of loop, but it seems like there would be a good pandas way to this, i'm just not finding it.

答:
We need create two type id , one by mod one by cumcount, then do pivot_table

```<code>df.id=df.id//3+1
df['id1']=df.groupby('id').cumcount()

s=df.pivot_table(index='id1',columns='id',values=['C1','C2'],aggfunc='sum').sort_index(level=1,axis=1)
      C1   C2   C1    C2    C1    C2
id     1    1    2     2     3     3
id1
0    1.0  2.0  5.0   6.0  11.0  12.0
1    2.0  3.0  7.0   8.0  13.0  14.0
2    2.0  4.0  9.0  10.0   NaN   NaN
</code>```

Body:
I've done some searching and can't find this.  I may not be using the correct wording.

This is what I want to do:

id, C1, C2
0,   1,  2
1,   2,  3
2,   2,  4
3,   5,  6
4,   7,  8
5,   9, 10
6,  11, 12
7,  13, 14

Into this (x rows (in this case 3) into 1 row with multiple columns):

id, C1, C2, C1_1, C2_1, C1_2, C2_2
0,   1,  2,    3,    4,    5,    6
1,   7,  8,    9,   10,   11,   12
2,  13, 14,  Nan,  Nan,  NaN,  NaN

it's okay if i need to drop the rows that would result in NaN.

I could write some kind of loop, but it seems like there would be a good pandas way to this, i'm just not finding it.

Body:
We need create two type id , one by mod one by cumcount, then do pivot_table

df.id=df.id//3+1
df['id1']=df.groupby('id').cumcount()

s=df.pivot_table(index='id1',columns='id',values=['C1','C2'],aggfunc='sum').sort_index(level=1,axis=1)
      C1   C2   C1    C2    C1    C2
id     1    1    2     2     3     3
id1
0    1.0  2.0  5.0   6.0  11.0  12.0
1    2.0  3.0  7.0   8.0  13.0  14.0
2    2.0  4.0  9.0  10.0   NaN   NaN


问:
import android.support.v4.app.ActivityCompat;
This is the error i am seeing when i add  "simple_permissions" package. How can i fix this? I recently upgraded flutter and it used to work very well before the upgrade.
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:9: error: cannot find symbol
import android.support.v4.app.ActivityCompat;</p>

```<code>/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:9: error: cannot find symbol
import android.support.v4.app.ActivityCompat;

  symbol:   class ActivityCompat
  location: package android.support.v4.app
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:10: error: package android.support.v4.content does not exist
import android.support.v4.content.ContextCompat;
                                 ^
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:156: error: cannot find symbol
        ActivityCompat.requestPermissions(activity, perm, 0);
        ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:163: error: cannot find symbol
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(activity, permission);
  symbol:   variable ContextCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:171: error: cannot find symbol
            if (ActivityCompat.shouldShowRequestPermissionRationale(registrar.activity(), permission)) {
                ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:175: error: cannot find symbol
                if (ActivityCompat.checkSelfPermission(registrar.context(), permission) == PackageManager.PERMISSION_GRANTED) {
                    ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':simple_permissions:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
[!] Flutter tried to create the file `android/settings_aar.gradle`, but failed.
To manually update `settings.gradle`, follow these steps:
    1. Copy `settings.gradle` as `settings_aar.gradle`
    2. Remove the following code from `settings_aar.gradle`:
        def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
        def properties = new Properties()
        assert localPropertiesFile.exists()
        localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
        def flutterSdkPath = properties.getProperty("flutter.sdk")
        assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
        apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
Exception: Please create the file and run this command again.
Exited (sigterm)
</code>```

答:
I suggest you to check the package before using it.

It seems that simple_permissions is outdated and this package hasn't been updated since 2018 and its repository is gone from github, consider using other package like permission_handler.

Cheers.

Body:
This is the error i am seeing when i add  "simple_permissions" package. How can i fix this? I recently upgraded flutter and it used to work very well before the upgrade.
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:9: error: cannot find symbol
import android.support.v4.app.ActivityCompat;

/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:9: error: cannot find symbol
import android.support.v4.app.ActivityCompat;

  symbol:   class ActivityCompat
  location: package android.support.v4.app
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:10: error: package android.support.v4.content does not exist
import android.support.v4.content.ContextCompat;
                                 ^
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:156: error: cannot find symbol
        ActivityCompat.requestPermissions(activity, perm, 0);
        ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:163: error: cannot find symbol
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(activity, permission);
  symbol:   variable ContextCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:171: error: cannot find symbol
            if (ActivityCompat.shouldShowRequestPermissionRationale(registrar.activity(), permission)) {
                ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
/root/flutter/.pub-cache/hosted/pub.dartlang.org/simple_permissions-0.1.9/android/src/main/java/com/ethras/simplepermissions/SimplePermissionsPlugin.java:175: error: cannot find symbol
                if (ActivityCompat.checkSelfPermission(registrar.context(), permission) == PackageManager.PERMISSION_GRANTED) {
                    ^
  symbol:   variable ActivityCompat
  location: class SimplePermissionsPlugin
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':simple_permissions:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
[!] Flutter tried to create the file `android/settings_aar.gradle`, but failed.
To manually update `settings.gradle`, follow these steps:
    1. Copy `settings.gradle` as `settings_aar.gradle`
    2. Remove the following code from `settings_aar.gradle`:
        def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
        def properties = new Properties()
        assert localPropertiesFile.exists()
        localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
        def flutterSdkPath = properties.getProperty("flutter.sdk")
        assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
        apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
Exception: Please create the file and run this command again.
Exited (sigterm)