问:
installing mingw-w64-v7 : configuration error
I'm trying to install on windows 10 mingw-w64-v7. So I download source from sourceforge and I tried to compile them on my computer. But It doesn't work.

The command ./configure give me :

```<code>./configure
checking whether to enable maintainer-specific portions of Makefiles... no
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking whether to build the headers... yes
checking whether to build the crt... yes
checking whether to build the optional libraries... no
checking whether to build the optional tools... no
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
=== configuring in mingw-w64-headers (/c/Users/Guillaume/Documents/build/mingw-w64-v7.0.0/mingw-w64-headers)
configure: running /bin/sh ./configure --disable-option-checking '--prefix=/usr/local'  --cache-file=/dev/null --srcdir=.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking whether to enable maintainer-specific portions of Makefiles... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking for a sed that does not truncate output... /usr/bin/sed
checking whether to rebuild headers with widl... no
checking whether to build a w32api package for Cygwin... no
checking for c-runtime headers... yes
checking for optional sdk headers... ddk,directx
checking if installing idl files is enabled... no
checking default _WIN32_WINNT version... 0x502
checking default msvcrt... msvcrt (0x700)
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating crt/_mingw.h
config.status: creating config.h
=== configuring in mingw-w64-crt (/c/Users/Guillaume/Documents/build/mingw-w64-v7.0.0/mingw-w64-crt)
configure: running /bin/sh ./configure --disable-option-checking '--prefix=/usr/local'  --cache-file=/dev/null --srcdir=.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking whether to enable maintainer-specific portions of Makefiles... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking for sysroot... /usr/local
checking for a sed that does not truncate output... /usr/bin/sed
checking for gawk... (cached) gawk
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.exe
checking for suffix of executables... .exe
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking for style of include used by make... none
checking dependency style of gcc... none
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... none
checking how to run the C preprocessor... gcc -E
checking for ranlib... ranlib
checking for dlltool... dlltool
checking for ar... ar
checking the archiver (ar) interface... ar
checking dependency style of gcc... none
checking for as... as
checking whether to build a w32api package for Cygwin... no
checking whether to build the Win32 libraries... yes
checking whether to build the Win64 libraries... no
checking whether to build the WinARM32 libraries... no
checking whether to build the WinARM64 libraries... no
checking whether to use genlib... no
checking whether to enable globbing... no
checking whether to enable private exports... no
checking whether to enable delay import libs... no
checking what to provide as libmsvcrt.a... msvcrt-os
checking whether to enable experimental features... no
checking whether the compiler supports -municode... no
checking whether the linker provides __CTOR_LIST__... yes
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking _mingw_mac.h usability... no
checking _mingw_mac.h presence... no
checking for _mingw_mac.h... no
configure: error: Please check if the mingw-w64 header set and the build/host option are set properly.
configure: error: ./configure failed for mingw-w64-crt
</code>```

I am not really experiment with windows. I need to compile my C++17 code on windows. What can I do to resolve my problem ?

答: A recent version of MinGW-w64 7.0.0 with the latest GCC 10 for Windows can be found at http://winlibs.com/</p>

Body:
I'm trying to install on windows 10 mingw-w64-v7. So I download source from sourceforge and I tried to compile them on my computer. But It doesn't work.

The command ./configure give me :

./configure
checking whether to enable maintainer-specific portions of Makefiles... no
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking whether to build the headers... yes
checking whether to build the crt... yes
checking whether to build the optional libraries... no
checking whether to build the optional tools... no
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
=== configuring in mingw-w64-headers (/c/Users/Guillaume/Documents/build/mingw-w64-v7.0.0/mingw-w64-headers)
configure: running /bin/sh ./configure --disable-option-checking '--prefix=/usr/local'  --cache-file=/dev/null --srcdir=.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking whether to enable maintainer-specific portions of Makefiles... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking for a sed that does not truncate output... /usr/bin/sed
checking whether to rebuild headers with widl... no
checking whether to build a w32api package for Cygwin... no
checking for c-runtime headers... yes
checking for optional sdk headers... ddk,directx
checking if installing idl files is enabled... no
checking default _WIN32_WINNT version... 0x502
checking default msvcrt... msvcrt (0x700)
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating crt/_mingw.h
config.status: creating config.h
=== configuring in mingw-w64-crt (/c/Users/Guillaume/Documents/build/mingw-w64-v7.0.0/mingw-w64-crt)
configure: running /bin/sh ./configure --disable-option-checking '--prefix=/usr/local'  --cache-file=/dev/null --srcdir=.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking whether to enable maintainer-specific portions of Makefiles... no
checking build system type... x86_64-pc-mingw64
checking host system type... x86_64-pc-mingw64
checking for sysroot... /usr/local
checking for a sed that does not truncate output... /usr/bin/sed
checking for gawk... (cached) gawk
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.exe
checking for suffix of executables... .exe
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking for style of include used by make... none
checking dependency style of gcc... none
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... none
checking how to run the C preprocessor... gcc -E
checking for ranlib... ranlib
checking for dlltool... dlltool
checking for ar... ar
checking the archiver (ar) interface... ar
checking dependency style of gcc... none
checking for as... as
checking whether to build a w32api package for Cygwin... no
checking whether to build the Win32 libraries... yes
checking whether to build the Win64 libraries... no
checking whether to build the WinARM32 libraries... no
checking whether to build the WinARM64 libraries... no
checking whether to use genlib... no
checking whether to enable globbing... no
checking whether to enable private exports... no
checking whether to enable delay import libs... no
checking what to provide as libmsvcrt.a... msvcrt-os
checking whether to enable experimental features... no
checking whether the compiler supports -municode... no
checking whether the linker provides __CTOR_LIST__... yes
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking _mingw_mac.h usability... no
checking _mingw_mac.h presence... no
checking for _mingw_mac.h... no
configure: error: Please check if the mingw-w64 header set and the build/host option are set properly.
configure: error: ./configure failed for mingw-w64-crt

I am not really experiment with windows. I need to compile my C++17 code on windows. What can I do to resolve my problem ?


来源: stackexchange

问:
Get past 20 rows in a column
I am trying to calculate the 20 day simple moving average of stock data from a data frame called data
These are the column names of the data frame:
1. open   2. high  3. low  4. close 5. SMA

I want each value in the SMA to be the average of the past 20 values in  4. close
I tried using
data['5. SMA'] = np.average(data['4. close'][:21])
 but it only returns a single value throughout the data column (which is understandable because the code works on the first 20 values only). However, I for each row in 5. SMA, I want to work with the past 20 values in 4. close.
How can I implement this using numpy or pandas?

答:
Usually googling pandas documentation gives a great outcome. Try this perhaps:</p>

```<code>s = pd.Series([1, 2, 3, 4])
s.rolling(2).mean()
0    NaN
1    1.5
2    2.5
3    3.5
dtype: float64
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get past 20 rows in a column

Body:
Usually googling pandas documentation gives a great outcome. Try this perhaps:

s = pd.Series([1, 2, 3, 4])
s.rolling(2).mean()
0    NaN
1    1.5
2    2.5
3    3.5
dtype: float64


问:
Serve static files with flask on development and nginx on production
Let's say I've got this mcve:

mcve.py

```<code>import textwrap
from pathlib import Path
from flask import Flask

working_dir = Path(__file__).parent
app = Flask(
    __name__,
    # static_folder=str(working_dir / "uploads"),
)

@app.route("/test")
def index():
    return textwrap.dedent(
        """
        <!DOCTYPE html>
        <html>
        <head>
            <title>Hello world</title>
        </head>
        <body>
            <img src="foo/foo.png">
            <img src="bar/bar.png">
        </body>
        </html>
    """
    ).strip()

if __name__ == "__main__":
    with app.test_client() as c:
        print(c.get("/test").data.decode("utf-8"))
</code>```

run.bat

```<code>set FLASK_APP=mcve.py
set FLASK_ENV=development
flask run
</code>```

If I execute run.bat and then I go to http://localhost:5000/test in the browser I'll get:

```<code>>flask run
 * Serving Flask app "x.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with windowsapi reloader
 * Debugger is active!
 * Debugger PIN: 497-008-397
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [31/May/2020 22:32:19] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /foo/foo.png HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /bar/bar.png HTTP/1.1" 404 -
</code>```

Question

How should I modify mcve.py to server the images properly (now you can see is giving 404) in development using flask's server but then serve them properly with nginx on production?

答:
You don't have to configure flask specifically for this. These logs:

```<code>127.0.0.1 - - [31/May/2020 22:32:19] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /foo/foo.png HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /bar/bar.png HTTP/1.1" 404 -
</code>```

are actually generated by the werkzeug development server that's serving the static content for you. When you move to using nginx, you can intercept the GET requests with a URL rule. From the example nginx config file from the Flask Mega Tutorial:

```<code>...

