问:
How to define and access the database postgresql like flask sample code
I'm new use python flask, I want connected to postgresql use code like flask sample in this link, but in code sample use sqlite3. I try to search code sample and make me confused because every sample use different approach. This my code run but when use CLI to initialize database error.

```<code>Error: No such command "init-db".
</code>```

My structure file

This my code:

run.py

```<code>#run.py
import os

from smart_app import create_app

app = create_app()

if __name__ == '__main__':
    app.run()
</code>```

init.py

```<code>#__init__.py
from flask import Flask

def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)

    # load default configuration
    app.config.from_object('config.default')

    # load the configuration from the instance folder
    app.config.from_pyfile('config.py')

    # Load the file specified by the APP_CONFIG_FILE environment variable
    # Variables defined here will override those in the default configuration
    app.config.from_envvar('APP_CONFIG_FILE')

    # Connect to database
    from . import db
    db.init_app(app)

    return app
</code>```

db.py

db.py

import click
from flask import current_app, g
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy

```<code># db = SQLAlchemy()

def get_db():
    if 'db' not in g:
        g.db = SQLAlchemy()

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database')

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)
</code>```

答:
If you familiar with SQL, use the psycopg2 to connect to your postgresql database.

Or if you want use ORM to operate the database in flask, you can use flask_sqlalchemy.

Body:
I'm new use python flask, I want connected to postgresql use code like flask sample in this link, but in code sample use sqlite3. I try to search code sample and make me confused because every sample use different approach. This my code run but when use CLI to initialize database error.

Error: No such command "init-db".

My structure file

This my code:

run.py

#run.py
import os

from smart_app import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

init.py

#__init__.py
from flask import Flask

def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)

    # load default configuration
    app.config.from_object('config.default')

    # load the configuration from the instance folder
    app.config.from_pyfile('config.py')

    # Load the file specified by the APP_CONFIG_FILE environment variable
    # Variables defined here will override those in the default configuration
    app.config.from_envvar('APP_CONFIG_FILE')

    # Connect to database
    from . import db
    db.init_app(app)

    return app

db.py

db.py

import click
from flask import current_app, g
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy

# db = SQLAlchemy()

def get_db():
    if 'db' not in g:
        g.db = SQLAlchemy()

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database')

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)


来源: stackexchange

问:
Left alignment of Material-UI dialog buttons
I have three buttons in a Dialog like so:

The JSX is

        <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} >
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose()} >
            Clear
          </Button>
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose()} >
            Cancel
          </Button>
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose(this.state.selectedValue)} >
            Select
          </Button>
        </DialogActions>```

The 'buttonRoot' style simply determines the button coloring. How to I left align the 'Clear' button so it sits on the left? It seems the buttons are each in a div with a MuiDialogActions-action class.

答:
Just use divider element with flex: 1 0 0 CSS style:

<DialogActions>
  <Button>
    Left
  </Button>
  <Button>
    Buttons
  </Button>

  <Button>
    Right
  </Button>
  <Button>
    Buttons
  </Button>
</DialogActions>
```

ContentLicense: CC BY-SA 3.0

Body:
I have three buttons in a Dialog like so:

The JSX is

        <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} >
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose()} >
            Clear
          </Button>
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose()} >
            Cancel
          </Button>
          <Button classes={{ root: this.props.classes.buttonRoot }} size="small" onClick={() => this.props.handleDialogClose(this.state.selectedValue)} >
            Select
          </Button>
        </DialogActions>

The 'buttonRoot' style simply determines the button coloring. How to I left align the 'Clear' button so it sits on the left? It seems the buttons are each in a div with a MuiDialogActions-action class.

Body:
Just use divider element with flex: 1 0 0 CSS style:

<DialogActions>
  <Button>
    Left
  </Button>
  <Button>
    Buttons
  </Button>
  <div style={{flex: '1 0 0'}} />
  <Button>
    Right
  </Button>
  <Button>
    Buttons
  </Button>
</DialogActions>

ContentLicense: CC BY-SA 4.0


问:
UX and Security - The best way to display the ID of object to user
If you have an experience in UX or Security, please answer this question.
I am working in some project and we need to show the object id to the user.
So all edit form's has the id, the client ask for this --".

My doubt is, what is the best way to show the id in the form?

I did this way, the ID is just a text:

But some one is showing the ID as a disable input, but this seems wrong to me.

Can some tell me the best way to show the ID ? Maybe a third option.
And please explain your answer, I need to convince my team.

Thank's!!!!

答:
Of course the correct solution is not to show the ID of an object. IDs (along with object) are internal technical terminology, the user does not care that you use an id to uniquely refer to an object in a database.

Just remove the ID field entirely.


问:
Angular material table - this._elementRef is undefined
i was trying to use angular material table and I found the following error:

```<code>    ERROR TypeError: "this._elementRef is undefined"
    ERROR CONTEXT
</code>```

on the following line:

    <mat-table [dataSource]="data" class="example-table"
               matSort matSortActive="created" matSortDisableClear      matSortDirection="desc">
```

<p>I've noticed that when I remove the mat-table tag the error disappears.</p>

<blockquote>
  <p>note: My app module is already importing MatTableModule</p>
</blockquote>

<p>Here is my entire table code:</p>

<p>html</p>

<pre class="lang-html prettyprint-override"><code>    (...)

    <mat-table [dataSource]="data" class="example-table"
           matSort matSortActive="created" matSortDisableClear matSortDirection="desc">
      <!-- CRM Column -->
      <ng-container matColumnDef="crm">
        <th mat-header-cell *matHeaderCellDef>CRM</th>
        <td mat-cell *matCellDef="let row">{{row.crm}}</td>
      </ng-container>

      <!-- CPF Column -->
      <ng-container matColumnDef="cpf">
        <th mat-header-cell *matHeaderCellDef>CPF</th>
        <td mat-cell *matCellDef="let row">{{row.cpf}}</td>
      </ng-container>

      <ng-container matColumnDef="especializacao">
        <th mat-header-cell *matHeaderCellDef>Especialização</th>
        <td mat-cell *matCellDef="let row">{{row.especializacao}}</td>
      </ng-container>

      <!-- Nome Column -->
      <ng-container matColumnDef="nome">
        <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear></th>
        <td mat-cell *matCellDef="let row">{{row.nome}}</td>
      </ng-container>

      <!-- Telefone Column -->
      <ng-container matColumnDef="telefone">
        <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear></th>
        <td mat-cell *matCellDef="let row">{{row.telefone}}</td>
      </ng-container>

      <!-- Data nascismento Column -->
      <ng-container matColumnDef="data_de_nascimento">
        <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear></th>
        <td mat-cell *matCellDef="let row">{{row.data_de_nascimento}}</td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </mat-table>

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

js

  // (...)

  data: MedicData[] = [];

  // (...)

  export interface MedicData {
    crm: string;
    cpf: string;
    especializacao: string;
    nome: string;
    telefone: string;
    data_de_nascimento: string;
  }
```

答:
I don't know if this is causing the exact error, but one thing I notice is that you are using the directive mat-table as the element name <mat-table></mat-table>. This is perfectly fine, but then you use the element names 	 instead of <mat-cell></mat-cell> etc. A  and

 can't exist without a parent
, so it is most likely causing problems.

Body:
i was trying to use angular material table and I found the following error:

    ERROR TypeError: "this._elementRef is undefined"
    ERROR CONTEXT

on the following line:

    <mat-table [dataSource]="data" class="example-table"
               matSort matSortActive="created" matSortDisableClear      matSortDirection="desc">

I've noticed that when I remove the mat-table tag the error disappears.

note: My app module is already importing MatTableModule

Here is my entire table code:

html

    (...)

    <mat-table [dataSource]="data" class="example-table"
           matSort matSortActive="created" matSortDisableClear matSortDirection="desc">

      <ng-container matColumnDef="crm">
        CRM
        {{row.crm}}
      </ng-container>

      <ng-container matColumnDef="cpf">
        CPF
        {{row.cpf}}
      </ng-container>

      <ng-container matColumnDef="especializacao">
        Especialização
        {{row.especializacao}}
      </ng-container>

      <ng-container matColumnDef="nome">

        {{row.nome}}
      </ng-container>

      <ng-container matColumnDef="telefone">

        {{row.telefone}}
      </ng-container>

      <ng-container matColumnDef="data_de_nascimento">

        {{row.data_de_nascimento}}
      </ng-container>

    </mat-table>

    (...)

js

  // (...)

  data: MedicData[] = [];

  // (...)

  export interface MedicData {
    crm: string;
    cpf: string;
    especializacao: string;
    nome: string;
    telefone: string;
    data_de_nascimento: string;
  }

Body: I don't know if this is causing the exact error, but one thing I notice is that you are using the directive mat-table as the element name <mat-table></mat-table>. This is perfectly fine, but then you use the element names <td></td> instead of <mat-cell></mat-cell> etc. A <td> and <tr></tr> can't exist without a parent <table>, so it is most likely causing problems.


问:
How can I remove this element from the list?
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

```<code>list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)
</code>```

Body:
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)

Body:
Use a list comprehension to filter out the unwanted elements.

list1 = [x for x in list1 if 'Americano' not in x]

Results:

>>> list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]
>>>
>>>
>>> list1 = [x for x in list1 if 'Americano' not in x]
>>> list1
[['4', 'Smoothie_queen', '4', '12000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]
>>>


问:
How to delete one specific Page of a ms-word document (docx) with POI?
I'm finding some ways to delete one specific page in my docx template, prefer to using POI. Is there any methods could do this?

I can get XWPFDocument object from my template file, but I don't know how to get specific "Page object", such like getPage(int pageIndex)?

XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(templateFile));
```

答: OK, I'm gonna change the template so that I can mark all specific content in XWPFTable objects. Then, to remove row might be a reluctant way.</p>


问:
Display MySQL "GROUP BY" results correctly
I cannot seem to get this query displayed properly. Here is the code:

```<code>$select_stats = "SELECT
  c.ResponderID
  , COUNT(MsgID)
  , a.SubscriberID
  , CanReceiveHTML
  , EmailAddress
FROM InfResp_msglogs AS a
  , InfResp_subscribers AS b
  , InfResp_responders AS c
WHERE b.CanReceiveHTML = 1
  AND c.owner='".$_SESSION['logged_user_id']."'
  AND c.ResponderID = b.ResponderID
  AND b.SubscriberID = a.SubscriberID
GROUP BY c.ResponderID";

//echo $select_result;

while($row = mysql_fetch_array($select_result))
{
    $messages = $row['COUNT(MsgID)'];
    $campaign = $row['ResponderID'];
    $subscriber = $row['SubscriberID'];
    $subscriber_email = $row['EmailAddress'];

    echo "<br>Campaign = ". $campaign ."
          <br>Sent emails count = ". $messages ."
          <br>Subscriber Nr. = ". $subscriber ."
          <br>Subscriber Email = ". $subscriber_email ."<br>";
     }
</code>```

This is the output:

```<code>Campaign = 10
Sent emails count = 109
Subscriber Nr. = 95
Subscriber Email = timothy@gmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com
</code>```

As there are three different subscribers under campaign no.10 and one under campaign no.11 in the db (each with its own email addresses of course), I would like the output to be:

```<code>Campaign = 10
Sent emails count = 109
Subscriber Nr. = 92
94
95
Subscriber Email = timothy@gmail.com
anthony@yahoo.com
josie@hotmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com
</code>```

Thanks.

答:
You need group_concat for this:</p>

```<code>... SELECT c.ResponderID, COUNT(MsgID), a.SubscriberID, CanReceiveHTML,
group_concat(EmailAddress ORDER BY EmailAddress DESC SEPARATOR ' ') ...
</code>```

Body:
I cannot seem to get this query displayed properly. Here is the code:

$select_stats = "SELECT
  c.ResponderID
  , COUNT(MsgID)
  , a.SubscriberID
  , CanReceiveHTML
  , EmailAddress
FROM InfResp_msglogs AS a
  , InfResp_subscribers AS b
  , InfResp_responders AS c
WHERE b.CanReceiveHTML = 1
  AND c.owner='".$_SESSION['logged_user_id']."'
  AND c.ResponderID = b.ResponderID
  AND b.SubscriberID = a.SubscriberID
GROUP BY c.ResponderID";

//echo $select_result;

while($row = mysql_fetch_array($select_result))
{
    $messages = $row['COUNT(MsgID)'];
    $campaign = $row['ResponderID'];
    $subscriber = $row['SubscriberID'];
    $subscriber_email = $row['EmailAddress'];

    echo "
Campaign = ". $campaign ."

Sent emails count = ". $messages ."

Subscriber Nr. = ". $subscriber ."

Subscriber Email = ". $subscriber_email ."
";
     }

This is the output:

Campaign = 10
Sent emails count = 109
Subscriber Nr. = 95
Subscriber Email = timothy@gmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com

As there are three different subscribers under campaign no.10 and one under campaign no.11 in the db (each with its own email addresses of course), I would like the output to be:

Campaign = 10
Sent emails count = 109
Subscriber Nr. = 92
94
95
Subscriber Email = timothy@gmail.com
anthony@yahoo.com
josie@hotmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com

Thanks.

Body:
You need group_concat for this:

... SELECT c.ResponderID, COUNT(MsgID), a.SubscriberID, CanReceiveHTML,
group_concat(EmailAddress ORDER BY EmailAddress DESC SEPARATOR ' ') ...


问:
openpyxl - adjust column width size
I have following script which is converting a CSV file to an XLSX file, but my column size is very narrow. Each time I have to drag them with mouse to read data. Does anybody know how to set column width in openpyxl?

Here is the code I am using.

```<code>#!/usr/bin/python2.6
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

f = open('users_info_cvs.txt', "rU")

csv.register_dialect('colons', delimiter=':')

reader = csv.reader(f, dialect='colons')

wb = Workbook()
dest_filename = r"account_info.xlsx"

ws = wb.worksheets[0]
ws.title = "Users Account Information"

for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = get_column_letter((column_index + 1))
        ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell

wb.save(filename = dest_filename)
</code>```

答:
All the above answers are generating an issue which is that col[0].column is returning number while worksheet.column_dimensions[column] accepts only character such as 'A', 'B', 'C' in place of column. I've modified @Virako's code and it is working fine now.</p>

```<code>import re
import openpyxl
..
for col in _ws.columns:
    max_lenght = 0
    print(col[0])
    col_name = re.findall('\w\d', str(col[0]))
    col_name = col_name[0]
    col_name = re.findall('\w', str(col_name))[0]
    print(col_name)
    for cell in col:
        try:
            if len(str(cell.value)) > max_lenght:
                max_lenght = len(cell.value)
        except:
            pass
    adjusted_width = (max_lenght+2)
    _ws.column_dimensions[col_name].width = adjusted_width
</code>```

Title: openpyxl - adjust column width size

Body:
I have following script which is converting a CSV file to an XLSX file, but my column size is very narrow. Each time I have to drag them with mouse to read data. Does anybody know how to set column width in openpyxl?

Here is the code I am using.

#!/usr/bin/python2.6
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

f = open('users_info_cvs.txt', "rU")

csv.register_dialect('colons', delimiter=':')

reader = csv.reader(f, dialect='colons')

wb = Workbook()
dest_filename = r"account_info.xlsx"

ws = wb.worksheets[0]
ws.title = "Users Account Information"

for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = get_column_letter((column_index + 1))
        ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell

wb.save(filename = dest_filename)

Body:
All the above answers are generating an issue which is that col[0].column is returning number while worksheet.column_dimensions[column] accepts only character such as 'A', 'B', 'C' in place of column. I've modified @Virako's code and it is working fine now.

import re
import openpyxl
..
for col in _ws.columns:
    max_lenght = 0
    print(col[0])
    col_name = re.findall('\w\d', str(col[0]))
    col_name = col_name[0]
    col_name = re.findall('\w', str(col_name))[0]
    print(col_name)
    for cell in col:
        try:
            if len(str(cell.value)) > max_lenght:
                max_lenght = len(cell.value)
        except:
            pass
    adjusted_width = (max_lenght+2)
    _ws.column_dimensions[col_name].width = adjusted_width


问:
Compile a Scala library to JavaScript
I want to use the expressions subproject from this project in my TypeScript node.js project. I learned about Scala.js and its ability to compile Scala to javascript. I tried to follow the guide to compile the code to javascript, but I got stuck. The tutorial seems to imply that you can only build applications, not libraries.

The only way to expose the libraries' classes I can think of right now is to write a main function that would do the equivalent of module.exports = { ClassName: ScalaClassName }, but I've never written any Scala. Would this approach even work?

答: You can emit JavaScript modules with Scala.js. See Emitting a JavaScript module. You probably need to add some @JSExportTopLevel to determine what will be part of the module, which probably means adding those annotations to the original library if it doesn't yet have them.

Title: Compile a Scala library to JavaScript


问:
Old project creation dialog in visual studio 2019
How do I switch back to old project creation dialog in visual studio 2019,

the old project creation dialog:

答:
I was able to bring back old project creation dialog using this extension and now that android version dropdown is available:

https://github.com/MicrosoftDocs/visualstudio-docs/issues/3221

Classic 'New Project' Dialog

https://marketplace.visualstudio.com/items?itemName=softworkz.SwitchProjectDialog


问:
what is the replacement for Apache spark in IBM watson studio services as now it is deprecated
I was creating a recommendation engine in IBM Watson studio for that I needed to add spark service but now it is deprecated what I should use now.</p>

答: @Veer as @charles said Spark services are now accessible via Environments. When creating a notebook select a Spark compatible environment and import pyspark in your notebook.


问:
Regex for patterns like [ABC], ABC and ABCxx where xx is a number
I have a text whose length can vary between 1 and 1000. I am looking to get the following sub strings extracted from the text.

Sub string of the form ABCxx/ABCx where ABC are always english alphabets and x/xx is a number which can vary from 0 to 99 (the numeric length is either 1 or 2). The following regex does the job for me to extract this sub string - [a-zA-Z]{3}[0-9]{1,2}

Sub string of the form <space>ABC<space>, ABC (last sub string/word in the text)and ABC (first sub string in the text). Basically here I am trying to find a 3 letter word delimited by spaces in the text.

For getting the above matches, I have the following regex's.

[ ][a-zA-Z]{3}[ ], [ ][a-zA-Z]{3} and [a-zA-Z]{3}[ ]
```

<ol start="3">
<li>Same as 2, but the three character string can also be in a box bracket like [ABC]. </li>
</ol>

<pre class="lang-rb prettyprint-override"><code>\[([a-zA-Z]{3})\]
</code>```

Since the patterns are more or less similar, is there anyway to combine all 5 of them ?

Eg: ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc

Here valid matches are ABC, rat, LAN45, eat, HGF1, abc.

答:
```<code>R = /
    \p{L}{3}\d{1,2}    # match 3 letters followed by 1 or 2 digits
    |                  # or
    (?<=\A|\p{Space})  # match start of string or a space in a pos lookbehind
    (?:                # begin a non-capture group
      \p{L}{3}         # match three letters
      |                # or
      \[\p{L}{3}\]     # match three letters surrounded by brackets
    )                  # end of non-capture group
    (?=\p{Space}|\z)   # match space or end of string in a pos lookahead
    /x                 # free-spacing regex definition mode
</code>```

```<code>"ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc".scan R
   #=> ["ABC", "[rat]", "LAN45", "eat", "HGF1", "abc"]
</code>```

This regex is conventionally written (not free-spacing mode):

```<code>R = /\p{L}{3}\d{1,2}|(?<=\A| )(?:\p{L}{3}\[\p{L}{3}\])(?= |\z)/
</code>```

Now consider:

```<code> "ABCD123 [efg]456".scan R
   #=> ["BCD12"]
</code>```

I believe this is consistent with the statement of the problem, but if "BCD12" should not be a match if it is preceded by a letter or followed by a digit (here both apply), then the regex should be modified as follows.

```<code>R = /
    (?<=\A|\p{Space})  # match start of string or a space in a pos lookbehind
    (?:                # begin a non-capture group
      \p{L}{3}         # match three letters
      \d{,2}           # match 0, 1 or 2 digits
      |                # or
      \[\p{L}{3}\]     # match three letters surrounded by brackets
    )                  # end of non-capture group
    (?=\p{Space}|\z)   # match space or end of string in a pos lookahead
    /x                 # free-spacing regex definition mode

"ABC catmat dogdog [rat] XLAN45 eat HGF123 jkhgkj abc".scan R
  #=> ["ABC", "[rat]", "eat", "abc"]
</code>```

Notice that, in both regexes, I replaced \p{Space} with a space character. In free-spacing mode spaces are removed before the regex is parsed, so they must be written \p{Space}, [[:space:]], [ ] (a character class containing a space), \ an escaped space character or, if appropriate, \s for a whitespace character (which includes spaces, newlines, tabs and a few other characters).

Body:
I have a text whose length can vary between 1 and 1000. I am looking to get the following sub strings extracted from the text.

Sub string of the form ABCxx/ABCx where ABC are always english alphabets and x/xx is a number which can vary from 0 to 99 (the numeric length is either 1 or 2). The following regex does the job for me to extract this sub string - [a-zA-Z]{3}[0-9]{1,2}

Sub string of the form <space>ABC<space>, ABC (last sub string/word in the text)and ABC (first sub string in the text). Basically here I am trying to find a 3 letter word delimited by spaces in the text.

For getting the above matches, I have the following regex's.

[ ][a-zA-Z]{3}[ ], [ ][a-zA-Z]{3} and [a-zA-Z]{3}[ ]

Same as 2, but the three character string can also be in a box bracket like [ABC].

\[([a-zA-Z]{3})\]

Since the patterns are more or less similar, is there anyway to combine all 5 of them ?

Eg: ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc

Here valid matches are ABC, rat, LAN45, eat, HGF1, abc.

Body:
R = /
    \p{L}{3}\d{1,2}    # match 3 letters followed by 1 or 2 digits
    |                  # or
    (?<=\A|\p{Space})  # match start of string or a space in a pos lookbehind
    (?:                # begin a non-capture group
      \p{L}{3}         # match three letters
      |                # or
      \[\p{L}{3}\]     # match three letters surrounded by brackets
    )                  # end of non-capture group
    (?=\p{Space}|\z)   # match space or end of string in a pos lookahead
    /x                 # free-spacing regex definition mode

"ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc".scan R
   #=> ["ABC", "[rat]", "LAN45", "eat", "HGF1", "abc"]

This regex is conventionally written (not free-spacing mode):

R = /\p{L}{3}\d{1,2}|(?<=\A| )(?:\p{L}{3}\[\p{L}{3}\])(?= |\z)/

Now consider:

 "ABCD123 [efg]456".scan R
   #=> ["BCD12"]

I believe this is consistent with the statement of the problem, but if "BCD12" should not be a match if it is preceded by a letter or followed by a digit (here both apply), then the regex should be modified as follows.

R = /
    (?<=\A|\p{Space})  # match start of string or a space in a pos lookbehind
    (?:                # begin a non-capture group
      \p{L}{3}         # match three letters
      \d{,2}           # match 0, 1 or 2 digits
      |                # or
      \[\p{L}{3}\]     # match three letters surrounded by brackets
    )                  # end of non-capture group
    (?=\p{Space}|\z)   # match space or end of string in a pos lookahead
    /x                 # free-spacing regex definition mode

"ABC catmat dogdog [rat] XLAN45 eat HGF123 jkhgkj abc".scan R
  #=> ["ABC", "[rat]", "eat", "abc"]

Notice that, in both regexes, I replaced \p{Space} with a space character. In free-spacing mode spaces are removed before the regex is parsed, so they must be written \p{Space}, [[:space:]], [ ] (a character class containing a space), \ an escaped space character or, if appropriate, \s for a whitespace character (which includes spaces, newlines, tabs and a few other characters).


问:
Why would $_FILES be empty when uploading files to PHP?
I have WampServer 2 installed on my Windows 7 computer. I'm using Apache 2.2.11 and PHP 5.2.11. When I attempt to upload any file from a form, it seems to upload, but in PHP, the $_FILES array is empty. There is no file in the c:\wamp\tmp folder. I have configured php.ini to allow file uploads and such. The tmp folder has read/write privileges for the current user. I'm stumped.

HTML:

```<code><html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <form enctype="multipart/form-data" action="vanilla-upload.php" method="POST">
        Choose a file to upload: <input name="uploadedfile" type="file" /><br />
        <input type="submit" value="Upload File" />
    </form>
</body>
</html>
</code>```

PHP:

```<code><?php
echo 'file count=', count($_FILES),"\n";
var_dump($_FILES);
echo "\n";
?>
</code>```

答:
Do not trust the temp folder location provided by sys_get_temp_dir if you're in a shared hosting environment.

Here is one more thing to check that has not yet been mentioned...

I assumed, naturally, that the folder where my PHP script stored temporary file uploads was /tmp. This belief was reinforced by the fact that echo sys_get_temp_dir() . PHP_EOL; returns/tmp. Also, echo ini_get('upload_tmp_dir'); returns nothing.

To verify that the uploaded file does in fact briefly appear in my /tmp folder, I added a sleep(30); statement to my script (as suggested here) and navigated to my /tmp folder in cPanel File Manager to locate the file. However, no matter what, the uploaded file was nowhere to be found there.

I spent hours trying to determine the reason for this, and implemented every suggestion that's been offered here.

Finally, after searching my website files for the query tmp, I discovered that my site contained other folders named tmp in different directories. I realized that my PHP script was actually writing the uploaded files to .cagefs/tmp. (The "Show Hidden Files" setting must be enabled in cPanel in order to view this folder.)

So, why does the sys_get_temp_dir function return inaccurate info?

Here's an explanation from the PHP.net webpage for sys_get_temp_dir (i.e., the top comment):

If running on a Linux system where systemd has PrivateTmp=true (which
  is the default on CentOS 7 and perhaps other newer distros), this
  function will simply return "/tmp", not the true, much longer,
  somewhat dynamic path.

This SO post delves into the issue, as well:

Stack Overflow: sys_get_temp_dir in shared hosting environment

Body:
I have WampServer 2 installed on my Windows 7 computer. I'm using Apache 2.2.11 and PHP 5.2.11. When I attempt to upload any file from a form, it seems to upload, but in PHP, the $_FILES array is empty. There is no file in the c:\wamp\tmp folder. I have configured php.ini to allow file uploads and such. The tmp folder has read/write privileges for the current user. I'm stumped.

HTML:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <form enctype="multipart/form-data" action="vanilla-upload.php" method="POST">
        Choose a file to upload: <input name="uploadedfile" type="file" />

        <input type="submit" value="Upload File" />
    </form>

PHP:

<?php
echo 'file count=', count($_FILES),"\n";
var_dump($_FILES);
echo "\n";
?>


问:
Return final observable from nested block
Hi guys I have the following code:

```<code>return this.facebook.getFacebookUserInfos(req.token).pipe(
      switchMap(user => {
            return this._repo.findBy({email: user.email}).pipe(
              switchMap(foundUser => {
                // assume foundUser is always null
                if (!foundUser) {
                  const fromFacebook = this.createUserModel(user, event.queryStringParameters);
                 return this._repo.save(fromFacebook);
                }
                return of(foundUser);
              }));
          }),
          switchMap(user => {
            return this.getAuthToken(user)
          }),
          map(response => Response.ok(response.body, response.headers)),
          catchError((err) => of(Response.errorResponse(err)))
        );
</code>```

I'm stuck as it calls this._repo.save(fromFacebook) and doesn't wait for the observable to finish and goes to the next switch map with another observable. How can I force the block to wait for the result of this._repo.save(fromFacebook) before passing to the next one? the save method returns an observable as well. Thanks in advance for your help.
Cheers

答:
Try the below code snippet.</p>

```<code>return this.facebook.getFacebookUserInfos(req.token).pipe(
      switchMap(user => {
            return this._repo.findBy({email: user.email}).pipe(
              switchMap(foundUser => {
                // assume foundUser is always null
                if (!foundUser) {
                  const fromFacebook = this.createUserModel(user, event.queryStringParameters);
                 return this._repo.save(fromFacebook);
                } else {
                 return of(foundUser);
                }
              }));
          }),
          concatMap(user => {
            return this.getAuthToken(user)
          }),
          map(response => Response.ok(response.body, response.headers)),
          catchError((err) => of(Response.errorResponse(err)))
        );
</code>```

Body:
Hi guys I have the following code:

return this.facebook.getFacebookUserInfos(req.token).pipe(
      switchMap(user => {
            return this._repo.findBy({email: user.email}).pipe(
              switchMap(foundUser => {
                // assume foundUser is always null
                if (!foundUser) {
                  const fromFacebook = this.createUserModel(user, event.queryStringParameters);
                 return this._repo.save(fromFacebook);
                }
                return of(foundUser);
              }));
          }),
          switchMap(user => {
            return this.getAuthToken(user)
          }),
          map(response => Response.ok(response.body, response.headers)),
          catchError((err) => of(Response.errorResponse(err)))
        );

I'm stuck as it calls this._repo.save(fromFacebook) and doesn't wait for the observable to finish and goes to the next switch map with another observable. How can I force the block to wait for the result of this._repo.save(fromFacebook) before passing to the next one? the save method returns an observable as well. Thanks in advance for your help.
Cheers

Body:
Try the below code snippet.

return this.facebook.getFacebookUserInfos(req.token).pipe(
      switchMap(user => {
            return this._repo.findBy({email: user.email}).pipe(
              switchMap(foundUser => {
                // assume foundUser is always null
                if (!foundUser) {
                  const fromFacebook = this.createUserModel(user, event.queryStringParameters);
                 return this._repo.save(fromFacebook);
                } else {
                 return of(foundUser);
                }
              }));
          }),
          concatMap(user => {
            return this.getAuthToken(user)
          }),
          map(response => Response.ok(response.body, response.headers)),
          catchError((err) => of(Response.errorResponse(err)))
        );


问:
Telling numberOfRowsInSection how many rows it needs after parsing JSON with JSONDecoder in closure using MVVM architecture
I'm using MMVM architecture.

Basically I have this function to parse JSON in a viewModelProtocol extension as default implementation, my viewModels are conforming to this protocol. Most viewModels populate standard Views without any problem except for one that is populating a tableVIew but I can't tell numberOfRowsInSection how many rows it needs.

```<code>func setWithJSON<T>(completion: @escaping (T) -> Void, error: @escaping (Error) -> Void, service: Services) where T : Decodable {
    let failure: (Error) -> Void = { error in
        self.dataFetchError?(error)
    }

    let completion: (Data) -> Void = { data in

        do {
            let parsedJSON = try JSONDecoder().decode(T.self, from: data)
            completion(parsedJSON)
        } catch {
            self.dataFetchError?(error)
        }
        return
    }

    QueryAPI.shared.setServiceURL(service)
    QueryAPI.shared.fetchData(failure: failure, completion: completion)
}
</code>```

With it I'm getting a generic type of parsedJSON

I'm using the function in my view to populate my cells in the cellForRowAt indexPath: method like this.

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! ExperienceViewCell

    let error: (Error) -> Void = { error in
        self.handleError(error)
    }

    let completion: ([Experience]) -> Void = { experiences in
        DispatchQueue.main.async { [ weak cell ] in
            cell?.companyLabel.text = experiences[indexPath.row].company
            cell?.positionLabel.text = experiences[indexPath.row].position
            cell?.websiteLabel.text = experiences[indexPath.row].website
            cell?.startDateLabel.text = experiences[indexPath.row].startDate
            cell?.endDateLabel.text = experiences[indexPath.row].endDate
            cell?.summaryTextView.text = experiences[indexPath.row].summary
            cell?.highLightsTextView.text = experiences[indexPath.row].highlights
        }
    }

    viewModel.setWithJSON(completion: completion, error: error, service: .workExperience)
    self.viewModel.dataFetchError = { error in
        self.handleError(error)
    }

    return cell
}
</code>```

This way I'm getting an array of the struct Experience in the closure and I use every one of its elements to populate the rows of my tableView.

But I don't have a way to tell the method numberOfRowsInSection how many rows do we need so I'm hardcoding it but that's not what I need.

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 7
}
</code>```

Is there any way I can get an array of Experience when the view loads so I can tell the method how many rows it should return.

Thanks in advance.

答:
The problem I see is that you are calling the service in the tableView:cellForRowAt: function and this is not a good approach.

Try to set in your viewController a variable var experiences: [Experience] = []

In the viewDidLoad function call your service

```<code>func viewDidLoad() {
    super.viewDidLoad()
    let completion: ([Experience]) -> Void = { experiences in
        DispatchQueue.main.async { [ weak self ] in
            self?.experiences = experiences
            self?.tableView.reloadData()
        }
    }
    viewModel.setWithJSON(completion: completion, error: error, service: .workExperience)
    self.viewModel.dataFetchError = { error in
        self.handleError(error)
    }
}
</code>```

In the function tableView:numberOfRowsInSection: you can return experiences.count

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return experiences.count
}
</code>```