server {

    ...

    location / {
        # forward application requests to the gunicorn server
        proxy_pass http://localhost:8000;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static {
        # handle static files directly, without forwarding to the application
        alias /home/ubuntu/microblog/app/static;
        expires 30d;
    }
}
</code>```

Note the /location rule that handles requests to static directly, so those requests from the browser wouldn't even hit whatever is serving your flask app in production. There are many more methods for matching urls that you can find, e.g. here. It's perfectly possible to add multiple such rules to look in separate locations but you'll want to structure the app to give these files a distinct location so you can implement such rules.

Separately, to get around your current 404s, look at the template docs for Jinja2 and use the url_for method to make sure it resolves relative paths correctly.

For example, if I want to include:

```<code><link href='static/css/bootstrap-4.3.1.min.css' rel="stylesheet">
</code>```

I would instead use:

```<code><link href="{{ url_for('static', filename='css/bootstrap-4.3.1.min.css') }}" rel="stylesheet">
</code>```

This passes off the responsibility of path resolution to the app, so no matter how many hyperlinks I've followed or blueprints I'm using, this path will always resolve to the correct static directory when the template is rendered.

I'm not sure this will work with return textwrap.dedent because it might not invoke Jinja on the template. You can import render_template_string for a throwaway example like you have here, but render_template will work in your actual app too.

Body:
Let's say I've got this mcve:

mcve.py

import textwrap
from pathlib import Path
from flask import Flask

working_dir = Path(__file__).parent
app = Flask(
    __name__,
    # static_folder=str(working_dir / "uploads"),
)

@app.route("/test")
def index():
    return textwrap.dedent(
        """
        <!DOCTYPE html>

            <title>Hello world</title>

    """
    ).strip()

if __name__ == "__main__":
    with app.test_client() as c:
        print(c.get("/test").data.decode("utf-8"))

run.bat

set FLASK_APP=mcve.py
set FLASK_ENV=development
flask run

If I execute run.bat and then I go to http://localhost:5000/test in the browser I'll get:

>flask run
 * Serving Flask app "x.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with windowsapi reloader
 * Debugger is active!
 * Debugger PIN: 497-008-397
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [31/May/2020 22:32:19] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /foo/foo.png HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /bar/bar.png HTTP/1.1" 404 -

Question

How should I modify mcve.py to server the images properly (now you can see is giving 404) in development using flask's server but then serve them properly with nginx on production?

Body:
You don't have to configure flask specifically for this. These logs:

127.0.0.1 - - [31/May/2020 22:32:19] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /foo/foo.png HTTP/1.1" 404 -
127.0.0.1 - - [31/May/2020 22:32:22] "GET /bar/bar.png HTTP/1.1" 404 -

are actually generated by the werkzeug development server that's serving the static content for you. When you move to using nginx, you can intercept the GET requests with a URL rule. From the example nginx config file from the Flask Mega Tutorial:

...

server {

    ...

    location / {
        # forward application requests to the gunicorn server
        proxy_pass http://localhost:8000;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static {
        # handle static files directly, without forwarding to the application
        alias /home/ubuntu/microblog/app/static;
        expires 30d;
    }
}

Note the /location rule that handles requests to static directly, so those requests from the browser wouldn't even hit whatever is serving your flask app in production. There are many more methods for matching urls that you can find, e.g. here. It's perfectly possible to add multiple such rules to look in separate locations but you'll want to structure the app to give these files a distinct location so you can implement such rules.

Separately, to get around your current 404s, look at the template docs for Jinja2 and use the url_for method to make sure it resolves relative paths correctly.

For example, if I want to include:

<link href='static/css/bootstrap-4.3.1.min.css' rel="stylesheet">

I would instead use:

<link href="{{ url_for('static', filename='css/bootstrap-4.3.1.min.css') }}" rel="stylesheet">

This passes off the responsibility of path resolution to the app, so no matter how many hyperlinks I've followed or blueprints I'm using, this path will always resolve to the correct static directory when the template is rendered.

I'm not sure this will work with return textwrap.dedent because it might not invoke Jinja on the template. You can import render_template_string for a throwaway example like you have here, but render_template will work in your actual app too.


问:
When do values passed to a parameter require quotes?
I have been working with Exchange Online unified groups and Microsoft Teams teams in powershell: New-UnifiedGroup, Set-UnifiedGroup, Get-UnifiedGroup, New-Team, Get-Team etc. I have been creating groups and teams from PowerShell.

I am interested in understanding a bit better when a value for a parameter requires quotes and when it does not.

When I import from CSV, it seems the values are automatically interpreted as strings. When I supply them to a parameter that requires a string, the value does not require quotes even if it has spaces e.g New-UnifiedGroup -DisplayName $item.displayName does not require quotes even when the display name has spaces.

But when I want to create a team from an existing group, and I get the ID of the group, the group id requires quotes: New-Teams -GroupId "$group.ExternalDirectoryObjectId". In this case the parameter -GroupId requires a string value, although the ExternalDirectoryObjectId that it requires is not a string.

Is there a rule that a value does not require quotes if it is a string, and a string value is expected? Does it help to declare a variable as a string before passing it to a parameter that requires a string? For example, if I have a $path variable, I usually have to provide it as -Path "$path". If I declared the path as [String]$path =, would I then not need to use the quotes in -Path $path

答:
Generally, only ever use quoting in PowerShell to explicitly pass a value as a string ([string]).

String literals require quoting if they contain any of the following: spaces or, more generally, PowerShell metacharacters[1], and commands or expressions as part of a larger string (which must then be enclosed in $(...) - see below).

To pass the value of a variable, one of its properties, or even the result of a method call on it, you do not need quoting in PowerShell, which will pass the resulting value with its original data type; however, when the value is bound to its target parameter, PowerShell may automatically convert it to the parameter's type.

If the target parameter is [string]-typed (as is the case with New-Team's -GroupId parameter), PowerShell will automatically convert any non-string argument to a string, essentially by calling .ToString() on it[2].  If the resulting string isn't the right representation, you must perform explicit stringification, by way of an expression or command.

E.g., both -GroupId $groupId and -GroupId $group.ExternalDirectoryObjectId would work - even if the resulting string contains embedded spaces or other PowerShell metacharacters.

If you need to pass an object's property, a method call, or any type of command or expression as part of a larger string, enclose the argument in "..." and use $(...), the subexpression operator around the expression / command (e.g., "$($group.ExternalDirectoryObjectId)/more"; referencing a variable by itself inside "..." does not require $(...)).

"$group.ExternalDirectoryObjectId" definitely does not work as intended, because only variable reference $group by itself is recognized - and stringified - whereas the .ExternalDirectoryObjectId part is treated literally - see first link below for why.

Further reading:

Overview of PowerShell's expandable strings (string interpolation, "...")

String literals in PowerShell (bottom section)

How unquoted tokens are parsed as arguments.

[1] The metacharacters are (some only need quoting if at the start of the argument):

<space> ' " ` , ; ( ) { } | & < > @ #

[2] The exact stringification rules, where culture-sensitivity factors in as well, are detailed in this answer.

Generally, PowerShell has a very flexible automatic type-conversion system whose rules are complex and not explicitly documented - a peek at the source code may help.

PowerShell always tries to automatically convert a given value to the target type, where the target type may be dictated by a parameter's type or the (usually) LHS operand of an operator-based expression (e.g., 42 + "1" yields 43).


问:
This script does not populate sheet after parsing retrieved data
I hope this is well explained. First of all, sorry because my coding background is zero and I am just trying to "fix" a previously written script.

Problem The script  does not populate sheet after parsing retrieved data if the function is triggered by timer and the sheet is not open in my browser .

The script works OK if run it manually while sheet is open.

Problem details:
When I open the sheet the cells are stuck showing "Loading" and after a short time, data is written.

Expected behavior is to get the data written no matter if I don't open the sheet.

Additional info: This is how I manually run the function

```<code>function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [
    {name: "Manual Push Report", functionName: "runTool"}
     ];
  sheet.addMenu("PageSpeed Menu", entries);
}
</code>```

Additional info: I set the triggers with Google Apps Script GUI See the trigger

Before posting the script code, you can see how the cells look in the sheet:

Script code

```<code>function runTool() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var rows = activeSheet.getLastRow();

  for(var i=3; i <= rows; i++){
    var workingCell = activeSheet.getRange(i, 2).getValue();
    var stuff = "=runCheck"

     if(workingCell != ""){
     activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");

     }
     }
}

// URL check //

function runCheck(Url) {

  var key = "XXXX Google PageSpeed API Key";
  var strategy = "desktop"

    var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key + "&strategy=" + strategy +"";

    var array = [];

    var response = UrlFetchApp.fetch(serviceUrl);

    if (response.getResponseCode() == 200) {
        var content = JSON.parse(response.getContentText());

        if ((content != null) && (content["lighthouseResult"] != null)) {

                if (content["captchaResult"]) {
                      var score = content["lighthouseResult"]["categories"]["performance"]["score"];

            } else {
                      var score = "An error occured";

            }
        }

    array.push([score,"complete"]);
    Utilities.sleep(1000);
    return array;
}
}

</code>```

You can try the code using the sheet below with a valid Pagespeed API key.

You only need to add a Trigger and wait for it's execution while the sheet is not open in your browser

https://docs.google.com/spreadsheets/d/1ED2u3bKpS0vaJdlCwsLOrZTp5U0_T8nZkmFHVluNvKY/copy

答:
I suggest you to change your algorithm. Instead of using a custom function to call UrlFetchApp, do that call in the function called by a time-driven trigger.

You could keep your runCheck as is, just replace

```<code>activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");
</code>```

by

```<code> activeSheet.getRange(i, 3, 1, 2).setValues(runCheck(url));
</code>```

NOTE

Custom functions are calculated when the spreadsheet is opened and when its arguments changes while the spreadsheet is open.

Related