And finally, inside function tableView:cellForRowAt: you can put your code to update the cell:

```<code>cell.companyLabel.text = experiences[indexPath.row].company
cell.positionLabel.text = experiences[indexPath.row].position
cell.websiteLabel.text = experiences[indexPath.row].website
cell.startDateLabel.text = experiences[indexPath.row].startDate
cell.endDateLabel.text = experiences[indexPath.row].endDate
cell.summaryTextView.text = experiences[indexPath.row].summary
cell.highLightsTextView.text = experiences[indexPath.row].highlights
</code>```

With tableView.reloadData(), you will call again the function tableView:numberOfRowsInSection: after you receive your list of experiences.

Body:
I'm using MMVM architecture.

Basically I have this function to parse JSON in a viewModelProtocol extension as default implementation, my viewModels are conforming to this protocol. Most viewModels populate standard Views without any problem except for one that is populating a tableVIew but I can't tell numberOfRowsInSection how many rows it needs.

func setWithJSON<T>(completion: @escaping (T) -> Void, error: @escaping (Error) -> Void, service: Services) where T : Decodable {
    let failure: (Error) -> Void = { error in
        self.dataFetchError?(error)
    }

    let completion: (Data) -> Void = { data in

        do {
            let parsedJSON = try JSONDecoder().decode(T.self, from: data)
            completion(parsedJSON)
        } catch {
            self.dataFetchError?(error)
        }
        return
    }

    QueryAPI.shared.setServiceURL(service)
    QueryAPI.shared.fetchData(failure: failure, completion: completion)
}