Cache custom function result between spreadsheet opens

Body:
I hope this is well explained. First of all, sorry because my coding background is zero and I am just trying to "fix" a previously written script.

Problem The script  does not populate sheet after parsing retrieved data if the function is triggered by timer and the sheet is not open in my browser .

The script works OK if run it manually while sheet is open.

Problem details:
When I open the sheet the cells are stuck showing "Loading" and after a short time, data is written.

Expected behavior is to get the data written no matter if I don't open the sheet.

Additional info: This is how I manually run the function

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [
    {name: "Manual Push Report", functionName: "runTool"}
     ];
  sheet.addMenu("PageSpeed Menu", entries);
}

Additional info: I set the triggers with Google Apps Script GUI See the trigger

Before posting the script code, you can see how the cells look in the sheet:

Script code

function runTool() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var rows = activeSheet.getLastRow();

  for(var i=3; i <= rows; i++){
    var workingCell = activeSheet.getRange(i, 2).getValue();
    var stuff = "=runCheck"

     if(workingCell != ""){
     activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");

     }
     }
}

// URL check //

function runCheck(Url) {

  var key = "XXXX Google PageSpeed API Key";
  var strategy = "desktop"

    var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key + "&strategy=" + strategy +"";

    var array = [];

    var response = UrlFetchApp.fetch(serviceUrl);

    if (response.getResponseCode() == 200) {
        var content = JSON.parse(response.getContentText());

        if ((content != null) && (content["lighthouseResult"] != null)) {

                if (content["captchaResult"]) {
                      var score = content["lighthouseResult"]["categories"]["performance"]["score"];

            } else {
                      var score = "An error occured";

            }
        }

    array.push([score,"complete"]);
    Utilities.sleep(1000);
    return array;
}
}

You can try the code using the sheet below with a valid Pagespeed API key.

You only need to add a Trigger and wait for it's execution while the sheet is not open in your browser

https://docs.google.com/spreadsheets/d/1ED2u3bKpS0vaJdlCwsLOrZTp5U0_T8nZkmFHVluNvKY/copy

Body:
I suggest you to change your algorithm. Instead of using a custom function to call UrlFetchApp, do that call in the function called by a time-driven trigger.

You could keep your runCheck as is, just replace

activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");

by

 activeSheet.getRange(i, 3, 1, 2).setValues(runCheck(url));

NOTE

Custom functions are calculated when the spreadsheet is opened and when its arguments changes while the spreadsheet is open.

Related

Cache custom function result between spreadsheet opens


问:
Node + Docker Compose: Development and production setup
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

```<code>FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead
</code>```

docker-compose.yml

```<code>version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"
</code>```

package.json

```<code>// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...
</code>```

答:
You can create a structure like this:

```<code>docker-compose.yml -->
      docker-compose.dev.yml
      docker-compose.prod.yml
</code>```

Where the base configuration resides in docker-compose.yml, while environment-specific info such as ports or user credentials would be in docker-compose.dev.yml or docker-compose.prod.yml

And then you can run the dev environment with:

```<code>docker-compose \
    -f docker-compose.yml \
    -f docker-compose.dev.yml \
    up -d
</code>```

Or the prod environment with:

```<code>docker-compose \
    -f docker-compose.yml \
    -f docker-compose.prod.yml \
    up -d
</code>```

Body:
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead

docker-compose.yml

version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"

package.json

// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...

Body:
You can create a structure like this:

docker-compose.yml -->
      docker-compose.dev.yml
      docker-compose.prod.yml

Where the base configuration resides in docker-compose.yml, while environment-specific info such as ports or user credentials would be in docker-compose.dev.yml or docker-compose.prod.yml

And then you can run the dev environment with:

docker-compose \
    -f docker-compose.yml \
    -f docker-compose.dev.yml \
    up -d

Or the prod environment with:

docker-compose \
    -f docker-compose.yml \
    -f docker-compose.prod.yml \
    up -d


问:
How to customize Android's LockScreen?
I know that there is already some apps can do this, such as:

WidgetLocker Lockscreen

Flyscreen

I want to know how to do this in my app? What classes I can use? Or what articles I should read? I don't want to change the Android's source code.

And I wonder if it will be different to deal with when the screen is locked by draw pattern?

答: Have a look at this answer. You need to write your own home screen app which will implement the lockscreen behaviour that you require. There is sample code for writing your own home screen app in the Android SDK.</p>

ContentLicense: CC BY-SA 3.0

Title: How to customize Android's LockScreen?


问:
Why do I get a NullReferenceException when defining a nullable owned type in EF Core 3.1?
I'm connecting to a Cosmos DB instance using Entity Framework Core 3.1.4.

I have a Broadcast class that contains a property of owned type Availability.

I don't want Availability to be mapped as an Entity. Availabilities don't have Ids, nor should they be stored in their own containers. Availabilities are nullable. The classes look like:

```<code>public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public Availability Availability { get; set; }
}

[Owned]
public class Availability
{
    public DateTime? Start { get; set; }
    public DateTime? End { get; set; }
}

public class BroadcastContext : DbContext
{
    public DbSet<Broadcast> Broadcast{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Broadcast>().OwnsOne(e => e.Availability).WithOwner();
    }
}
</code>```

So an item inside the Broadcast container in the DB should look like:

```<code>{
   id: "GUID",
   Name: "Foobar Broadcast",
   Availability: {
     Start: FooDate,
     End: BarDate
   }
}
</code>```

When trying to Add a new Broadcast object with "Availability" set to null, this line: modelBuilder.Entity<Channel>().OwnsOne(e => e.Availabilities).WithOwner(); throws the following exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I understand that EF Core 3.0 supports nullable Owned Types.

Am I missing something? How can I sort this out?.

答:
When using navigation properties in EF, you want to use the virtual keyword.  This will allow EF to perform an override on the property.

Try changing Broadcast to the following:

```<code>public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public virtual Availability Availability { get; set; } //added virtual keyword.
}
</code>```

Body:
I'm connecting to a Cosmos DB instance using Entity Framework Core 3.1.4.

I have a Broadcast class that contains a property of owned type Availability.

I don't want Availability to be mapped as an Entity. Availabilities don't have Ids, nor should they be stored in their own containers. Availabilities are nullable. The classes look like:

public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public Availability Availability { get; set; }
}

[Owned]
public class Availability
{
    public DateTime? Start { get; set; }
    public DateTime? End { get; set; }
}

public class BroadcastContext : DbContext
{
    public DbSet<Broadcast> Broadcast{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Broadcast>().OwnsOne(e => e.Availability).WithOwner();
    }
}

So an item inside the Broadcast container in the DB should look like:

{
   id: "GUID",
   Name: "Foobar Broadcast",
   Availability: {
     Start: FooDate,
     End: BarDate
   }
}

When trying to Add a new Broadcast object with "Availability" set to null, this line: modelBuilder.Entity<Channel>().OwnsOne(e => e.Availabilities).WithOwner(); throws the following exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I understand that EF Core 3.0 supports nullable Owned Types.

Am I missing something? How can I sort this out?.

Body:
When using navigation properties in EF, you want to use the virtual keyword.  This will allow EF to perform an override on the property.

Try changing Broadcast to the following:

public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public virtual Availability Availability { get; set; } //added virtual keyword.
}


问:
Typescript type declarations for Promise that returns a React Component
I have the following function:

```<code>const withCacheRefresh = (lazyLoadComponent: any) => {
  return new Promise<React.ComponentType<any>>((resolve) => {
    lazyLoadComponent()
      .then(resolve)
      .catch(() => {
        window.location.reload(true);
      });
  });
}
</code>```

It takes in a promise as an argument, specifically lazy. I proceed to call the promise, either resolving the promise by returning the result of lazy, or in my catch, refresh the page. I'm running into issues with the following Typescript compilation error:

```<code>Type 'Promise<ComponentType<any>>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Type 'ComponentType<any>' is not assignable to type '{ default: ComponentType<any>; }'.
    Property 'default' is missing in type 'ComponentClass<any, any>' but required in type '{ default: ComponentType<any>; }'.  TS2322
</code>```

I have two questions:

How can I specify my first argument lazyLoadComponent to be of the type for a function that returns a component of React.Component<any> type instead of just any?

How can I fix my Promise<React.ComponentType<any>> definition such that it conforms to the required type of Promise<{ default: ComponentType<any>; }> ?

Update

I've received answers telling me that my solution is incorrect for my stated problem, but I purposely chose to omit details about the nuances of my larger problem space.

Since it was asked, I feel like there's no pain clarifying: when new deployments get released for my application, new chunks get created, and the old ones purged from the production workspace. Consequently, clients that still remain in the previous release (since the app hasn't been refreshed to the latest version) are still using old chunks. HMR would not work since this is a production environment. An explicit refresh would cause the service workers to retrieve the latest chunks.

A similar circumstance is described in this Github Issue.

答:
This is a convoluted (and slightly incorrect) way of doing things.

I'm going to assume you have a reason for reloading the page on an error other than "I hope it fixes the error" (if that's the reason or if it's for cache-busting purposes, you should definitely try HMR).

EDIT Since OP has clarified what he meant, I'd suggest, instead of hoping the browser doesn't cache the lazy-loaded component and thereby errors when a new version is rolled out, to use a precache manifest in the Service Worker itself, which would allow the SW to load the manifest whenever a new one is regestired. See this question for more info. You can integrate it into the bundler itself with the Workbox plugin, even if you don't use Workbox.