With it I'm getting a generic type of parsedJSON

I'm using the function in my view to populate my cells in the cellForRowAt indexPath: method like this.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! ExperienceViewCell

    let error: (Error) -> Void = { error in
        self.handleError(error)
    }

    let completion: ([Experience]) -> Void = { experiences in
        DispatchQueue.main.async { [ weak cell ] in
            cell?.companyLabel.text = experiences[indexPath.row].company
            cell?.positionLabel.text = experiences[indexPath.row].position
            cell?.websiteLabel.text = experiences[indexPath.row].website
            cell?.startDateLabel.text = experiences[indexPath.row].startDate
            cell?.endDateLabel.text = experiences[indexPath.row].endDate
            cell?.summaryTextView.text = experiences[indexPath.row].summary
            cell?.highLightsTextView.text = experiences[indexPath.row].highlights
        }
    }

    viewModel.setWithJSON(completion: completion, error: error, service: .workExperience)
    self.viewModel.dataFetchError = { error in
        self.handleError(error)
    }

    return cell
}

This way I'm getting an array of the struct Experience in the closure and I use every one of its elements to populate the rows of my tableView.

But I don't have a way to tell the method numberOfRowsInSection how many rows do we need so I'm hardcoding it but that's not what I need.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 7
}

Is there any way I can get an array of Experience when the view loads so I can tell the method how many rows it should return.

Thanks in advance.

Body:
The problem I see is that you are calling the service in the tableView:cellForRowAt: function and this is not a good approach.

Try to set in your viewController a variable var experiences: [Experience] = []

In the viewDidLoad function call your service

func viewDidLoad() {
    super.viewDidLoad()
    let completion: ([Experience]) -> Void = { experiences in
        DispatchQueue.main.async { [ weak self ] in
            self?.experiences = experiences
            self?.tableView.reloadData()
        }
    }
    viewModel.setWithJSON(completion: completion, error: error, service: .workExperience)
    self.viewModel.dataFetchError = { error in
        self.handleError(error)
    }
}

In the function tableView:numberOfRowsInSection: you can return experiences.count

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return experiences.count
}

And finally, inside function tableView:cellForRowAt: you can put your code to update the cell:

cell.companyLabel.text = experiences[indexPath.row].company
cell.positionLabel.text = experiences[indexPath.row].position
cell.websiteLabel.text = experiences[indexPath.row].website
cell.startDateLabel.text = experiences[indexPath.row].startDate
cell.endDateLabel.text = experiences[indexPath.row].endDate
cell.summaryTextView.text = experiences[indexPath.row].summary
cell.highLightsTextView.text = experiences[indexPath.row].highlights

With tableView.reloadData(), you will call again the function tableView:numberOfRowsInSection: after you receive your list of experiences.