I'm also going to assume you want to use this with lazy, not call it on lazy, because otherwise it's not exactly possible to catch any errors.

```<code>import React from 'react';

type LazyFactory = Parameters<typeof React.lazy>[0];

const withCacheRefresh = (
  importResult: LazyFactory
): LazyFactory => () =>
  importResult().catch(() => {
    window.location.reload(true);
    // Following makes return type `never`, which satisfies TypeScript
    throw new Error('component load failed');
  });
</code>```

There's no need to wrap it in a promise because it already is one. You can just .catch on it directly.

Usage:

```<code>const MyLazyComponent = React.lazy(withCacheRefresh(() => import('./Component')));
</code>```

Body:
I have the following function:

const withCacheRefresh = (lazyLoadComponent: any) => {
  return new Promise<React.ComponentType<any>>((resolve) => {
    lazyLoadComponent()
      .then(resolve)
      .catch(() => {
        window.location.reload(true);
      });
  });
}

It takes in a promise as an argument, specifically lazy. I proceed to call the promise, either resolving the promise by returning the result of lazy, or in my catch, refresh the page. I'm running into issues with the following Typescript compilation error:

Type 'Promise<ComponentType<any>>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Type 'ComponentType<any>' is not assignable to type '{ default: ComponentType<any>; }'.
    Property 'default' is missing in type 'ComponentClass<any, any>' but required in type '{ default: ComponentType<any>; }'.  TS2322

I have two questions:

How can I specify my first argument lazyLoadComponent to be of the type for a function that returns a component of React.Component<any> type instead of just any?

How can I fix my Promise<React.ComponentType<any>> definition such that it conforms to the required type of Promise<{ default: ComponentType<any>; }> ?

Update

I've received answers telling me that my solution is incorrect for my stated problem, but I purposely chose to omit details about the nuances of my larger problem space.

Since it was asked, I feel like there's no pain clarifying: when new deployments get released for my application, new chunks get created, and the old ones purged from the production workspace. Consequently, clients that still remain in the previous release (since the app hasn't been refreshed to the latest version) are still using old chunks. HMR would not work since this is a production environment. An explicit refresh would cause the service workers to retrieve the latest chunks.

A similar circumstance is described in this Github Issue.

Body:
This is a convoluted (and slightly incorrect) way of doing things.

I'm going to assume you have a reason for reloading the page on an error other than "I hope it fixes the error" (if that's the reason or if it's for cache-busting purposes, you should definitely try HMR).

EDIT Since OP has clarified what he meant, I'd suggest, instead of hoping the browser doesn't cache the lazy-loaded component and thereby errors when a new version is rolled out, to use a precache manifest in the Service Worker itself, which would allow the SW to load the manifest whenever a new one is regestired. See this question for more info. You can integrate it into the bundler itself with the Workbox plugin, even if you don't use Workbox.

I'm also going to assume you want to use this with lazy, not call it on lazy, because otherwise it's not exactly possible to catch any errors.

import React from 'react';

type LazyFactory = Parameters<typeof React.lazy>[0];

const withCacheRefresh = (
  importResult: LazyFactory
): LazyFactory => () =>
  importResult().catch(() => {
    window.location.reload(true);
    // Following makes return type `never`, which satisfies TypeScript
    throw new Error('component load failed');
  });

There's no need to wrap it in a promise because it already is one. You can just .catch on it directly.

Usage:

const MyLazyComponent = React.lazy(withCacheRefresh(() => import('./Component')));


问:
For a large project, what planning should be done before coding and how should it be approached?
What is your method of "mapping out" an idea before creating it?

Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace.  What planning/design steps should I take before I start the actual work?

For example, should I map everything out page by page (their functionalities, data, etc.)?

答: For a large project first think of a one-liner to description of your site (try to not use any buzzwords here). Next think of three design maxims (rules your design Should never conflict with). Then draw a few views and think up a few user cases (1 day) then work in code for 2 weeks (this will be a throw away prototype so just work as fast as you can forget about bugs and details, don't worry about code smells or design patterns, just make as much as you can), then revaluate all the steps above and throw away your two week prototype, and begin your project in a serious manner applying solid engineering and design. After a month has gone by evaluate your(team) moral and get feedback. If it all seems to be going ok, continue, you got a long ride ahead, otherwise just give up, do a postmortem, and start over with new goals.</p>

OwnerDisplayName: sarmenhb

LastEditorDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Robert Gould


问:
Why is docker-compose volume not mounting correctly? (I'm using nginx and certbot with docker)
I'm trying to get certbot docker container to work with my angular/node setup, but Im struggling to mount the requisite shared volumes.  I am following the tutorial here and also here but I'm obviously not following something.  Here is my docker compose ... the angular/node bit works fine on its own so I won't post the Dockerfiles.

What I think I'm trying to achieve below, is to make the static files within my angular container at path /usr/share/nginx/html available to the certbox container so it can work its magic...

```<code>version: '3'
services:

  angular:
    build: angular
    depends_on:
      - nodejs
    ports:
      - "80:80"
    volumes:
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
      - web-root:/usr/share/nginx/html

  certbot:
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
      - web-root:/usr/share/nginx/html
    depends_on:
      - angular
    command: certonly --webroot --webroot-path=/usr/share/nginx/html --email ivyterrace@hotmail.co.uk --agree-tos --no-eff-email --staging -d trailscape.cc -d www.trailscape.cc

  nodejs:
    build: nodejs
    volumes:
      - ./data:/data
    ports:
      - "8080:8080"

volumes:
    certbot-etc:
    certbot-var:
    web-root:
</code>```

The problem I have is mounting the web-root volume .. when I inspect the certbot docker image i get:

```<code>            "Volumes": {
                "/etc/letsencrypt": {},
                "/var/lib/letsencrypt": {}
            },
</code>```

No  /usr/share/nginx/html.  If I inspect the angular image its even worse:

```<code>            "Volumes": null,
</code>```

But if I view volumes using docker volume ls, I can see the web-root volume:

```<code>DRIVER              VOLUME NAME
local               ivyterrace_certbot-etc
local               ivyterrace_certbot-var
local               ivyterrace_web-root
</code>```

What's going on, why are my named volumes not mounting correctly?  The nodejs volume mounts fine.

I've been trying to wkr this out for two days so any pointers appreciated.

答:
It can be permission problem, the first try with sudo(if OS is linux)

Second: try change volumes like this.

```<code> volumes:
      - ../data/certbot-etc:/etc/letsencrypt
</code>```

Hope your OS is not windows.

Body:
I'm trying to get certbot docker container to work with my angular/node setup, but Im struggling to mount the requisite shared volumes.  I am following the tutorial here and also here but I'm obviously not following something.  Here is my docker compose ... the angular/node bit works fine on its own so I won't post the Dockerfiles.

What I think I'm trying to achieve below, is to make the static files within my angular container at path /usr/share/nginx/html available to the certbox container so it can work its magic...

version: '3'
services:

  angular:
    build: angular
    depends_on:
      - nodejs
    ports:
      - "80:80"
    volumes:
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
      - web-root:/usr/share/nginx/html

  certbot:
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
      - web-root:/usr/share/nginx/html
    depends_on:
      - angular
    command: certonly --webroot --webroot-path=/usr/share/nginx/html --email ivyterrace@hotmail.co.uk --agree-tos --no-eff-email --staging -d trailscape.cc -d www.trailscape.cc

  nodejs:
    build: nodejs
    volumes:
      - ./data:/data
    ports:
      - "8080:8080"

volumes:
    certbot-etc:
    certbot-var:
    web-root:

The problem I have is mounting the web-root volume .. when I inspect the certbot docker image i get:

            "Volumes": {
                "/etc/letsencrypt": {},
                "/var/lib/letsencrypt": {}
            },

No  /usr/share/nginx/html.  If I inspect the angular image its even worse:

            "Volumes": null,

But if I view volumes using docker volume ls, I can see the web-root volume:

DRIVER              VOLUME NAME
local               ivyterrace_certbot-etc
local               ivyterrace_certbot-var
local               ivyterrace_web-root

What's going on, why are my named volumes not mounting correctly?  The nodejs volume mounts fine.

I've been trying to wkr this out for two days so any pointers appreciated.

Body:
It can be permission problem, the first try with sudo(if OS is linux)

Second: try change volumes like this.

 volumes:
      - ../data/certbot-etc:/etc/letsencrypt

Hope your OS is not windows.


问:
Dev-C++ - [Build Error] [main.o] Error 2816
I started a new project and I am trying to compile using defaults on Microsoft Windows 10. I need to compile for Windows 98 for a specific project. The compiler shows the following error message [Build Error] [main.o] Error 2816.

This is the contents of main.cpp:

```<code>#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    system("PAUSE");
    return EXIT_SUCCESS;
}
</code>```

I have no idea what this error means, and I did not find anything using Google. Any ideas?

Edit - Compile log

```<code>Compiler: Default compiler
Building Makefile: "C:\Projects\prog\Makefile.win"
Executing  make...
make.exe -f "C:\Projects\prog\Makefile.win" all
gcc.exe -c main.c -o main.o -I"C:/Dev-Cpp/include"

gcc.exe main.o  -o "prog.exe" -L"C:/Dev-Cpp/lib"

gcc.exe: Internal error: Aborted (program collect2)
Please submit a full bug report.
See <URL:http://www.mingw.org/bugs.shtml> for instructions.

make.exe: *** [prog.exe] Error 1

Execution terminated
</code>```

答:
Maybe this answer is too late but it would be helpful for the others.

The file "make.exe" is not working well with the Dev C++.
Try to download an old version of Dev C++ with the old set of files for the compiling softwares of MinGW.

Body:
I started a new project and I am trying to compile using defaults on Microsoft Windows 10. I need to compile for Windows 98 for a specific project. The compiler shows the following error message [Build Error] [main.o] Error 2816.

This is the contents of main.cpp:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    system("PAUSE");
    return EXIT_SUCCESS;
}

I have no idea what this error means, and I did not find anything using Google. Any ideas?

Edit - Compile log

Compiler: Default compiler
Building Makefile: "C:\Projects\prog\Makefile.win"
Executing  make...
make.exe -f "C:\Projects\prog\Makefile.win" all
gcc.exe -c main.c -o main.o -I"C:/Dev-Cpp/include"

gcc.exe main.o  -o "prog.exe" -L"C:/Dev-Cpp/lib"

gcc.exe: Internal error: Aborted (program collect2)
Please submit a full bug report.
See <URL:http://www.mingw.org/bugs.shtml> for instructions.

make.exe: *** [prog.exe] Error 1

Execution terminated


问:
Why is my RxJS countdown clock not displaying?
I am working on an Angular 9 quiz app and I'm using RxJS for the countdown timer (in containers\scoreboard\time\time.component.ts) and the timer doesn't seem to be displaying. The stopTimer() function should stop the timer on the number of seconds on which it is stopped. The timer should stop after the correct answer(s) are selected and the timer should reset in between questions. The time elapsed per question should be saved into the elapsedTimes array. Please see my code for the timer in the TimeComponent on Stackblitz: https://stackblitz.com/edit/angular-9-quiz-app. Thank you.

The code below is my first start with building a countdown clock with RxJS. My most recent code is on Stackblitz.

```<code>  countdownClock() {
    this.timer = interval(1000)
      .pipe(
        takeUntil(this.isPause),
        takeUntil(this.isStop)
      );
    this.timerObserver = {
      next: (_: number) => {
        this.timePerQuestion -= 1;
          ...
        }
    };

    this.timer.subscribe(this.timerObserver);
  }

  goOn() {
    this.timer.subscribe(this.timerObserver);
  }

  pauseTimer() {
    this.isPause.next();
    // setTimeout(() => this.goOn(), 1000)
  }

  stopTimer() {
    this.timePerQuestion = 0;
    this.isStop.next();
  }
</code>```

I use stopTimer() and pauseTimer() in my TimerService so I can call them from a different component.

答:
i have fixed your stackblitz. Based on your call of timerservice methods, your timer will behave

And no need to set elapsed time in teardown logic. it will automatically push whenver timer will stop.

Stackblitz Url :- https://stackblitz.com/edit/angular-9-quiz-app-er3pjn

Time countdown method :-

```<code>  countdownClock() {
    const $ = document.querySelector.bind(document);
    const start$ = this.timerService.isStart.asObservable().pipe(shareReplay(1));
    const reset$ = this.timerService.isReset.asObservable();
    const stop$ = this.timerService.isStop.asObservable();
    const markTimestamp$ = fromEvent($("#mark"), "click");
    const continueFromLastTimestamp$ = fromEvent($("#continue"), "click");
    start$.subscribe((data) => console.log(data));
    this.timeLeft$ = concat(start$.pipe(first()), reset$).pipe(
      switchMapTo(
        timer(0, 1000).pipe(
          scan((acc, crt) => acc > 0? acc - 1: acc, this.timePerQuestion),
        )
      ),
      takeUntil(stop$.pipe(skip(1))),
      repeatWhen(completeSbj =>
        completeSbj.pipe(
          switchMapTo(
            start$.pipe(
              skip(1),
              first()
            )
          )
        )
      )
    ).pipe(tap((value)=>this.timerService.setElapsed(this.timePerQuestion-value)));
</code>```

In scoreboard component params subscribe i have reset the timer, so it will reset whenever question will change.

Body:
I am working on an Angular 9 quiz app and I'm using RxJS for the countdown timer (in containers\scoreboard\time\time.component.ts) and the timer doesn't seem to be displaying. The stopTimer() function should stop the timer on the number of seconds on which it is stopped. The timer should stop after the correct answer(s) are selected and the timer should reset in between questions. The time elapsed per question should be saved into the elapsedTimes array. Please see my code for the timer in the TimeComponent on Stackblitz: https://stackblitz.com/edit/angular-9-quiz-app. Thank you.

The code below is my first start with building a countdown clock with RxJS. My most recent code is on Stackblitz.

  countdownClock() {
    this.timer = interval(1000)
      .pipe(
        takeUntil(this.isPause),
        takeUntil(this.isStop)
      );
    this.timerObserver = {
      next: (_: number) => {
        this.timePerQuestion -= 1;
          ...
        }
    };

    this.timer.subscribe(this.timerObserver);
  }

  goOn() {
    this.timer.subscribe(this.timerObserver);
  }

  pauseTimer() {
    this.isPause.next();
    // setTimeout(() => this.goOn(), 1000)
  }

  stopTimer() {
    this.timePerQuestion = 0;
    this.isStop.next();
  }

I use stopTimer() and pauseTimer() in my TimerService so I can call them from a different component.

Body:
i have fixed your stackblitz. Based on your call of timerservice methods, your timer will behave

And no need to set elapsed time in teardown logic. it will automatically push whenver timer will stop.

Stackblitz Url :- https://stackblitz.com/edit/angular-9-quiz-app-er3pjn

Time countdown method :-

  countdownClock() {
    const $ = document.querySelector.bind(document);
    const start$ = this.timerService.isStart.asObservable().pipe(shareReplay(1));
    const reset$ = this.timerService.isReset.asObservable();
    const stop$ = this.timerService.isStop.asObservable();
    const markTimestamp$ = fromEvent($("#mark"), "click");
    const continueFromLastTimestamp$ = fromEvent($("#continue"), "click");
    start$.subscribe((data) => console.log(data));
    this.timeLeft$ = concat(start$.pipe(first()), reset$).pipe(
      switchMapTo(
        timer(0, 1000).pipe(
          scan((acc, crt) => acc > 0? acc - 1: acc, this.timePerQuestion),
        )
      ),
      takeUntil(stop$.pipe(skip(1))),
      repeatWhen(completeSbj =>
        completeSbj.pipe(
          switchMapTo(
            start$.pipe(
              skip(1),
              first()
            )
          )
        )
      )
    ).pipe(tap((value)=>this.timerService.setElapsed(this.timePerQuestion-value)));

In scoreboard component params subscribe i have reset the timer, so it will reset whenever question will change.


问:
Can not retrieve a jpg image using php
I am retrieving a jpg file from an oracle db, and trying to output it with the echo command.  The jpg file is stored as a blob inside the database, and displays properly when I access it from the database.  Here is the relevant code:

```<code>$query = 'select * from answer where answer_id = :answer_id';

$stmt = oci_parse($conn, $query);

oci_bind_by_name($stmt, ':answer_id', $answer_id);

oci_execute($stmt);

if ($row = oci_fetch_array($stmt, OCI_BOTH)){

    header('Content-type: image/jpeg');

    $mylob =  $row['ANS_PICTURE']->load();
    echo $mylob;

}
</code>```

This sends out an amount of data that is consistent with the size of the file, but the browser is completely unable to interpret it as an image.

Strangely, when I use

```<code>$fp = fopen('test.jpg', 'w');
fwrite($fp, $mylob);
</code>```

I can save the file and it has no trouble displaying the image, even using the browser to open the image through the server.

If I add a file-disposition header and prompt the user to save the image, it still does not display the image when I open it.

So it seems like there is a problem between printing the data and the browser receiving the data, though I have no idea what the problem could be.

Anyone have an idea?

答:
Check for any extra output that might have snuck in before or after your image data.

In particular, check for

A Byte Order Mark before your opening <?php tag

Trailing whitespace on your script and any other included scripts. The easiest way to defeat this is to omit the closing ?> tag or even better, execute exit; after echoing your image data.

Lastly, this probably has no effect at all but I believe the correct header name is Content-Type (capital "C", capital "T").

Title: Can not retrieve a jpg image using php

Body:
I am retrieving a jpg file from an oracle db, and trying to output it with the echo command.  The jpg file is stored as a blob inside the database, and displays properly when I access it from the database.  Here is the relevant code:

$query = 'select * from answer where answer_id = :answer_id';

$stmt = oci_parse($conn, $query);

oci_bind_by_name($stmt, ':answer_id', $answer_id);

oci_execute($stmt);

if ($row = oci_fetch_array($stmt, OCI_BOTH)){

    header('Content-type: image/jpeg');

    $mylob =  $row['ANS_PICTURE']->load();
    echo $mylob;

}

This sends out an amount of data that is consistent with the size of the file, but the browser is completely unable to interpret it as an image.

Strangely, when I use

$fp = fopen('test.jpg', 'w');
fwrite($fp, $mylob);

I can save the file and it has no trouble displaying the image, even using the browser to open the image through the server.

If I add a file-disposition header and prompt the user to save the image, it still does not display the image when I open it.

So it seems like there is a problem between printing the data and the browser receiving the data, though I have no idea what the problem could be.

Anyone have an idea?


问:
If Statement Returning True All The Time
I am trying to check if the input is true, and continue to next word if false.

```<code>        "Apples",
        "Bananas",
        "Pears",
        "Door",
        "Towel",
        "Computer",
    ];

    var x = myArray[Math.floor(Math.random()*myArray.length)];

function clearbox(){
    if (x = myInput.value){
        var x = myArray[Math.floor(Math.random();*myArray.length)]);
        document.getElementById('myInput').value = ''
        document.getElementById("word").innerHTML = x
    } else {
        document.getElementById('myInput').value = ''   ;
    }
    };
</code>```

For some reason the if statment is not working, can someone help please?

答:
You should be using == instead of = which results in true always (you can also use === for type checking as well):

```<code>if (x == myInput.value)
</code>```

You have a syntax error here (remove the ;):

```<code>var x = myArray[Math.floor(Math.random()*myArray.length)]);
</code>```

Body:
I am trying to check if the input is true, and continue to next word if false.

        "Apples",
        "Bananas",
        "Pears",
        "Door",
        "Towel",
        "Computer",
    ];

    var x = myArray[Math.floor(Math.random()*myArray.length)];

function clearbox(){
    if (x = myInput.value){
        var x = myArray[Math.floor(Math.random();*myArray.length)]);
        document.getElementById('myInput').value = ''
        document.getElementById("word").innerHTML = x
    } else {
        document.getElementById('myInput').value = ''   ;
    }
    };