问:
How to disable/enable submit button based on Datepicker selected date?
I have a simple form that contains one submit button and 2 input text, that call "date1" and "date2" and both are using DatePicker Gijgo plugin (https://gijgo.com/datepicker) to select date.

I would like to disable submit button if i select date from "date2" that is less than today and enable submit button if i select date from "data2" that is greater/equal than today.

Before i post here, i researched the topics below, but i didn't find the correct way to solve this:

JQuery Datepicker OnSelect and TextChanged problem

Activate button when two datepickers fields have values

jQuery disable or enable submit button based on dates

Below is the code that i'm working:

1. CDN Scripts

```<code><!-- BOOTSTRAP CSS CDN -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" />

<!-- BOOTSTRAP SCRIPT CDN -->

<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<!-- DATEPICKER SCRIPT CDN -->

<script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script>
<link href="https://unpkg.com/gijgo@1.9.13/css/gijgo.min.css" rel="stylesheet" type="text/css" />

</code>```

2. HTML form code

```<code><div class="container" style="max-width:507px;">
<br>
<form method="post" id="date_form" enctype="multipart/form-data">

<div class="form-row">

<div class="col-md-6 mb-3">
<label align="left"><b>Date 1</b></label>
<input type="text" name="date1" id="date1" class="form-control"/>

</div>

<div class="col-md-6 mb-3">
<label align="left"><b>Date 2</b></label>
<input type="text" name="date2" id="date2" class="form-control"/>

</div>

</div>

</form>

<div class="form-footer">
<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-success" value="SUBMIT" disabled/>
</div>
</div>
</code>```

DatePicker script that disable old date from "date2" before the date that was selected at "date1":

```<code>
<!-- DATEPICKER SCRIPT -->

<script>

var today = new Date();
        $('#date1').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            maxDate: function () {
                return $('#date2').val();
            }
        });
        $('#date2').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            minDate: function () {
                return $('#date1').val();
            }
        });

</script>

</code>```

4. And finaly, the code that i'm trying to apply to disable submit button when i selected a date from "date2" that is less (<) than today, but unfortunately it doesn't works:

```<code><!-- SCRIPT TO DISABLE SUBMIT BUTTON IF ***date2*** IS LESS THAN TODAY -->

<script>

$('#date2').datepicker({
    dateFormat: 'dd/mm/yyyy',
    onSelect: function(dateText){
        var date2 = $('#date2').val();
            var curDate = new Date();
            if(date2 < curDate){
$("#btnSubmit").attr("disabled", true);
            }else{
$("#btnSubmit").attr("disabled", false);
            }
        }
});
</script>
</code>```

In this case, how can i modify this script above to disable submit button when i select each time a date from "date2" that is less than today and enable submit button when i select a date from "date2" that is greater/equal than today?

答:
Use the change event to capture the set date and compare to current time. Then set the button's disabled state based on the comparison.

```<code>.....
change: function(e) {
    //get date in yyyy/mm/dd format
    var vl = $(this).val().split('/').reverse().join('/');
    //getTime to compare with current timestamp
    var ds = new Date(vl).getTime();
    //current timestamp
    var dn = e.timeStamp;
    $('#btnSubmit').prop('disabled', ds<dn);
}
....
</code>```

        $('#date1').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            maxDate: function () {
                return $('#date2').val();
            }
        });
        $('#date2').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            minDate: function () {
                return $('#date1').val();
            },
            change: function(e) {
              //get date in yyyy/mm/dd format
              var vl = $(this).val().split('/').reverse().join('/');
              //getTime to compare with current timestamp
              var ds = new Date(vl).getTime();
              //current timestamp
              var dn = e.timeStamp;
              $('#btnSubmit').prop('disabled', ds<dn);
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- BOOTSTRAP CSS CDN -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" />

<!-- BOOTSTRAP SCRIPT CDN -->

<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<!-- DATEPICKER SCRIPT CDN -->

<script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script>
<link href="https://unpkg.com/gijgo@1.9.13/css/gijgo.min.css" rel="stylesheet" type="text/css" />
<div class="container" style="max-width:507px;">
<br>
<form method="post" id="date_form" enctype="multipart/form-data">

<div class="form-row">

<div class="col-md-6 mb-3">
<label align="left"><b>Date 1</b></label>
<input type="text" name="date1" id="date1" class="form-control"/>

</div>

<div class="col-md-6 mb-3">
<label align="left"><b>Date 2</b></label>
<input type="text" name="date2" id="date2" class="form-control"/>

</div>

</div>

</form>

<div class="form-footer">
<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-success" value="SUBMIT"/>
</div>
</div></code>```

Body:
I have a simple form that contains one submit button and 2 input text, that call "date1" and "date2" and both are using DatePicker Gijgo plugin (https://gijgo.com/datepicker) to select date.

I would like to disable submit button if i select date from "date2" that is less than today and enable submit button if i select date from "data2" that is greater/equal than today.

Before i post here, i researched the topics below, but i didn't find the correct way to solve this:

JQuery Datepicker OnSelect and TextChanged problem

Activate button when two datepickers fields have values

jQuery disable or enable submit button based on dates

Below is the code that i'm working:

1. CDN Scripts

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" />

<link href="https://unpkg.com/gijgo@1.9.13/css/gijgo.min.css" rel="stylesheet" type="text/css" />

2. HTML form code

<form method="post" id="date_form" enctype="multipart/form-data">

Date 1
<input type="text" name="date1" id="date1" class="form-control"/>

Date 2
<input type="text" name="date2" id="date2" class="form-control"/>

</form>

<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-success" value="SUBMIT" disabled/>

DatePicker script that disable old date from "date2" before the date that was selected at "date1":

4. And finaly, the code that i'm trying to apply to disable submit button when i selected a date from "date2" that is less (<) than today, but unfortunately it doesn't works:

In this case, how can i modify this script above to disable submit button when i select each time a date from "date2" that is less than today and enable submit button when i select a date from "date2" that is greater/equal than today?

Body:
Use the change event to capture the set date and compare to current time. Then set the button's disabled state based on the comparison.

.....
change: function(e) {
    //get date in yyyy/mm/dd format
    var vl = $(this).val().split('/').reverse().join('/');
    //getTime to compare with current timestamp
    var ds = new Date(vl).getTime();
    //current timestamp
    var dn = e.timeStamp;
    $('#btnSubmit').prop('disabled', ds<dn);
}
....

        $('#date1').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            maxDate: function () {
                return $('#date2').val();
            }
        });
        $('#date2').datepicker({
            format: 'dd/mm/yyyy',
            uiLibrary: 'bootstrap4',
            iconsLibrary: 'fontawesome',
            minDate: function () {
                return $('#date1').val();
            },
            change: function(e) {
              //get date in yyyy/mm/dd format
              var vl = $(this).val().split('/').reverse().join('/');
              //getTime to compare with current timestamp
              var ds = new Date(vl).getTime();
              //current timestamp
              var dn = e.timeStamp;
              $('#btnSubmit').prop('disabled', ds<dn);
            }
        });

<!-- BOOTSTRAP CSS CDN -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" />

<!-- BOOTSTRAP SCRIPT CDN -->

<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<!-- DATEPICKER SCRIPT CDN -->

<script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script>
<link href="https://unpkg.com/gijgo@1.9.13/css/gijgo.min.css" rel="stylesheet" type="text/css" />
<div class="container" style="max-width:507px;">
<br>
<form method="post" id="date_form" enctype="multipart/form-data">

<div class="form-row">

<div class="col-md-6 mb-3">
<label align="left"><b>Date 1</b></label>
<input type="text" name="date1" id="date1" class="form-control"/>

</div>

<div class="col-md-6 mb-3">
<label align="left"><b>Date 2</b></label>
<input type="text" name="date2" id="date2" class="form-control"/>

</div>

</div>

</form>

<div class="form-footer">
<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-success" value="SUBMIT"/>
</div>
</div>


问:
'PylintSensor' skipped because there is no related rule activated in the quality profile
I would like to scan my python code with Sonar (version 7.1) and pylint. I'm using plugin SonarPython (version 1.10)

Command execute scan:

```<code>sonar-scanner -Dsonar.projectKey=${PROJECT} -Dsonar.projectVersion=${VERSION} -Dsonar.projectName=${PROJECT} -Dsonar.python.pylint=/usr/bin/pylint -X
</code>```

And my sonar-project.properties file:

```<code>sonar.projectBaseDir=./
sonar.sources=./
sonar.python.coverage.reportPath=./coverage.xml
sonar.core.codeCoveragePlugin=cobertura
sonar.python.xunit.reportPath=./nosetests.xml
sonar.exclusions=test/**
</code>```

I got :

DEBUG: PylintSensor skipped because there is no related rule activated
  in the quality profile

  DEBUG: PylintImportSensor skipped because
  there is no related rule activated in the quality profile

Thanks!

答:
It skips because I do not active Pylint rules on Sonar server.

You can refer: Here

Body:
I would like to scan my python code with Sonar (version 7.1) and pylint. I'm using plugin SonarPython (version 1.10)

Command execute scan:

sonar-scanner -Dsonar.projectKey=${PROJECT} -Dsonar.projectVersion=${VERSION} -Dsonar.projectName=${PROJECT} -Dsonar.python.pylint=/usr/bin/pylint -X

And my sonar-project.properties file:

sonar.projectBaseDir=./
sonar.sources=./
sonar.python.coverage.reportPath=./coverage.xml
sonar.core.codeCoveragePlugin=cobertura
sonar.python.xunit.reportPath=./nosetests.xml
sonar.exclusions=test/**

I got :

DEBUG: PylintSensor skipped because there is no related rule activated
  in the quality profile

  DEBUG: PylintImportSensor skipped because
  there is no related rule activated in the quality profile

Thanks!


问:
Jquery Fade in fade out, with pause or delay
If have the following code but i cant get a pause AFTER ever fade in   and fade out:</p>

```<code>$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});
</code>```

答: This doesn't exactly help with your code, but maybe you should look into the the jQuery Cycle plugin, because it sounds like you want to cycle through a bunch of images/content in a slideshow manner with the ability to pause/play.</p>

Body:
If have the following code but i cant get a pause AFTER ever fade in   and fade out:

$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});


问:
I am having trouble creating a class to model loans with interest and payments
I am getting having errors with the math in my loan repayment calculator. I am trying to create a class where I can create a loan, iterate it by month or year, and also apply payments to the loan. I am not entirely sure where my issue lies in this code.

I've tried altering the payment method and am stuck with the root problem with the math. I think there is an underlying issue with the way that I have interest accruing and the principle balance

```<code>class loan():

    p_i = 0 #initial principle
    p_new = 0 #total balance
    rate = 0 #interest rate (in %)
    acc = 0 #total accrued interest

    def __init__(self,p,rate):

        self.p_i = p
        self.p_new = p
        self.rate = rate

    def month(self):

        if self.p_i == self.p_new:
            self.acc += self.p_i * (1 + (self.rate/100)/12)
            self.p_new = self.p_i + self.acc
        else:
            self.acc += self.p_i * (1 + (self.rate/100)/12)
            self.p_new = self.p_i + self.acc

    def year(self):

        if self.p_i == self.p_new:
            self.acc += self.p_i * (1 + (self.rate/100)) - self.p_i
            self.p_new = self.p_i + self.acc
        else:
            temp = 0
            temp = self.p_i * (1 + (self.rate/100)) - self.p_i
            self.p_new += temp
            self.acc += temp

    def payment(self,amount):

        temp = 0
        if amount < self.acc:
            self.acc -= amount
        else:
            self.p_i -= amount - self.acc
            self.acc = 0
            self.p_new -= amount
</code>```

I would expect the output for say, a 10000 dollar loan with a 5% interest rate to be 10500 and then 11025 and the accrued interest to be 1025, instead I am getting 11000 and 1000 respectively.

答:
I would recommend as a start that you take this out of a class and just do this procedurally until you get the math worked out.  It seems you are battling the class syntax a bit.

So just try setting variables and some functions and then looping through some options.

Start with something like this:

```<code>principal = 10000
rate = 0.05

def monthly_interest():
    global principal, rate
    principal += rate/12*principal

def make_payment(payment):
    global principal
    principal -= payment

for month in range(1,13):
    monthly_interest()
    # print totals
    print('month {:2d}, principal ${:0.2f}'.format(month, principal))
</code>```

Realize this is kinda ugly with global variables and all, but if you are having trouble getting the math to work, start here and then build to a class later when you have the kinks worked out.

Output:

```<code>month  1, principal $10041.67
month  2, principal $10083.51
month  3, principal $10125.52
month  4, principal $10167.71
month  5, principal $10210.08
month  6, principal $10252.62
month  7, principal $10295.34
month  8, principal $10338.24
month  9, principal $10381.31
month 10, principal $10424.57
month 11, principal $10468.00
month 12, principal $10511.62
</code>```

Body:
I am getting having errors with the math in my loan repayment calculator. I am trying to create a class where I can create a loan, iterate it by month or year, and also apply payments to the loan. I am not entirely sure where my issue lies in this code.

I've tried altering the payment method and am stuck with the root problem with the math. I think there is an underlying issue with the way that I have interest accruing and the principle balance

class loan():

    p_i = 0 #initial principle
    p_new = 0 #total balance
    rate = 0 #interest rate (in %)
    acc = 0 #total accrued interest

    def __init__(self,p,rate):

        self.p_i = p
        self.p_new = p
        self.rate = rate

    def month(self):

        if self.p_i == self.p_new:
            self.acc += self.p_i * (1 + (self.rate/100)/12)
            self.p_new = self.p_i + self.acc
        else:
            self.acc += self.p_i * (1 + (self.rate/100)/12)
            self.p_new = self.p_i + self.acc

    def year(self):

        if self.p_i == self.p_new:
            self.acc += self.p_i * (1 + (self.rate/100)) - self.p_i
            self.p_new = self.p_i + self.acc
        else:
            temp = 0
            temp = self.p_i * (1 + (self.rate/100)) - self.p_i
            self.p_new += temp
            self.acc += temp

    def payment(self,amount):

        temp = 0
        if amount < self.acc:
            self.acc -= amount
        else:
            self.p_i -= amount - self.acc
            self.acc = 0
            self.p_new -= amount

I would expect the output for say, a 10000 dollar loan with a 5% interest rate to be 10500 and then 11025 and the accrued interest to be 1025, instead I am getting 11000 and 1000 respectively.

Body:
I would recommend as a start that you take this out of a class and just do this procedurally until you get the math worked out.  It seems you are battling the class syntax a bit.

So just try setting variables and some functions and then looping through some options.

Start with something like this:

principal = 10000
rate = 0.05

def monthly_interest():
    global principal, rate
    principal += rate/12*principal

def make_payment(payment):
    global principal
    principal -= payment

for month in range(1,13):
    monthly_interest()
    # print totals
    print('month {:2d}, principal ${:0.2f}'.format(month, principal))

Realize this is kinda ugly with global variables and all, but if you are having trouble getting the math to work, start here and then build to a class later when you have the kinks worked out.

Output:

month  1, principal $10041.67
month  2, principal $10083.51
month  3, principal $10125.52
month  4, principal $10167.71
month  5, principal $10210.08
month  6, principal $10252.62
month  7, principal $10295.34
month  8, principal $10338.24
month  9, principal $10381.31
month 10, principal $10424.57
month 11, principal $10468.00
month 12, principal $10511.62


问:
or where clause - Laravel eloquent
I have this query:

```<code>if($keyword){
    array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}
</code>```

The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).

I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.

For the example:

```<code>if($fromPrice){
    array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
    array_push($where, ['price', '<=', $toPrice]);
}
</code>```

And the query is:

```<code>$cars= Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where)->paginate(10);
</code>```

I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.

Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

答:
You can also go with</p>

```<code>$propertyQuery = Property::query();
if($keyword){
   $propertyQuery->where(function($query) use ($keyword){
                    $query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
           });
         }
$cars = $propertyQuery->paginate(10);
</code>```

Title: or where clause - Laravel eloquent

Body:
I have this query:

if($keyword){
    array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}

The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).

I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.

For the example:

if($fromPrice){
    array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
    array_push($where, ['price', '<=', $toPrice]);
}

And the query is:

$cars= Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where)->paginate(10);

I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.

Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

Body:
You can also go with

$propertyQuery = Property::query();
if($keyword){
   $propertyQuery->where(function($query) use ($keyword){
                    $query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
           });
         }
$cars = $propertyQuery->paginate(10);


问:
Python, I want to convert a specific column type after importing a csv file
```<code>import numpy as np

data_arr = np.loadtxt("asset.csv", delimiter = ",", dtype = 'str')
data_arr
</code>```

Result:

```<code>array([['G1', '1', '100', '5', '0'],

['G1', '1', '21', '538', '0'],

['G1', '1', '22', '6000', '0'],

...,

['G2', '8', '61', '241908', '8800'],

['G2', '8', '70', '57341', '16800'],

['G2', '9', '51', '1340', '0']], dtype='<U7')
</code>```

But I want to convert 2,3,4,5 columns(The '1', '100', '5', and '0' fields in the first row) to int type

because I want to try

```<code>family_number = np.array([1,2,3,4,100])

capital = data_arr[data_arr[:,0]=="G1"]

for i, number in enumerate(family_number):

    family_numbers = capital[capital[:,1]>i] & capital[capital[:,1]<=number]

    print("\t" + len(family_numbers))
</code>```

How can I convert type of columns? Please help!

答:
You could slice the result and use astype:

arr = np.array([['1', '2', '3'], ['3', '4', '5'], ['5', '6', '7']])
arr
# array([['1', '2', '3'],
#        ['3', '4', '5'],
#        ['5', '6', '7']], dtype='<U1')

arr[:,1:].astype(int)
# array([[2, 3],
#        [4, 5],
#        [6, 7]])
```

I mean, the other answers and comments (@Amadan's, for example) seem correct in that you could import them with different data types in the first place. But, if you're stuck after the fact, code like the above should work.

Body:
import numpy as np

data_arr = np.loadtxt("asset.csv", delimiter = ",", dtype = 'str')
data_arr

Result:

array([['G1', '1', '100', '5', '0'],

['G1', '1', '21', '538', '0'],

['G1', '1', '22', '6000', '0'],

...,

['G2', '8', '61', '241908', '8800'],

['G2', '8', '70', '57341', '16800'],

['G2', '9', '51', '1340', '0']], dtype='<U7')

But I want to convert 2,3,4,5 columns(The '1', '100', '5', and '0' fields in the first row) to int type

because I want to try

family_number = np.array([1,2,3,4,100])

capital = data_arr[data_arr[:,0]=="G1"]

for i, number in enumerate(family_number):

    family_numbers = capital[capital[:,1]>i] & capital[capital[:,1]<=number]

    print("\t" + len(family_numbers))

How can I convert type of columns? Please help!

Body:
You could slice the result and use astype:

arr = np.array([['1', '2', '3'], ['3', '4', '5'], ['5', '6', '7']])
arr
# array([['1', '2', '3'],
#        ['3', '4', '5'],
#        ['5', '6', '7']], dtype='<U1')

arr[:,1:].astype(int)
# array([[2, 3],
#        [4, 5],
#        [6, 7]])

I mean, the other answers and comments (@Amadan's, for example) seem correct in that you could import them with different data types in the first place. But, if you're stuck after the fact, code like the above should work.


问:
'Worksheet' object has no attribute 'max_col'
I have used the max_col attribute numerous times in other projects, but keep getting the error 'Worksheet' object has no attribute 'max_col'

I'm especially confused because I use max_row right above it, with no error. I checked the documentation, and max_col still seems to be correct?

```<code>#!/usr/bin/python

# excelToCSV.py - Converts all excel files in a directory to CSV, one file
# per sheet

import openpyxl
import csv
import os

for excelFile in os.listdir('.'):
    #Skip non-xlsx files, load the workbook object.
    if excelFile.endswith('.xlsx'):
        wbA = openpyxl.load_workbook(excelFile)
        #Loop through each sheet in the workbook
        for sheet in wbA.worksheets:    #Note: changing wb to wb.worksheets
            sheetName = sheet.title
            sheetA = wbA.get_sheet_by_name(sheetName)
            # Create the CSV filename from the excel filename and sheet title
            excelFileStripped = excelFile.strip('.xlsx')
            csvFilename = excelFileStripped + '_' + sheetName + '.csv'
            # Create the csv.writer object for this csv file
            csvFile = open(csvFilename, 'w', newline='')
            csvWriter = csv.writer(csvFile)
            # Loop through every row in the sheet
            maxRow = sheetA.max_row
            maxCol = sheetA.max_col
</code>```

答: The attribute is max_column not max_col (official documentation)

Body:
I have used the max_col attribute numerous times in other projects, but keep getting the error 'Worksheet' object has no attribute 'max_col'

I'm especially confused because I use max_row right above it, with no error. I checked the documentation, and max_col still seems to be correct?

#!/usr/bin/python

# excelToCSV.py - Converts all excel files in a directory to CSV, one file
# per sheet

import openpyxl
import csv
import os

for excelFile in os.listdir('.'):
    #Skip non-xlsx files, load the workbook object.
    if excelFile.endswith('.xlsx'):
        wbA = openpyxl.load_workbook(excelFile)
        #Loop through each sheet in the workbook
        for sheet in wbA.worksheets:    #Note: changing wb to wb.worksheets
            sheetName = sheet.title
            sheetA = wbA.get_sheet_by_name(sheetName)
            # Create the CSV filename from the excel filename and sheet title
            excelFileStripped = excelFile.strip('.xlsx')
            csvFilename = excelFileStripped + '_' + sheetName + '.csv'
            # Create the csv.writer object for this csv file
            csvFile = open(csvFilename, 'w', newline='')
            csvWriter = csv.writer(csvFile)
            # Loop through every row in the sheet
            maxRow = sheetA.max_row
            maxCol = sheetA.max_col


问:
Where is kill_proc_info defined?
what is header file for the kernel API function kill_proc_info(int sig, struct siginfo *info, pid_t pid)</p>

答:
Grep is your friend. Or use one of the cross-references like http://lxr.linux.no or http://www.cs.fsu.edu/~baker/devices/lxr/http/source/.

Ad edit (the original question did not say "API"):
Actually, that function is not an API. It's an implementation detail of signal.c. It is not an API, because there is no EXPORT_SYMBOL[_GPL] declaration for it, so it's not callable from modular code.

Title: Where is kill_proc_info defined?


问:
i made a python script to login but it always reply error
this is a script i made it logs on to a php site but it always show error
i teated cookie lib that dont seem to work out for me any idea to fix it

import requests
url = 'http://my local site/some.php'
password = "foo"

r = requests.post(url,password)
print (r.content)
```

<p>this is php script i wrote </p>

<pre class="lang-php prettyprint-override"><code><?php
$password=$_POST['password'];

if($password=='foo')
{
    echo"{"status":"true","Message":"Key Found."}";

}
else
{
    echo "{"status":"false","Message":"No Key Found."}";
}
?>```
```

答:
```<code>data = {'password': "foo"}
r = requests.post(url,data)
</code>```

You should read the requests documentation. https://2.python-requests.org/en/master/user/quickstart/#make-a-request

Body:
this is a script i made it logs on to a php site but it always show error
i teated cookie lib that dont seem to work out for me any idea to fix it

import requests
url = 'http://my local site/some.php'
password = "foo"

r = requests.post(url,password)
print (r.content)

this is php script i wrote

<?php
$password=$_POST['password'];

if($password=='foo')
{
    echo"{"status":"true","Message":"Key Found."}";

}
else
{
    echo "{"status":"false","Message":"No Key Found."}";
}
?>```

Body:
data = {'password': "foo"}
r = requests.post(url,data)

You should read the requests documentation. https://2.python-requests.org/en/master/user/quickstart/#make-a-request


问:
Python Selenium: how to scrape results after clicking each record in a table on website
The website has a table containing multiple elements that can be clicked.

Every click will direct me to a separate page showing additional table results for the respective element.

I want to scrape the table results for all these elements using Selenium in Python (also use BeautifulSoup for parsing html data).

Below is my current code:

```<code>for i in range(table_pd2.shape[0]):

driver.find_element_by_link_text(table_pd2[0][i]).click()
driver.switch_to.window(driver.window_handles[1])

bs = BeautifulSoup(driver.page_source, 'html.parser')
table = bs.find_all('table', id='xxx')
table_pd = pd.read_html(str(table))
table_pd = table_pd[0]

driver.close()
driver.switch_to.window(driver.window_handles[0])
</code>```

Below is my logic:

table_pd2: a pandas series I created including the text of all elements

In the for loop:

locate and click each element in the table on website

switch to a popup page containing additional table results

get the table results and store them in a pandas df called table_pd

close the current page and switch back to the original page for clicking
the next item

Problem:
- How could I save each of the results in table_pd after each click? How could I combine all table_pd into a big pandas dataframe?

Please suggest, thanks!

答:
Try this below.</p>

```<code>all_df = pd.DataFrame() #<====== created over all df
for i in range(table_pd2.shape[0]):

driver.find_element_by_link_text(table_pd2[0][i]).click()
driver.switch_to.window(driver.window_handles[1])

bs = BeautifulSoup(driver.page_source, 'html.parser')
table = bs.find_all('table', id='xxx')
table_pd = pd.read_html(str(table))
table_pd = table_pd[0]
all_df.append(table_pd) #<====== appending to over all df
driver.close()
driver.switch_to.window(driver.window_handles[0])
</code>```

Body:
The website has a table containing multiple elements that can be clicked.

Every click will direct me to a separate page showing additional table results for the respective element.

I want to scrape the table results for all these elements using Selenium in Python (also use BeautifulSoup for parsing html data).

Below is my current code:

for i in range(table_pd2.shape[0]):

driver.find_element_by_link_text(table_pd2[0][i]).click()
driver.switch_to.window(driver.window_handles[1])

bs = BeautifulSoup(driver.page_source, 'html.parser')
table = bs.find_all('table', id='xxx')
table_pd = pd.read_html(str(table))
table_pd = table_pd[0]

driver.close()
driver.switch_to.window(driver.window_handles[0])

Below is my logic:

table_pd2: a pandas series I created including the text of all elements

In the for loop:

locate and click each element in the table on website

switch to a popup page containing additional table results

get the table results and store them in a pandas df called table_pd

close the current page and switch back to the original page for clicking
the next item

Problem:
- How could I save each of the results in table_pd after each click? How could I combine all table_pd into a big pandas dataframe?

Please suggest, thanks!

Body:
Try this below.

all_df = pd.DataFrame() #<====== created over all df
for i in range(table_pd2.shape[0]):

driver.find_element_by_link_text(table_pd2[0][i]).click()
driver.switch_to.window(driver.window_handles[1])

bs = BeautifulSoup(driver.page_source, 'html.parser')
table = bs.find_all('table', id='xxx')
table_pd = pd.read_html(str(table))
table_pd = table_pd[0]
all_df.append(table_pd) #<====== appending to over all df
driver.close()
driver.switch_to.window(driver.window_handles[0])


问:
What Does Django static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Actually DO?
I am using Django 2.2. From the Django Managing static files documentation:

If you use django.contrib.staticfiles as explained above, runserver
  will do this automatically when DEBUG is set to True. If you don’t
  have django.contrib.staticfiles in INSTALLED_APPS, you can still
  manually serve static files using the django.views.static.serve()
  view.

This is not suitable for production use! For some common deployment
  strategies, see Deploying static files.

For example, if your STATIC_URL is defined as /static/, you can do
  this by adding the following snippet to your urls.py:

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

Note

This helper function works only in debug mode and only if the given
  prefix is local (e.g. /static/) and not a URL (e.g.
  http://static.example.com/).

Also this helper function only serves the actual STATIC_ROOT folder;
  it doesn’t perform static files discovery like
  django.contrib.staticfiles.

My Interpretation

static is a helper function that serves files from the STATIC_ROOT during development (is this True?)

static only works when debug = True

static only works with a local prefix like STATIC_URL = '/static/'

When DEBUG is set to True and I use and setup the staticfiles app as explained in the documentation, if I do python manage.py runserver to start the local server, the serving of static files will be handled automatically (true??)

My Questions

What EXACTLY does adding static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to your project's urls.py DO?

Is it true that static serves static files locally from the STATIC_ROOT directory? To test this theory, after running collectstatic, I then deleted the static directories to see if the static files still load fine (from the STATIC_ROOT) and they DON'T! Why?

How can I verify that Django is loading the static files from my STATIC_ROOT location... and not the static directories in my project and apps??

Why is adding static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns necessary if Django serves static files automatically (mentioned in documentation)?

Example

settings.py

```<code>DEBUG = True

...

INSTALLED_APPS = [
    'django.contrib.admin',
    ...
    'django.contrib.staticfiles',
    'puppies.apps.PuppiesConfig'
]

...

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATIC_ROOT = 'c:/lkdsjfkljsd_cdn'
</code>```

In all my templates, I'm using {% load static %}.

Then I do: python manage.py collectstatic

At this point, it doesn't seem to matter if I have the below in my urls.py or not - my static files still load BUT I don't know if they're coming from my project's static directories or my STATIC_ROOT (c:/lkdsjfkljsd_cdn):

```<code>if settings.DEBUG is True:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

Lastly, if I delete those static directories in my project, all css, js and images don't work which leads me to believe that my Django project is loading static files from my project's static directories, NOT the STATIC_ROOT.

So, again, how can I tell Django to load the static files from my STATIC_ROOT location... and not the static directories in my project and apps?? OR, do I misunderstand that Django isn't supposed to load files from my STATIC_ROOT location locally?

*Edit (adding HTML image)

答:
I think you are mixing up few things. Let me clarify.

static:

As per documentation, it provides URL pattern for serving static file. If you go to the implementation, then you will see:

```<code>return [
        re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
]
</code>```

What it does is, it removes forward slash from left of the prefix(ie converts /static/ to static/), and then there is a view(which is serve) who does the pulling files.

serve:

This function does the serving files. It will serve files from a document root.

runserver:

runserver command runs the django development server. If you have django.contrib.staticfiles installed in INSTALLED_APPS, then it will automatically serve static files. If you don't want to serve static, then use runserver --nostatic. collectstatic or STATIC_ROOT has no relation to this command.

collectstatic:

This command collects all static files from different STATIC_DIRS, and put them in folder which is defined by STATIC_ROOT. collectstatic is very useful in production deployment, when you are using a reverse proxy server like NGINX or Apache etc. NGINX/Apache/Varnish uses that folder (where collectstatic stored the static files) as root and serve static from it. It is not recommended to use runserver in production. You can use gunicorn/uwsgi to serve django. But gunicorn/uwsgi does not serve static files, hence using reverse proxy server to serve static files.

finally:

To answer your questions:

No you don't have to put that in your code, unless you are not adding django.contrib.staticfiles in your INSTALLED_APPS.

No

You don't need to. STATIC_ROOT is used for different purpose

It is not. But for serving MEDIA files, you can add the following pattern:

```<code>if settings.DEBUG:
    urlpatterns += [
        re_path(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
    ]
</code>```

In production, media files should be served by reverse proxy server as well.

Body:
I am using Django 2.2. From the Django Managing static files documentation:

If you use django.contrib.staticfiles as explained above, runserver
  will do this automatically when DEBUG is set to True. If you don’t
  have django.contrib.staticfiles in INSTALLED_APPS, you can still
  manually serve static files using the django.views.static.serve()
  view.

This is not suitable for production use! For some common deployment
  strategies, see Deploying static files.

For example, if your STATIC_URL is defined as /static/, you can do
  this by adding the following snippet to your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Note

This helper function works only in debug mode and only if the given
  prefix is local (e.g. /static/) and not a URL (e.g.
  http://static.example.com/).

Also this helper function only serves the actual STATIC_ROOT folder;
  it doesn’t perform static files discovery like
  django.contrib.staticfiles.

My Interpretation

static is a helper function that serves files from the STATIC_ROOT during development (is this True?)

static only works when debug = True

static only works with a local prefix like STATIC_URL = '/static/'

When DEBUG is set to True and I use and setup the staticfiles app as explained in the documentation, if I do python manage.py runserver to start the local server, the serving of static files will be handled automatically (true??)

My Questions

What EXACTLY does adding static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to your project's urls.py DO?

Is it true that static serves static files locally from the STATIC_ROOT directory? To test this theory, after running collectstatic, I then deleted the static directories to see if the static files still load fine (from the STATIC_ROOT) and they DON'T! Why?

How can I verify that Django is loading the static files from my STATIC_ROOT location... and not the static directories in my project and apps??

Why is adding static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns necessary if Django serves static files automatically (mentioned in documentation)?

Example

settings.py

DEBUG = True

...

INSTALLED_APPS = [
    'django.contrib.admin',
    ...
    'django.contrib.staticfiles',
    'puppies.apps.PuppiesConfig'
]

...

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATIC_ROOT = 'c:/lkdsjfkljsd_cdn'

In all my templates, I'm using {% load static %}.

Then I do: python manage.py collectstatic

At this point, it doesn't seem to matter if I have the below in my urls.py or not - my static files still load BUT I don't know if they're coming from my project's static directories or my STATIC_ROOT (c:/lkdsjfkljsd_cdn):

if settings.DEBUG is True:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Lastly, if I delete those static directories in my project, all css, js and images don't work which leads me to believe that my Django project is loading static files from my project's static directories, NOT the STATIC_ROOT.

So, again, how can I tell Django to load the static files from my STATIC_ROOT location... and not the static directories in my project and apps?? OR, do I misunderstand that Django isn't supposed to load files from my STATIC_ROOT location locally?

*Edit (adding HTML image)

Body:
I think you are mixing up few things. Let me clarify.

static:

As per documentation, it provides URL pattern for serving static file. If you go to the implementation, then you will see:

return [
        re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
]

What it does is, it removes forward slash from left of the prefix(ie converts /static/ to static/), and then there is a view(which is serve) who does the pulling files.

serve:

This function does the serving files. It will serve files from a document root.

runserver:

runserver command runs the django development server. If you have django.contrib.staticfiles installed in INSTALLED_APPS, then it will automatically serve static files. If you don't want to serve static, then use runserver --nostatic. collectstatic or STATIC_ROOT has no relation to this command.

collectstatic:

This command collects all static files from different STATIC_DIRS, and put them in folder which is defined by STATIC_ROOT. collectstatic is very useful in production deployment, when you are using a reverse proxy server like NGINX or Apache etc. NGINX/Apache/Varnish uses that folder (where collectstatic stored the static files) as root and serve static from it. It is not recommended to use runserver in production. You can use gunicorn/uwsgi to serve django. But gunicorn/uwsgi does not serve static files, hence using reverse proxy server to serve static files.

finally:

To answer your questions:

No you don't have to put that in your code, unless you are not adding django.contrib.staticfiles in your INSTALLED_APPS.

No

You don't need to. STATIC_ROOT is used for different purpose

It is not. But for serving MEDIA files, you can add the following pattern:

if settings.DEBUG:
    urlpatterns += [
        re_path(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
    ]

In production, media files should be served by reverse proxy server as well.


问:
view.findViewById() returns null in one function but works fine in other one
I am trying to get a TextView object using view.findViewById() in a function which is called when a button is clicked. In the onClickButton() null is returned whereas in other function setDefaultValues() it works fine.

Activity1.java

```<code>public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);
        setDefaultValues();
    }

    private void setDefaultValues() {
        TextView tipView = findViewById(R.id.tipView);
       tipView.setText(getString(R.string.main_msg_tip,Double.toString(TIP)));
    }

    public void onClickToggleButton(View view){
        TextView tipView = view.findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
}

</code>```

When testing the app the following error message was shown:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referenceat com.example.chandan.learning.Activity1.onClickToggleButton
</code>```

Edit : The activity_1.xml file does contain the TextView with tipView id so the theory that element is not present in the XML file is out of the window.

答:
It is a bad practice to duplicate code. Now you have duplication of method findViewById. To avoid that, you should create a global variable in the class Activity1. That will also be solution of your problem:

```<code>public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    private TextView tipView;

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

    private void setDefaultValues() {
        tipView = findViewById(R.id.tipView);
        tipView.setText(getString(R.string.main_msg_tip, Double.toString(TIP)));
    }

    public void onClickToggleButton(View view) {
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
    }
}
</code>```

Body:
I am trying to get a TextView object using view.findViewById() in a function which is called when a button is clicked. In the onClickButton() null is returned whereas in other function setDefaultValues() it works fine.

Activity1.java

public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);
        setDefaultValues();
    }

    private void setDefaultValues() {
        TextView tipView = findViewById(R.id.tipView);
       tipView.setText(getString(R.string.main_msg_tip,Double.toString(TIP)));
    }

    public void onClickToggleButton(View view){
        TextView tipView = view.findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
}

When testing the app the following error message was shown:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referenceat com.example.chandan.learning.Activity1.onClickToggleButton

Edit : The activity_1.xml file does contain the TextView with tipView id so the theory that element is not present in the XML file is out of the window.

Body:
It is a bad practice to duplicate code. Now you have duplication of method findViewById. To avoid that, you should create a global variable in the class Activity1. That will also be solution of your problem:

public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    private TextView tipView;

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

    private void setDefaultValues() {
        tipView = findViewById(R.id.tipView);
        tipView.setText(getString(R.string.main_msg_tip, Double.toString(TIP)));
    }

    public void onClickToggleButton(View view) {
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
    }
}


问:
Will my virtual environment folder still work if i shift it from my local machine to a shared folder?
Currently, I have a Flask app waiting to be shifted to a shared drive in the company's local network. My current plan is to create a virtual environment inside a folder locally, install all the necessary dependencies like Python3, Flask, Pandas and etc. This is to ensure that my Flask app can still reference to necessary dependencies to run the app.

As I can't access my shared drive via command prompt, my plan is to create a virtual environment locally then shift it to the shared folder together with all the scripts required by my Flask app. Will the app be able to run on the shared drive in this manner?

答:
The standard virtualenv hardcodes the path of the environment into some of its files in the environment it creates, and stops working if you rename it etc. So no, you'll probably have to recreate the env on the destination server.

Perhaps your app's startup script could take care of creating the env if it's missing.