For some reason the if statment is not working, can someone help please?

Body:
You should be using == instead of = which results in true always (you can also use === for type checking as well):

if (x == myInput.value)

You have a syntax error here (remove the ;):

var x = myArray[Math.floor(Math.random()*myArray.length)]);


问:
the getter 'text' was called on null flutter
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}
</code>```

答:
You had a couple of errors in there, so i ll just post the whole, working code. You were missing a MaterialApp and Scaffold Widget. These are required for your App to run (Scaffold is required on every screen).

As for your TextController, you have to check if the controller exists, and if the controller.text has a value, otherwise you try to assign null when your widget is expecting a String. I solved that with a ternery expression here.

condition ? if yes block : if no block

Full Code:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(NewApp());
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
            child: Column(
          children: <Widget>[
            TextField(
              controller: textController,
            ),
            Text(textController != null && textController.text != null
                ? textController.text
                : "")
          ],
        )),
      ),
    );
  }
}
</code>```

Body:
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}

Body:
You had a couple of errors in there, so i ll just post the whole, working code. You were missing a MaterialApp and Scaffold Widget. These are required for your App to run (Scaffold is required on every screen).

As for your TextController, you have to check if the controller exists, and if the controller.text has a value, otherwise you try to assign null when your widget is expecting a String. I solved that with a ternery expression here.

condition ? if yes block : if no block

Full Code:

import 'package:flutter/material.dart';

void main() {
  runApp(NewApp());
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
            child: Column(
          children: <Widget>[
            TextField(
              controller: textController,
            ),
            Text(textController != null && textController.text != null
                ? textController.text
                : "")
          ],
        )),
      ),
    );
  }
}


问:
Create strongly typed array of arrays in TypeScript
In a language like C# I can declare a list of lists like:

```<code>List<List<int>> list_of_lists;
</code>```

Is there a similar way to declare a strongly typed array of arrays in TypeScript?  I tried the following approaches but neither compiles.

```<code>var list_of_lists:int[][];
var list_of_lists:Array<int[]>;
</code>```

答:
The simplest is:

```<code>x: Array<Array<Any>>
</code>```

And, if you need something more complex, you can do something like this:

```<code>y: Array<Array<{z:int, w:string, r:Time}>>
</code>```

Body:
In a language like C# I can declare a list of lists like:

List<List<int>> list_of_lists;

Is there a similar way to declare a strongly typed array of arrays in TypeScript?  I tried the following approaches but neither compiles.

var list_of_lists:int[][];
var list_of_lists:Array<int[]>;

Body:
The simplest is:

x: Array<Array<Any>>

And, if you need something more complex, you can do something like this:

y: Array<Array<{z:int, w:string, r:Time}>>


问:
Can't change endTime in CountDownTimer
I want to create a countdown timer in my flutter app and I used flutter_countdown_timer to make it. In my app I used the below code;

```<code>CountdownTimer(
                  endTime: 1594829147719,
                  textStyle: TextStyle(
                      fontFamily: 'Montserrat',
                      fontSize: 12,
                      color: Colors.white),
                  defaultDays: "==",
                  defaultHours: "--",
                  defaultMin: "**",
                  defaultSec: "++",
                  daysSymbol: "Days ",
                  hoursSymbol: "Hrs ",
                  minSymbol: "Mins ",
                  secSymbol: "Secs",
                ),
</code>```

In the above if I change the endTime from 1594829147719 to some other value this timer stops working and doesn't give any output.

What can be the possible cause for this and how can I fix this ?

答:
You can create a timer from scratch.

```<code>int timerSeconds;
DateTime startedAt;

StartTimer(){

_timer= new Timer.periodic(oneSec, (Timer t) => {

      setState(() {
        startedAt=DateTime.now();
        seconds--;
      })
    });
}
//to format the timer text
 String _printDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

String getTimerText(){
   int timePassed= DateTime.now().difference(startedAt).inSeconds;
   timerTextString=_printDuration(Duration(seconds: timerText-timePassed));
}
</code>```

Then stop the timer when disposing of.

```<code>@override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }
</code>```

Then call the text string in Text widget like this

```<code>Text(getTimerText());
</code>```

Title: Can't change endTime in CountDownTimer

Body:
I want to create a countdown timer in my flutter app and I used flutter_countdown_timer to make it. In my app I used the below code;

CountdownTimer(
                  endTime: 1594829147719,
                  textStyle: TextStyle(
                      fontFamily: 'Montserrat',
                      fontSize: 12,
                      color: Colors.white),
                  defaultDays: "==",
                  defaultHours: "--",
                  defaultMin: "**",
                  defaultSec: "++",
                  daysSymbol: "Days ",
                  hoursSymbol: "Hrs ",
                  minSymbol: "Mins ",
                  secSymbol: "Secs",
                ),

In the above if I change the endTime from 1594829147719 to some other value this timer stops working and doesn't give any output.

What can be the possible cause for this and how can I fix this ?

Body:
You can create a timer from scratch.

int timerSeconds;
DateTime startedAt;

StartTimer(){

_timer= new Timer.periodic(oneSec, (Timer t) => {

      setState(() {
        startedAt=DateTime.now();
        seconds--;
      })
    });
}
//to format the timer text
 String _printDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

String getTimerText(){
   int timePassed= DateTime.now().difference(startedAt).inSeconds;
   timerTextString=_printDuration(Duration(seconds: timerText-timePassed));
}

Then stop the timer when disposing of.

@override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

Then call the text string in Text widget like this

Text(getTimerText());


答:
Your if statement if (x = myInput.value) should be using a boolean comparison operator (==), but you used an assignment operator (=) instead. As a result, the variable x is being set to the value myInput.value which will always return true, as values > 0 are interpreted to be true <s>by the compiler</s>. Instead, your function should read:

```<code>function clearbox(){
    if (x == myInput.value){
        var x = myArray[Math.floor(Math.random()*myArray.length)]);
        document.getElementById('myInput').value = ''
        document.getElementById("word").innerHTML = x
    } else {
        document.getElementById('myInput').value = ''   ;
    }
</code>```

Title: If Statement Returning True All The Time

Body:
Your if statement if (x = myInput.value) should be using a boolean comparison operator (==), but you used an assignment operator (=) instead. As a result, the variable x is being set to the value myInput.value which will always return true, as values > 0 are interpreted to be true <s>by the compiler</s>. Instead, your function should read:

function clearbox(){
    if (x == myInput.value){
        var x = myArray[Math.floor(Math.random()*myArray.length)]);
        document.getElementById('myInput').value = ''
        document.getElementById("word").innerHTML = x
    } else {
        document.getElementById('myInput').value = ''   ;
    }


问:
How to pass arguments to kapt compiler dynamicly inside my gradle plugin?
I'm currently writing a Gradle plugin to inject some arguments to an annotation processor. It works fine when using annotationProcessor in a Java based Android project. When I tried kapt in a Kotlin based project, it didn't work since kapt collected args from its own configurations.

What I did so far:

```<code>val args = variant.javaCompileOptions.annotationProcessorOptions.arguments
args["key"] = "value"
</code>```

What I knew for kapt args passing is that you can set them via its extensions in the build.gradle, link:

```<code>kapt {
    arguments {
        arg("key", "value")
    }
}
</code>```

So how to pass arguments to kapt compiler dynamicly inside my gradle plugin? Thanks.

答:
Unfortunately it's not well documented and I have run into this particular issue before. Here is what I did

in your plugin apply function do this (target is the gradle project that the plugin is being applied to). If you  are applying the plugin into your root project then simply put the same code into target.subProjects{...}

```<code>target.afterEvaluate{
    target.plugins.all {
        when (it) {
            is AppPlugin -> {
                extensions[AppExtension::class].run {
                    configureJavaCompilerArguments("option1", "option2")
                }
            }
            //if your project has a library that requires/use kapt also do this
            is LibraryPlugin -> {
                extensions[LibraryExtension::class].run {
                    configureJavaCompilerArguments("option1", "option2")
                }
            }
         }
    }
}
</code>```

For simplicity I have declared a fancy extension function to add the arguments

```<code>fun BaseExtension.configureJavaCompilerArguments(option1:String, option2: String) {
    with(defaultConfig.javaCompileOptions.annotationProcessorOptions) {
        includeCompileClasspath = true
        arguments(mapOf(
                "some.key.in.your.ap.1" to option1,
                "some.key.in.your.ap.2" to option2
        ))
    }
}
</code>```

and also this fancy function that I took from Butter-knife source code

```<code>internal operator fun <T : Any> ExtensionContainer.get(type: KClass<T>): T {
    return getByType(type.java)
}
</code>```

now in your annotation processor just declare interest to these options specifying the same keys!! that is so important.

Happy coding!

Body:
I'm currently writing a Gradle plugin to inject some arguments to an annotation processor. It works fine when using annotationProcessor in a Java based Android project. When I tried kapt in a Kotlin based project, it didn't work since kapt collected args from its own configurations.

What I did so far:

val args = variant.javaCompileOptions.annotationProcessorOptions.arguments
args["key"] = "value"

What I knew for kapt args passing is that you can set them via its extensions in the build.gradle, link:

kapt {
    arguments {
        arg("key", "value")
    }
}

So how to pass arguments to kapt compiler dynamicly inside my gradle plugin? Thanks.

Body:
Unfortunately it's not well documented and I have run into this particular issue before. Here is what I did

in your plugin apply function do this (target is the gradle project that the plugin is being applied to). If you  are applying the plugin into your root project then simply put the same code into target.subProjects{...}

target.afterEvaluate{
    target.plugins.all {
        when (it) {
            is AppPlugin -> {
                extensions[AppExtension::class].run {
                    configureJavaCompilerArguments("option1", "option2")
                }
            }
            //if your project has a library that requires/use kapt also do this
            is LibraryPlugin -> {
                extensions[LibraryExtension::class].run {
                    configureJavaCompilerArguments("option1", "option2")
                }
            }
         }
    }
}

For simplicity I have declared a fancy extension function to add the arguments

fun BaseExtension.configureJavaCompilerArguments(option1:String, option2: String) {
    with(defaultConfig.javaCompileOptions.annotationProcessorOptions) {
        includeCompileClasspath = true
        arguments(mapOf(
                "some.key.in.your.ap.1" to option1,
                "some.key.in.your.ap.2" to option2
        ))
    }
}

and also this fancy function that I took from Butter-knife source code

internal operator fun <T : Any> ExtensionContainer.get(type: KClass<T>): T {
    return getByType(type.java)
}

now in your annotation processor just declare interest to these options specifying the same keys!! that is so important.

Happy coding!


问:
Python pypi proxy-checker output?
So I installed this python tool: https://pypi.org/project/proxy-checker/
And I also installed PycURL

And my code is

```<code>checker = ProxyChecker()
checker.check_proxy('202.138.248.72:43037')
</code>```

And its says that all is working, but where can I see the results like at the link?
Do I have to link anything?

答:
.check_proxy() returns the result. You need to catch that and use in whatever way you want:

```<code>result = checker.check_proxy('202.138.248.72:43037')
</code>```

For example, you can print the results:

```<code>print(results)
</code>```

If you want just print and nothing else you can print directly:

```<code>print(checker.check_proxy('202.138.248.72:43037'))
</code>```

Title: Python pypi proxy-checker output?

Body:
So I installed this python tool: https://pypi.org/project/proxy-checker/
And I also installed PycURL

And my code is

checker = ProxyChecker()
checker.check_proxy('202.138.248.72:43037')

And its says that all is working, but where can I see the results like at the link?
Do I have to link anything?

Body:
.check_proxy() returns the result. You need to catch that and use in whatever way you want:

result = checker.check_proxy('202.138.248.72:43037')

For example, you can print the results:

print(results)

If you want just print and nothing else you can print directly:

print(checker.check_proxy('202.138.248.72:43037'))


问:
Avoiding collision between particles and collider in Unity
I have an arbitrarily large number of things shooting particle systems at each other. I want the particles to hit the targets but not the origin objects. Is it possible to either:

Use IgnoreCollision between a ParticleSystem and a Collider

Define new collision layers at runtime

Or is there some sneaky way of solving this I haven't considered?

答:
If you want to set the collides with value of the Collision module at runtime you need to define a Layermask and use the following code:

```<code>var particleCollision = yourParticleSystemComponent.collision;
particleCollision.collidesWith = layermask;
</code>```

I believe that you can't use IgnoreCollision between a ParticleSystem and a Collider.

Body:
If you want to set the collides with value of the Collision module at runtime you need to define a Layermask and use the following code:

var particleCollision = yourParticleSystemComponent.collision;
particleCollision.collidesWith = layermask;

I believe that you can't use IgnoreCollision between a ParticleSystem and a Collider.


问:
issue currency maj in opencart Version 3.0.2.0
I have a issue with currency in opencart 3.0.2.0.

When a change currency from euro to usd for example from header. catalog product currency note updated anymore.

you can check this here : prodaou.com

答:
I see. you are using Journal 3 template. And your issue can be seen only on the home page with Latest module. It is Journsl 3 chase issue, which was fixed on 3.0.2 version (Currency Cache fix) https://docs.journal-theme.com/changelog.

Update your Journal 3 theme. Don't forget to backup first.


问:
Right to Left text writing support in windows phone 7?
I m building an application for Arabic and in this i want that i should write text from right to left in textbox but i can see only the option to align the text to left or right.

How can i get this feature?

答: Languages that support right-to-left are only introduced in the Mango update. You can't do it before then.</p>


答:
You need to print the result:

from pprint import pprint
from proxy_checker import ProxyChecker

checker = ProxyChecker()
pprint(checker.check_proxy('202.138.248.72:43037'))
```

```{'anonymity': 'Elite',
 'country': 'Indonesia',
 'country_code': 'ID',
 'protocols': ['socks4'],
 'timeout': 797}
```

Title: Python pypi proxy-checker output?

Body:
You need to print the result:

from pprint import pprint
from proxy_checker import ProxyChecker

checker = ProxyChecker()
pprint(checker.check_proxy('202.138.248.72:43037'))

{'anonymity': 'Elite',
 'country': 'Indonesia',
 'country_code': 'ID',
 'protocols': ['socks4'],
 'timeout': 797}


问:
How can I display the file name of the image I am loading in a new div?
I have a file input that I'm using to display image thumbnails. When you click on a thumbnail, the image appears in a separate div. That part is working fine, but I would also like the name of the file to be displayed under the larger image. I used this great guide for displaying multiple image thumbnails. I have two event listeners, one for load and one for click. I tried to add document.getElementById('right').innertext=this.title; in the click event, but it just doesn't seem to do anything.

Below is my complete code:

        <input id="files" type="file" onchange="previewFiles()" multiple />

 ```

答:
You mean this?

it is innerText with a capital T and you want it in the p tag?

function previewFiles() {

  var preview = document.querySelector('#preview');
  var files = this.files;

  function readAndPreview(file) {

    var reader = new FileReader();

    reader.addEventListener("load", function() {
      var image = new Image();
      image.height = 50;
      image.title = file.name;
      image.id = Math.floor(Math.random() * 100);
      image.src = this.result;
      image.addEventListener("click", function() {
        document.getElementById('img2').src = this.src;
        document.querySelector('#right p').innerText = this.title;
      })

      preview.appendChild(image);
    }, false);

    reader.readAsDataURL(file);

  }

  if (files) {
    [].forEach.call(files, readAndPreview);
  }

}

document.querySelector('input[type=file]').addEventListener("change",previewFiles)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="left">
  <input id="files" type="file" multiple />
  <hr>
  <div id="preview"></div>
</div>

<div id="right">
  <img src="" id="img2" style="max-width: 500px;">
  <p></p>
</div>

</script></code>```

Body:
You mean this?

it is innerText with a capital T and you want it in the p tag?

function previewFiles() {

  var preview = document.querySelector('#preview');
  var files = this.files;

  function readAndPreview(file) {

    var reader = new FileReader();

    reader.addEventListener("load", function() {
      var image = new Image();
      image.height = 50;
      image.title = file.name;
      image.id = Math.floor(Math.random() * 100);
      image.src = this.result;
      image.addEventListener("click", function() {
        document.getElementById('img2').src = this.src;
        document.querySelector('#right p').innerText = this.title;
      })

      preview.appendChild(image);
    }, false);

    reader.readAsDataURL(file);

  }

  if (files) {
    [].forEach.call(files, readAndPreview);
  }

}

document.querySelector('input[type=file]').addEventListener("change",previewFiles)

<div id="left">
  <input id="files" type="file" multiple />
  <hr>
  <div id="preview"></div>
</div>

<div id="right">
  <img src="" id="img2" style="max-width: 500px;">
  <p></p>
</div>

</script>


问:
Why doesn't my C program wait to scan input?
I am new to C. I allocated memory with this statement:

```<code>patientptr = (char*) calloc (118, sizeof (char));
</code>```

then I assign data using this (this is a part of the function):

```<code>char name[51];
int age;
char agestr[3];
char infectiondate [11];
char address[51];
char *patientptr;

printf("\nEnter the patient name (50 characters at maximum): ");
scanf ("%50s", name);
*patientptr = name;

printf("Enter the patient age: ");
scanf ("%d", &age);
sprintf (agestr, "%2d", age);
*(patientptr + 51) = agestr;

printf("Enter the patient date of infection (in form of dd/mm/year): ");
*(patientptr + 54) = scanf ("%10d", infectiondate);

printf("Enter the patient address (50 characters at maximum): ");
*(patientptr + 65) = scanf ("%50s", address);

*(ptrsptr+patientsnum-1) = patientptr;

printf ("\nPatient added.\n");
</code>```

Everything goes fine except that after the "enter the patient address: " line, it prints the "patient added" line directly without waiting to scan the address. the output is like this:

```<code>Enter the patient name (50 characters at maximum): ahmed
Enter the patient age: 20
Enter the patient date of infection (in form of dd/mm/year): 10/10/2020
Enter the patient address (50 characters at maximum):
Patient added.
</code>```

is the wrong with my allocated memory?

答:
You may well have used calloc to allocate some memory but examine this snippet:

```<code>char *patientptr;

printf("\nEnter the patient name (50 characters at maximum): ");
scanf ("%50s", name);
*patientptr = name;
</code>```

That first line shadows whatever patientptr was with an uninitialised pointer, hence the final line is undefined behaviour (patientptr now points to some arbitrary address). All bets are off at this point, anything is possible.

Fix that and try again.

In addition, it looks like you believe that:

```<code>*(patientptr + 51) = agestr;
</code>```

is a way to copy a C string from one place to another. In actual fact, this will attempt to place the agestr pointer value into the single character at the memory location &(patientptr[51]), and possibly should have warned you about this.

You need to look into strcpy for this, something along the lines of:

```<code>strcpy(patientptr + 51, agestr);
</code>```

But, if you're looking to do user input, it's often a good idea to work around the limits of scanf. It does, after all, stand for "scan formatted" and there's very little that's less formatted than user input.

I have a favourite function I use for this, which is shown below, along with the modifications to your own code to use it (using both that function and with quite a bit of other validation specific to your case):

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

// Bullet-proof line input function.

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

// Ensure a character array is non-empty and all digits.

int checkDigits(char *arr, size_t sz) {
    if (sz == 0) {
        return 0;
    }
    while (sz-- > 0) {
        if (! isdigit(*arr++)) {
            return 0;
        }
    }
    return 1;
}

// Get customer data line, return NULL if okay, error if not.
// Output record must be long enough for format string below
// and a one-character end-string marker.

static char *getPatientData(char *patientData) {
    // Keep this format string in sync with field sizes below.

    static char *fmtString = "%-50.50s" "%3d" "%-10.10s" "%-50.50s";
    char name[51];
    char ageStr[4];
    char infectionDate[11];
    char address[51];

    if (getLine("Patient name: ", name, sizeof(name)) != OK) {
        return "Error getting name.";
    }

    if (getLine("Patient age: ", ageStr, sizeof(ageStr)) != OK) {
        return "Error getting age.";
    }
    if (! checkDigits(ageStr, strlen(ageStr))) {
        return "Error, age contains non-digit data.";
    }
    int age = atoi(ageStr);
    // Further age sanity checking, if desired. Example: ensure <= 150.

    if (getLine("Infection date (dd/mm/yyyy): ", infectionDate, sizeof(infectionDate)) != OK) {
        return "Error getting infection date.";
    }
    if (
        strlen(infectionDate) != 10
        || infectionDate[2] != '/'
        || infectionDate[5] != '/'
        || ! checkDigits(infectionDate, 2)
        || ! checkDigits(infectionDate + 3, 2)
        || ! checkDigits(infectionDate + 6, 4)
    ) {
        return "Error, incorrect format.";
    }
    // Further checking if desired. Example: valid year/month/day combo.

    if (getLine("Patient address: ", address, sizeof(address)) != OK) {
        return "Error getting address.";
    }

    sprintf(patientData, fmtString, name, age, infectionDate, address);
    return NULL;
}

int main(void) {
    char *patientPtr = malloc (50 + 3 + 10 + 50 + 1);
    char *result = getPatientData(patientPtr);
    if (result != NULL) {
        printf("*** %s\n", result);
        return 1;
    }
    printf("Got '%s'\n", patientPtr);
    return 0;
}
</code>```

A sample run follows:

```<code>Patient name: Pax Diablo
Patient age: 55
Infection date (dd/mm/yyyy): 25/05/2020
Patient address: No fixed abode
Got 'Pax Diablo                                         5525/05/2020No fixed abode                                    '
</code>```

Body:
I am new to C. I allocated memory with this statement:

patientptr = (char*) calloc (118, sizeof (char));

then I assign data using this (this is a part of the function):

char name[51];
int age;
char agestr[3];
char infectiondate [11];
char address[51];
char *patientptr;

printf("\nEnter the patient name (50 characters at maximum): ");
scanf ("%50s", name);
*patientptr = name;

printf("Enter the patient age: ");
scanf ("%d", &age);
sprintf (agestr, "%2d", age);
*(patientptr + 51) = agestr;

printf("Enter the patient date of infection (in form of dd/mm/year): ");
*(patientptr + 54) = scanf ("%10d", infectiondate);

printf("Enter the patient address (50 characters at maximum): ");
*(patientptr + 65) = scanf ("%50s", address);

*(ptrsptr+patientsnum-1) = patientptr;

printf ("\nPatient added.\n");

Everything goes fine except that after the "enter the patient address: " line, it prints the "patient added" line directly without waiting to scan the address. the output is like this:

Enter the patient name (50 characters at maximum): ahmed
Enter the patient age: 20
Enter the patient date of infection (in form of dd/mm/year): 10/10/2020
Enter the patient address (50 characters at maximum):
Patient added.

is the wrong with my allocated memory?

Body:
You may well have used calloc to allocate some memory but examine this snippet:

char *patientptr;

printf("\nEnter the patient name (50 characters at maximum): ");
scanf ("%50s", name);
*patientptr = name;

That first line shadows whatever patientptr was with an uninitialised pointer, hence the final line is undefined behaviour (patientptr now points to some arbitrary address). All bets are off at this point, anything is possible.

Fix that and try again.

In addition, it looks like you believe that:

*(patientptr + 51) = agestr;

is a way to copy a C string from one place to another. In actual fact, this will attempt to place the agestr pointer value into the single character at the memory location &(patientptr[51]), and possibly should have warned you about this.

You need to look into strcpy for this, something along the lines of:

strcpy(patientptr + 51, agestr);

But, if you're looking to do user input, it's often a good idea to work around the limits of scanf. It does, after all, stand for "scan formatted" and there's very little that's less formatted than user input.

I have a favourite function I use for this, which is shown below, along with the modifications to your own code to use it (using both that function and with quite a bit of other validation specific to your case):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

// Bullet-proof line input function.

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

// Ensure a character array is non-empty and all digits.

int checkDigits(char *arr, size_t sz) {
    if (sz == 0) {
        return 0;
    }
    while (sz-- > 0) {
        if (! isdigit(*arr++)) {
            return 0;
        }
    }
    return 1;
}

// Get customer data line, return NULL if okay, error if not.
// Output record must be long enough for format string below
// and a one-character end-string marker.

static char *getPatientData(char *patientData) {
    // Keep this format string in sync with field sizes below.

    static char *fmtString = "%-50.50s" "%3d" "%-10.10s" "%-50.50s";
    char name[51];
    char ageStr[4];
    char infectionDate[11];
    char address[51];

    if (getLine("Patient name: ", name, sizeof(name)) != OK) {
        return "Error getting name.";
    }

    if (getLine("Patient age: ", ageStr, sizeof(ageStr)) != OK) {
        return "Error getting age.";
    }
    if (! checkDigits(ageStr, strlen(ageStr))) {
        return "Error, age contains non-digit data.";
    }
    int age = atoi(ageStr);
    // Further age sanity checking, if desired. Example: ensure <= 150.

    if (getLine("Infection date (dd/mm/yyyy): ", infectionDate, sizeof(infectionDate)) != OK) {
        return "Error getting infection date.";
    }
    if (
        strlen(infectionDate) != 10
        || infectionDate[2] != '/'
        || infectionDate[5] != '/'
        || ! checkDigits(infectionDate, 2)
        || ! checkDigits(infectionDate + 3, 2)
        || ! checkDigits(infectionDate + 6, 4)
    ) {
        return "Error, incorrect format.";
    }
    // Further checking if desired. Example: valid year/month/day combo.

    if (getLine("Patient address: ", address, sizeof(address)) != OK) {
        return "Error getting address.";
    }

    sprintf(patientData, fmtString, name, age, infectionDate, address);
    return NULL;
}

int main(void) {
    char *patientPtr = malloc (50 + 3 + 10 + 50 + 1);
    char *result = getPatientData(patientPtr);
    if (result != NULL) {
        printf("*** %s\n", result);
        return 1;
    }
    printf("Got '%s'\n", patientPtr);
    return 0;
}

A sample run follows:

Patient name: Pax Diablo
Patient age: 55
Infection date (dd/mm/yyyy): 25/05/2020
Patient address: No fixed abode
Got 'Pax Diablo                                         5525/05/2020No fixed abode                                    '