问:
How can I balance "Pythonic" and "convenient" in this case?
I have an "interface" that will be implemented by client code:

```<code>class Runner:
    def run(self):
        pass
</code>```

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

```<code>def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())
</code>```

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

答:
```<code>class Node(object):
  def __new__(cls, contents):
    return contents if isinstance(contents, cls) else object.__new__(cls)
  def __init__(self, contents):
    # construct from string...

class Manager(object):
  def do_something(self, runner, *args):
    do_something_else(Node(runner(*args)))
</code>```

Now it doesn't matter if the runner returns a Node or a string.

Body:
I have an "interface" that will be implemented by client code:

class Runner:
    def run(self):
        pass

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

Body:
class Node(object):
  def __new__(cls, contents):
    return contents if isinstance(contents, cls) else object.__new__(cls)
  def __init__(self, contents):
    # construct from string...

class Manager(object):
  def do_something(self, runner, *args):
    do_something_else(Node(runner(*args)))

Now it doesn't matter if the runner returns a Node or a string.


来源: stackexchange

问:
XSLT count element value and create new element with the value
I have the following source XML:

```<code><ITEMS>
   <ITEM>
      <CODE>34155</CODE>
      <VARIANTS>
         <NAME>A</NAME>
         <STOCK>12</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>B</NAME>
         <STOCK>0</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>C</NAME>
         <STOCK>50</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>D</NAME>
         <STOCK>3</STOCK>
      </VARIANTS>
   </ITEM>
</ITEMS>
</code>```

I would like to loop trough all <VARIANTS> elements count <STOCK> child value and create new <TOTALSTOCK> value under the parent element <ITEM>.

```<code><ITEMS>
   <ITEM>
      <TOTALSTOCK>65</TOTALSTOCK>
      <CODE>34155</CODE>
      <VARIANTS>
         <NAME>A</NAME>
         <STOCK>12</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>B</NAME>
         <STOCK>0</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>C</NAME>
         <STOCK>50</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>D</NAME>
         <STOCK>3</STOCK>
      </VARIANTS>
   </ITEM>
</ITEMS>
</code>```

Is such a mathematical operation possible with XSLT?

答:
There is no need "to loop trough all <VARIANTS> elements". You can do simply:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/ITEMS">
    <xsl:copy>
        <xsl:for-each select="ITEM">
            <xsl:copy>
                <TOTALSTOCK>
                    <xsl:value-of select="sum(VARIANTS/STOCK)"/>
                </TOTALSTOCK>
                <xsl:copy-of select="*"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following source XML:

<ITEMS>
   <ITEM>
      34155
      <VARIANTS>
         <NAME>A</NAME>
         <STOCK>12</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>B</NAME>
         <STOCK>0</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>C</NAME>
         <STOCK>50</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>D</NAME>
         <STOCK>3</STOCK>
      </VARIANTS>
   </ITEM>
</ITEMS>

I would like to loop trough all <VARIANTS> elements count <STOCK> child value and create new <TOTALSTOCK> value under the parent element <ITEM>.

<ITEMS>
   <ITEM>
      <TOTALSTOCK>65</TOTALSTOCK>
      34155
      <VARIANTS>
         <NAME>A</NAME>
         <STOCK>12</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>B</NAME>
         <STOCK>0</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>C</NAME>
         <STOCK>50</STOCK>
      </VARIANTS>
      <VARIANTS>
         <NAME>D</NAME>
         <STOCK>3</STOCK>
      </VARIANTS>
   </ITEM>
</ITEMS>

Is such a mathematical operation possible with XSLT?

Body:
There is no need "to loop trough all <VARIANTS> elements". You can do simply:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/ITEMS">
    <xsl:copy>
        <xsl:for-each select="ITEM">
            <xsl:copy>
                <TOTALSTOCK>
                    <xsl:value-of select="sum(VARIANTS/STOCK)"/>
                </TOTALSTOCK>
                <xsl:copy-of select="*"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
Package __init__.py import all subfiles, but only load one from another script?
I have created a package with the following file structure:

```<code>- package
  - __init__.py
  - load.py
  - train.py
  - test.py
</code>```

My __init__.py file is simply an import of classes for these files:

```<code>from package.load import Load
from package.train import Train
from package.test import Test
</code>```

Most of the time, I want to load all three, however on occasion I only want to load one of these classes specifically. For example in an ad hoc script (outside of the package) I want to be able to call only the Load class like so:

```<code>from package import Load
</code>```

While all of the above works in this design, I have an issue where dependencies from train/test are also loaded when I import Load like the above. How can I setup the __init__.py file such that I can make the same import call without getting the dependency to load from train/test?

Additional explanation:

Why I am doing this: I have an issue where I want some people to be able to use the Load class, which only uses base python, however the Train/Test files include specialized dependencies which users of just the Load class wont want to utilize or even install.

答:
Inside a folder oranges\, this is our __init__.py file:

__all__ = []

from pathlib import Path
from importlib import import_module
from sys import modules

package = modules[__name__]
initfile = Path(__file__)
for entry in initfile.parent.iterdir():
    is_file = entry.is_file()
    is_pyfile = entry.name.endswith('.py')
    is_not_initpy = (entry != initfile)
    if is_file and is_pyfile and is_not_initpy:
        module_name = entry.name.removesuffix('.py')
        module_path = __name__ + '.' + module_name
        module = import_module(module_path)
        setattr(package, module_name, module)
        __all__.append(module_name)
```

When we do from oranges import *, the code inside oranges\__init__.py cycles through the *.py files inside oranges\ (except __init__.py), and for each .py file does the following:

imports the .py file as a module into the variable module using Python's importlib.import_module

sets the module as a variable within the __init__.py file (or, more correctly, within the oranges package) using Python's setattr

finally, appends the module to the __all__ list

Body:
I have created a package with the following file structure:

- package
  - __init__.py
  - load.py
  - train.py
  - test.py

My __init__.py file is simply an import of classes for these files:

from package.load import Load
from package.train import Train
from package.test import Test

Most of the time, I want to load all three, however on occasion I only want to load one of these classes specifically. For example in an ad hoc script (outside of the package) I want to be able to call only the Load class like so:

from package import Load

While all of the above works in this design, I have an issue where dependencies from train/test are also loaded when I import Load like the above. How can I setup the __init__.py file such that I can make the same import call without getting the dependency to load from train/test?

Additional explanation:

Why I am doing this: I have an issue where I want some people to be able to use the Load class, which only uses base python, however the Train/Test files include specialized dependencies which users of just the Load class wont want to utilize or even install.

Body:
Inside a folder oranges\, this is our __init__.py file:

__all__ = []

from pathlib import Path
from importlib import import_module
from sys import modules

package = modules[__name__]
initfile = Path(__file__)
for entry in initfile.parent.iterdir():
    is_file = entry.is_file()
    is_pyfile = entry.name.endswith('.py')
    is_not_initpy = (entry != initfile)
    if is_file and is_pyfile and is_not_initpy:
        module_name = entry.name.removesuffix('.py')
        module_path = __name__ + '.' + module_name
        module = import_module(module_path)
        setattr(package, module_name, module)
        __all__.append(module_name)

When we do from oranges import *, the code inside oranges\__init__.py cycles through the *.py files inside oranges\ (except __init__.py), and for each .py file does the following:

imports the .py file as a module into the variable module using Python's importlib.import_module

sets the module as a variable within the __init__.py file (or, more correctly, within the oranges package) using Python's setattr

finally, appends the module to the __all__ list


问:
c# async await confuses me, seems to do nothing
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

```<code>using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}
</code>```

答:
As already mentioned in the comments:

you have to use await Task.Delay(2000) to tell the compiler that you want run Task.Delay(2000) asynchronous.
If you take a closer look in the example provided by you the compiler shows a warning:

This async methods lacks 'await'operators and will run synchronously [...]

Body:
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}


问:
the search for algolia display all the data before doing the search
I installed the algolia package, I configured it, it works fine, but there is still a problem, it is that the data displays in input search before doing the search.
see the site for more information.
site: link

searche.blade.php

```<code><div class="container">
    <div id="search-box">
        <!-- SearchBox widget will appear here -->
    </div>
    <div id="hits">
        <!-- Hits widget will appear here -->
    </div>
    <div class="aa-input-container" id="aa-input-container">
        <input type="search" id="aa-search-input" class="aa-input-search" placeholder="Search for posts" name="search" autocomplete="off" />
    </div>
</div>

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.0.2/dist/instantsearch.min.css">
    <script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.0.2/dist/instantsearch.min.js"></script>

    <script type="text/template" id="hits-temp">
        @{{ __highlightResult.h1 }}
        <div class="row song">
            <a class="song-link" href="song/@{{objectID}}">@{{{_highlightResult.title.value}}}</a>
        </div>

    </script>

    <script type="text/javascript">
        $(document).ready(function () {
            const search = instantsearch({
                appId: 'H329YTS1B5',
                apiKey: '10a91d843aaeef2d91583bfead9b339f',
                indexName: 'title',
                urlSync: false
            });
            // initialize SearchBox
            search.addWidget(
                instantsearch.widgets.searchBox({
                    container: '#search-box',
                    placeholder: 'Search for posts',
                    wrapInput: false,
                    cssClasses: {
                        input: 'form-control'
                    }
                })
            );
            // initialize hits widget
            search.addWidget(
                instantsearch.widgets.hits({
                    container: '#hits',
                    templates: {
                        empty: 'No results',
                        item: $('#hits-temp').html()
                    }
                })
            );
            search.start();
        });
    </script>
</code>```

答:
When the search query is empty, the search matches all records by default.

You'll need some additional code if you want to suppress results when the search box is empty:

https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/js/#handling-empty-queries

Body:
I installed the algolia package, I configured it, it works fine, but there is still a problem, it is that the data displays in input search before doing the search.
see the site for more information.
site: link

searche.blade.php

        <input type="search" id="aa-search-input" class="aa-input-search" placeholder="Search for posts" name="search" autocomplete="off" />

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.0.2/dist/instantsearch.min.css">


问:
Javascript to open default email client doesn't work
I need to perform following tasks;

on click of link (could be link button,  or Hyperlink) the default email program at client machine should open up.

Javascript for the same has been written as below:

string adminemail= "xyz@abc.com";    //fetches admin email address; display in To Field

ScriptManager.RegisterStartupScript(this.updatePanel1, typeof (string), "defaultemail", "window.open('mailto:" + adminemail+ " ');", true);

But, using the link button is not correct option, as it triggers postback. Hence i thought of using the  tag, but i am not sure how to link that with the javascript.

How to execute the JS with the help of  tag? OR Suggest some possible solution for the same.

Please guide!

Thanks!!

答:
Why not just use mailto? For example Send email to the admin

You can also include cc,bcc,subject and body fields in the query string to customize the email. See the IANR syntax reference.

ContentLicense: CC BY-SA 3.0

Body:
Why not just use mailto? For example <a href="mailto:xyz@abc.com">Send email to the admin</a>

You can also include cc,bcc,subject and body fields in the query string to customize the email. See the IANR syntax reference.


问:
npm start (yarn start) error. cannot find @babel/register
I creact app using react. I usually use yarn start to run my app.
Error messege is "cannot find @babel/register" but there is on the package.json.

In my package.json
"@babel/register": "^7.6.2"

my index.js

```<code>require('@babel/register');
module.exports = require('./server.js');
</code>```

Error

```<code>> reactjs-simple-boilerplate@1.0.0 start
> node src/server/index.js

internal/modules/cjs/loader.js:905
  throw err;
  ^

Error: Cannot find module '@babel/register'
Require stack:
- /Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (/Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js:1:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js'
  ]
}
</code>```

npm install --save-dev @babel/register is not works for me.
After run this code, I got npm ERR! code EINTEGRITY

答:
Not sure I can help 100% with the given information, but try running the following:

```<code>rm -rf node_modules package-lock.json yarn.lock; npm i
</code>```

That will not only remove your modules, but it'll also remove eventual lock files which are used as conformity for your module versions; It could happen they mismatched versions between installations causing the above error, thus by removing and reinstalling you should solve the problem.

If that's not the case, you might have something off on your package.json, which you'd need to share in order to debug further

Body:
I creact app using react. I usually use yarn start to run my app.
Error messege is "cannot find @babel/register" but there is on the package.json.

In my package.json
"@babel/register": "^7.6.2"

my index.js

require('@babel/register');
module.exports = require('./server.js');

Error

> reactjs-simple-boilerplate@1.0.0 start
> node src/server/index.js

internal/modules/cjs/loader.js:905
  throw err;
  ^

Error: Cannot find module '@babel/register'
Require stack:
- /Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (/Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js:1:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/mk/kr/kr-application-bd786050/kr-site/src/server/index.js'
  ]
}

npm install --save-dev @babel/register is not works for me.
After run this code, I got npm ERR! code EINTEGRITY

Body:
Not sure I can help 100% with the given information, but try running the following:

rm -rf node_modules package-lock.json yarn.lock; npm i

That will not only remove your modules, but it'll also remove eventual lock files which are used as conformity for your module versions; It could happen they mismatched versions between installations causing the above error, thus by removing and reinstalling you should solve the problem.

If that's not the case, you might have something off on your package.json, which you'd need to share in order to debug further


问:
css format blank string the same as actual text
I keep running into this problem - I have html like this:

hello

there

```
<p>and this css:</p>
<pre class="lang-css prettyprint-override"><code>.line
{
  background-color:red;
  padding:10px;
}

.word
{
  display:inline-block;
  width:200px;
  height:40px;
  padding:10px;
  background-color:white;
}
</code>```

And I get this:

Why is it happening, and how do I fix it so that an empty string is formatted exactly the same as a string with values?

答:
Vertical align

You could apply vertical-align:top to .word

.line {
  background-color: red;
  padding: 10px;
}

.word {
  display: inline-block;
  width: 100px;
  height: 40px;
  padding: 10px;
  background-color: white;
  vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"> </div>
  <div class="word"></div>
</div></code>```

Empty selector

Or add a rule for empty .word divs, but this would still be malformed for divs with spaces in them. Could be helpful if you can't change the  vertical-align

.line {
  background-color: red;
  padding: 10px;
}

.word {
  display: inline-block;
  width: 100px;
  height: 40px;
  padding: 10px;
  background-color: white;
}

 .word:empty:before {
    content: "\0020";
    display: inline-block;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"> </div>
  <div class="word"></div>
</div></code>```

Why is this happening

Vertical alignment determines how 'inline' elements are positioned in relation to each other. by default it's set to baseline

Baseline will try to put 'most' of the text above the baseline and some of the dangling bits like the g p and q and y under the baseline.

That would make sense for text, the browser will attempt to do that for all text. Even text that's wrapped in divs and styled with paddings.

The entire empty div is put on the baseline.

Browser manufacturers just agreed that this is how it should be done.

If you look at it as if it where a text editor, It would make sense for small inline images, the default would be to push the entire line down based on the dimension of the image

Body:
I keep running into this problem - I have html like this:

hello

there

and this css:

.line
{
  background-color:red;
  padding:10px;
}

.word
{
  display:inline-block;
  width:200px;
  height:40px;
  padding:10px;
  background-color:white;
}

And I get this:

Why is it happening, and how do I fix it so that an empty string is formatted exactly the same as a string with values?

Body:
Vertical align

You could apply vertical-align:top to .word

.line {
  background-color: red;
  padding: 10px;
}

.word {
  display: inline-block;
  width: 100px;
  height: 40px;
  padding: 10px;
  background-color: white;
  vertical-align: top;
}

<div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"> </div>
  <div class="word"></div>
</div>

Empty selector

Or add a rule for empty .word divs, but this would still be malformed for divs with spaces in them. Could be helpful if you can't change the  vertical-align

.line {
  background-color: red;
  padding: 10px;
}

.word {
  display: inline-block;
  width: 100px;
  height: 40px;
  padding: 10px;
  background-color: white;
}

 .word:empty:before {
    content: "\0020";
    display: inline-block;
  }

<div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"> </div>
  <div class="word"></div>
</div>

Why is this happening

Vertical alignment determines how 'inline' elements are positioned in relation to each other. by default it's set to baseline

Baseline will try to put 'most' of the text above the baseline and some of the dangling bits like the g p and q and y under the baseline.

That would make sense for text, the browser will attempt to do that for all text. Even text that's wrapped in divs and styled with paddings.

The entire empty div is put on the baseline.

Browser manufacturers just agreed that this is how it should be done.

If you look at it as if it where a text editor, It would make sense for small inline images, the default would be to push the entire line down based on the dimension of the image


问:
Go plugin debugging
There is a golang application that loads the plugin at runtime. I am developing this plugin and I would like to ask if there is an opportunity to debug the code of my plugin?

I tried to run delve by compiling both the application and the plugin with --gcflags="all=-N -l", but running the application in the debugger I got an error the executable file does not contain debugging information for the plugin

Are there ways to debug golang plugin?

答:
Solution: put breakpoint via runtime.Breakpoint(), then run application with delve. It will stop on breakpoint at the plugin code.

Don't forget to build plugin and application with flags: go build -trimpath -gcflags "all=-N -l"

Title: Go plugin debugging


问:
App installation failed: The application bundle does not contain an executable in Swift Xcode
I am getting this issue while installing application into my iphone 6s plus device.

This is whats happened.
Twitter kit was creating a problem. I deleted the POD folder and pod install and pod update TwitterKit. Everything sets up. added twitterkit framework in project. After clean build an build. Everything looks fine. Then i go to install app in device with the cable. I am getting this issue now.

Tried following ways

Clean and Build again

Deleted DerivedData path ~/Library/Developer/Xcode/DerivedData

Deleted the "Executable file" entry from Info.plist and build again

Quit Xcode and Reopened

Restarted my MacBook also

Deleted ~/.itmstransporter in Bin folder

In Build Setting 'Enable Bitcode' to No

None of the above solutions make it work.
Any help will be appreciated. Thanks

答:
I had the same message and resolved this by changing the build system in the workspace settings.
In my case, the build system for "shared workspace settings" was on "new build system" and the build system fro "pre user workspace settings" was on legacy. Putting both on new build solved the problem.</p>


问:
Mirror a specific branch into another repo under a different branch name
So I currently have 2 repos: RepoA and RepoB.  I am being to asked to mirror RepoA:Branch2 into RepoB:Master.  Is there a way to mirror all the commit history of RepoA:Branch2 into RepoB:Master.

All the examples I see keep the branch name the same or mirrors all the branches.  I only need the one branch with all the history with a new branch name

I have tried mirroring and pushing but it copies everything.  I have tried

答:
Single branch copied & renamed to another repo

Based on KarateTD's and some other sources...

```<code>mkdir branch2-only
cd branch2-only
git clone --single-branch --branch branch2 https://REPO_A_URL .
git remote add repo-b https://REPO_B_URL
git push repo-b branch2:master
</code>```

Body:
Single branch copied & renamed to another repo

Based on KarateTD's and some other sources...

mkdir branch2-only
cd branch2-only
git clone --single-branch --branch branch2 https://REPO_A_URL .
git remote add repo-b https://REPO_B_URL
git push repo-b branch2:master


问:
Redux-Toolkit Middleware custom: Uncaught RangeError: Maximum call stack size exceeded
I am studying Redux-Toolkit studio, and in particular, I am approaching custom middleware.

Below I report the definition of my store within my classic application example:

```<code>import { combineReducers, configureStore} from '@reduxjs/toolkit';
import {todosSlice} from '.. /features/todos/todosSlice';
import { filterStore } from '.. /features/todos/filterSlice';
import { myLog } from '.. /reduxtoolkitmiddlewarecustom/myLog';
const rootReducer = combineReducers({
  todos: todosSlice.reducer,
  filter: filterStore.reducer
});

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware(). concat(myLog),

});
</code>```

As you see in the store amount, the middleware "custom" defined in '.. /reduxtoolkitmiddlewarecustom/myLog';

The definition of middleware is as follows:

```<code>export const myLog = (store) => {

    console.log('Init myLog');
    return function myDispatch(next) {
        return function myAction(action) { //action is the action received from the store.
            store.Dispatch({ type: 'INIT_MYLOG', payload: null });
            console.log(action);
            //return next(action);
        }
    }

};
</code>```

Well, if I emit a Dispatch, I do not return next(action), is that the return I still get an error of "Uncaught Rangeerror: Maximum call stack size exceeded".

I thought I understood, but evidently, I don't. The only way to make the code work is, for example, to make a console.log
What am I tripping about?
If found the error, in general, if the middleware makes a Dispatch in the store, must a corresponding reducer/action creator exist?

Thank you so much

答:
your middleware dispatches INIT_MYLOG on every action. and that dispatched INIT_MYLOG then triggers your middleware. and that then dispatches. an endless circle.

Solution? Don't dispatch in a middleware except if you do it as a reaction to one specific action.

Body:
I am studying Redux-Toolkit studio, and in particular, I am approaching custom middleware.

Below I report the definition of my store within my classic application example:

import { combineReducers, configureStore} from '@reduxjs/toolkit';
import {todosSlice} from '.. /features/todos/todosSlice';
import { filterStore } from '.. /features/todos/filterSlice';
import { myLog } from '.. /reduxtoolkitmiddlewarecustom/myLog';
const rootReducer = combineReducers({
  todos: todosSlice.reducer,
  filter: filterStore.reducer
});

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware(). concat(myLog),

});

As you see in the store amount, the middleware "custom" defined in '.. /reduxtoolkitmiddlewarecustom/myLog';

The definition of middleware is as follows:

export const myLog = (store) => {

    console.log('Init myLog');
    return function myDispatch(next) {
        return function myAction(action) { //action is the action received from the store.
            store.Dispatch({ type: 'INIT_MYLOG', payload: null });
            console.log(action);
            //return next(action);
        }
    }

};

Well, if I emit a Dispatch, I do not return next(action), is that the return I still get an error of "Uncaught Rangeerror: Maximum call stack size exceeded".

I thought I understood, but evidently, I don't. The only way to make the code work is, for example, to make a console.log
What am I tripping about?
If found the error, in general, if the middleware makes a Dispatch in the store, must a corresponding reducer/action creator exist?

Thank you so much


问:
How to remove dash/ hyphen from each line in .txt file
I wrote a little program to turn pages from book scans to a .txt file. On some lines, words are moved to another line. I wonder if this is any way to remove the dashes and merge them with the syllables in the line below?

E.g.:

```<code>effects on the skin is fully under-
stood one fights
</code>```

to:

```<code> effects on the skin is fully understood
 one fights
</code>```

or:

```<code>effects on the skin is fully
understood one fights
</code>```

Or something like that. As long as it was connected. Python is my third language and so far I can't think of anything, so maybe someone will give mea hint.

Edit:
The point is that the last symbol, if it is a dash, is removed and merged with the rest of the word below

答:
If you just parse the line as a string then you can utilize the .split() function to move around these kinds of items

```<code>words = "effects on the skin is fully under-\nstood one fights"
#splitting among the newlines
wordsSplit = words.split("\n")
#splitting among the word spaces
for i in range(len(wordsSplit)):
    wordsSplit[i] = wordsSplit[i].split(" ")
#checking for the end of line hyphens
for i in range(len(wordsSplit)):
    for g in range(len(wordsSplit[i])):
        if "-" in wordsSplit[i][g]:
            #setting the new word in the list and removing the hyphen
            wordsSplit[i][g] = wordsSplit[i][g][0:-1]+wordsSplit[i+1][0]
            wordsSplit[i+1][0] = ""
#recreating the string
msg = ""
for i in range(len(wordsSplit)):
    for g in range(len(wordsSplit[i])):
        if wordsSplit[i][g] != "":
            msg += wordsSplit[i][g]+" "
</code>```

What this does is split by the newlines which are where the hyphens usually occur. Then it splits those into a smaller array by word. Then checks for the hyphens and if it finds one it replaces it with the next phrase in the words list and sets that word to nothing. Finally, it reconstructs the string into a variable called msg where it doesn't add a space if the value in the split array is a nothing string.

Body:
I wrote a little program to turn pages from book scans to a .txt file. On some lines, words are moved to another line. I wonder if this is any way to remove the dashes and merge them with the syllables in the line below?

E.g.:

effects on the skin is fully under-
stood one fights

to:

 effects on the skin is fully understood
 one fights

or:

effects on the skin is fully
understood one fights

Or something like that. As long as it was connected. Python is my third language and so far I can't think of anything, so maybe someone will give mea hint.

Edit:
The point is that the last symbol, if it is a dash, is removed and merged with the rest of the word below

Body:
If you just parse the line as a string then you can utilize the .split() function to move around these kinds of items

words = "effects on the skin is fully under-\nstood one fights"
#splitting among the newlines
wordsSplit = words.split("\n")
#splitting among the word spaces
for i in range(len(wordsSplit)):
    wordsSplit[i] = wordsSplit[i].split(" ")
#checking for the end of line hyphens
for i in range(len(wordsSplit)):
    for g in range(len(wordsSplit[i])):
        if "-" in wordsSplit[i][g]:
            #setting the new word in the list and removing the hyphen
            wordsSplit[i][g] = wordsSplit[i][g][0:-1]+wordsSplit[i+1][0]
            wordsSplit[i+1][0] = ""
#recreating the string
msg = ""
for i in range(len(wordsSplit)):
    for g in range(len(wordsSplit[i])):
        if wordsSplit[i][g] != "":
            msg += wordsSplit[i][g]+" "

What this does is split by the newlines which are where the hyphens usually occur. Then it splits those into a smaller array by word. Then checks for the hyphens and if it finds one it replaces it with the next phrase in the words list and sets that word to nothing. Finally, it reconstructs the string into a variable called msg where it doesn't add a space if the value in the split array is a nothing string.


问:
able to kill ngrok tunnely remotely in terminal on other pc?

Not too sure if this question belongs in StackOverflow if it doesn't please me know where I should move to.

A question of being lazy.

I registered for ngrok as a free plan user.
Free plan limited to 1 simultaneous ngrok client session, I do use it while I am using my desktop but let's say if I forgot to close it after I am done and next day I woke up in my bed using my laptop being lazy to go to where the desktop is.  I am then not able to turn on ngrok on my laptop because desktop is running it.

Is there a way to close ngrok remotely?  I thought maybe I could kill from ngrok's dashboard but doesn't seem there's such option though.

答: One trick you can do is regenerate your authtoken from the ngrok dashboard. That will disconnect any current agents so you can start a new one.</p>


问:
Filtering strings based on replicated numerical substrings at specific places in the string (in R)
I have a list of file names/paths and I want to filter out the ones where the filename begins with the same six digits that are found after the first "/" in the path.  So for example, in the below list, numbers [1], [2], and [6] would be retained, whereas numbers [3], [4], and [5] would be removed from the new list.  I'm imagining it should be possible to split each string at the "/"s and compare the first six digits of the 2nd split with the last split, but I'm not sure how to implement this.  Any suggestions would be appreciated.</p>
```<code>tail(processed_ARL_list)
[1] "220204/220204 2022-02-04 09-32-30/ARL2200660.D/ARL2200660.pdf"
[2] "220204/220204 2022-02-04 09-32-30/ARL2200661.D/ARL2200661.pdf"
[3] "220204/220204 2022-02-04 09-32-30/REFTTO220204_.D/220204 2022-02-04 09-32-30_REFTTO220204_.pdf"
[4] "220207/220204 2022-02-07 12-51-02/REFTTO220207_.D/220204 2022-02-07 12-51-02_REFTTO220207_.pdf"
[5] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/220204 2022-02-07 12-51-02_SREF0186 METHYL EUGENOL.pdf"
[6] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/SREF0186 METHYL EUGENOL.pdf"
</code>```

答:
So I got the result I was after using this looping method.  I feel like there might be a better way, but this will do for now.

```<code>    processed_results<-c()
    for (i in c(1:length(ARL_list))){
     filepath_split<-str_split(ARL_list[i],pattern="/")
     if(substr(unlist(filepath_split)[2],1,6)!=substr(unlist(filepath_split)[length(unlist(filepath_split))],1,6)){
       processed_results[i]<-TRUE
     }  else {
         processed_results[i]<-FALSE
     }
    }
    processed_ARL_list<-ARL_list[processed_results]
</code>```

Output

```<code>tail(processed_ARL_list)
[1] "220128/220128 2022-01-28 07-53-13/ARL2200536.D/ARL2200536.pdf"
[2] "220128/220128 2022-01-28 07-53-13/ARL2200537.D/ARL2200537.pdf"
[3] "220128/220131 2022-01-31 16-10-36/REFTTO220131_.D/REFTTO220131_.pdf"
[4] "220204/220204 2022-02-04 09-32-30/ARL2200660.D/ARL2200660.pdf"
[5] "220204/220204 2022-02-04 09-32-30/ARL2200661.D/ARL2200661.pdf"
[6] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/SREF0186 METHYL EUGENOL.pdf"
</code>```

Body:
I have a list of file names/paths and I want to filter out the ones where the filename begins with the same six digits that are found after the first "/" in the path.  So for example, in the below list, numbers [1], [2], and [6] would be retained, whereas numbers [3], [4], and [5] would be removed from the new list.  I'm imagining it should be possible to split each string at the "/"s and compare the first six digits of the 2nd split with the last split, but I'm not sure how to implement this.  Any suggestions would be appreciated.

tail(processed_ARL_list)
[1] "220204/220204 2022-02-04 09-32-30/ARL2200660.D/ARL2200660.pdf"
[2] "220204/220204 2022-02-04 09-32-30/ARL2200661.D/ARL2200661.pdf"
[3] "220204/220204 2022-02-04 09-32-30/REFTTO220204_.D/220204 2022-02-04 09-32-30_REFTTO220204_.pdf"
[4] "220207/220204 2022-02-07 12-51-02/REFTTO220207_.D/220204 2022-02-07 12-51-02_REFTTO220207_.pdf"
[5] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/220204 2022-02-07 12-51-02_SREF0186 METHYL EUGENOL.pdf"
[6] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/SREF0186 METHYL EUGENOL.pdf"

Body:
So I got the result I was after using this looping method.  I feel like there might be a better way, but this will do for now.

    processed_results<-c()
    for (i in c(1:length(ARL_list))){
     filepath_split<-str_split(ARL_list[i],pattern="/")
     if(substr(unlist(filepath_split)[2],1,6)!=substr(unlist(filepath_split)[length(unlist(filepath_split))],1,6)){
       processed_results[i]<-TRUE
     }  else {
         processed_results[i]<-FALSE
     }
    }
    processed_ARL_list<-ARL_list[processed_results]

Output

tail(processed_ARL_list)
[1] "220128/220128 2022-01-28 07-53-13/ARL2200536.D/ARL2200536.pdf"
[2] "220128/220128 2022-01-28 07-53-13/ARL2200537.D/ARL2200537.pdf"
[3] "220128/220131 2022-01-31 16-10-36/REFTTO220131_.D/REFTTO220131_.pdf"
[4] "220204/220204 2022-02-04 09-32-30/ARL2200660.D/ARL2200660.pdf"
[5] "220204/220204 2022-02-04 09-32-30/ARL2200661.D/ARL2200661.pdf"
[6] "220207/220204 2022-02-07 12-51-02/SREF0186 METHYL EUGENOL.D/SREF0186 METHYL EUGENOL.pdf"


答:
Equal height
 elements can be achieved when applying the .line class style display: flex.

.line {
  background-color:red;
  padding:10px;
  display: flex;
}

.word {
  border: 1px solid red;
  margin-left: 5px;
  margin-right: 5px;
  width: 200px;
  height: 40px;
  padding: 10px;
  background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"></div>
</div></code>```

Title: css format blank string the same as actual text

Body:
Equal height <div> elements can be achieved when applying the .line class style display: flex.

.line {
  background-color:red;
  padding:10px;
  display: flex;
}

.word {
  border: 1px solid red;
  margin-left: 5px;
  margin-right: 5px;
  width: 200px;
  height: 40px;
  padding: 10px;
  background-color: white;
}

<div class="line">
  <div class="word">hello</div>
  <div class="word">there</div>
  <div class="word"></div>
</div>


问:
What's the point of blessed in Perl?
```<code>[root@ ~]$ perl -e "print 1 if blessed $a;"
1
[root@ ~]$ perl -e "print 1 if blessed $c;"
1
[root@ ~]$ perl -e "print 1 if blessed $cee;"
1
</code>```

It seems always true,the version is 5.8.8.

UPDATE

I'm not running as root, it's CHANGED by me for the sake of privacy:)

答:
blessed is not a keyword in Perl. You are using double quotes in your shell command, so the variables ($a, $c, etc.) are from your shell's environment, they are not Perl variables.
Since these environment variables are probably empty, you are essentially executing the script

```<code>print 1 if blessed ;
</code>```

When used like this, blessed is just a bareword string and always evaluates to true. What you have done is not much difference from running

```<code>$ perl -e 'print 1 if foo'
</code>```

Title: What's the point of blessed in Perl?

Body:
[root@ ~]$ perl -e "print 1 if blessed $a;"
1
[root@ ~]$ perl -e "print 1 if blessed $c;"
1
[root@ ~]$ perl -e "print 1 if blessed $cee;"
1

It seems always true,the version is 5.8.8.

UPDATE

I'm not running as root, it's CHANGED by me for the sake of privacy:)

Body:
blessed is not a keyword in Perl. You are using double quotes in your shell command, so the variables ($a, $c, etc.) are from your shell's environment, they are not Perl variables.
Since these environment variables are probably empty, you are essentially executing the script

print 1 if blessed ;

When used like this, blessed is just a bareword string and always evaluates to true. What you have done is not much difference from running

$ perl -e 'print 1 if foo'


问:
AWS Amplify not opening file
I'm trying to open a .html file "resume.html" on my website. This is my "public" folder.

I'm using React, and I'm trying to open "resume.html" in a new tab on button click with this code:

<Resume className="resume" onClick={() => window.open("/resume.html", "_blank")}>View Resume</Resume>

Everything works fine during development. on my localhost: 3000, the resume opens in a new tab just fine. But when I host the site on AWS Amplify, the button click loads "index.html".

I have no idea why the AWS amplify server would be loading a different file than my localhost server.

答:
If you use ReactJS then everything will go through a build step to create the deployment assets that make up the Single Page Application. The result of this build step is what will be deployed to be hosted on AWS.

For navigation in ReactJS it is better to use a routing library like React Router. You can create a new React Component for the resume content and navigate to it using a Router Link. This will work better for the Single Page Application to understand rather than opening a HMTL page with window.open.

Title: AWS Amplify not opening file


问:
How can I access a service running on WSL2 from inside a Docker container?
I am using Windows 10 1909 and have installed WSL2, using Ubuntu 20.04, the 19.03.13-beta2 docker version, having installed Docker for Windows Edge version using the WSL2 option. The integration is working pretty great, but I have one issue which I cannot solve.

On the WSL2 instance, there are services running, exposing some ports (3000, 3001, 3002,...). From one of the docker containers, I need to access the services for a specific development scenario (API Gateway), and this I cannot get to work.

I have tried using the WSL2 IP address directly, but then the connect just times out. I have also tried using host.docker.internal, which resolves to something else than the WSL2 IP address, but it still doesn't work.

Is there a special trick I need to pull, or is this kind of routing currently not supported, but will be, or is this for some other reason not possible?

This illustrates what I am trying to achieve:

The other routings work - i.e. I can access all the service ports coming from the node.js processes inside WSL2 from the Windows browser, and also I can access the exposed service ports from the containers both from inside WSL2 and from Windows. It's just this missing link I cannot make work.

答:
I ran into this problem with the latest Docker Desktop. I rolled it back to 4.2 and it worked.

Docker Desktop 4.2

Windows 19044.1466

Ubuntu 20.04

I have a java service running on a linux local host (accessing the IP address using ifconfig command), my other containers running on docker desktop using the WSL2 based engine, which can communicate to my java service using the IP address.


问:
SwiftUI: Preview with data in ViewModel
I load my data from a viewModel which is loading data from web. Problem: I want to set some preview sample data to have content in preview window. Currently my preview contains an empty list as I do not provide data.

How can I achieve this?

```<code>struct MovieListView: View {

    @ObservedObject var viewModel = MovieViewModel()

    var body: some View {
       List{
        ForEach(viewModel.movies) { movie in
                MovieRow(movie: movie)
                    .listRowInsets(EdgeInsets())
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MovieListView()
    }
}

class MovieViewModel: ObservableObject{

    private let provider = NetworkManager()

    @Published var movies = [Movie]()

    init() {
       loadNewMovies()
    }

    func loadNewMovies(){
         provider.getNewMovies(page: 1) {[weak self] movies in
                   print("\(movies.count) new movies loaded")
                   self?.movies.removeAll()
            self?.movies.append(contentsOf: movies)}
    }
}
</code>```

答:
This question was written before @StateObject was introduced at WWDC 2020. I believe these days you'd want to use @StateObject instead of @ObservedObject because otherwise your view model can be re-initialized numerous times (which would result in multiple network calls in this case).

I wanted to do the exact same thing as OP, but with @StateObject. Here's my solution that doesn't rely on any build configurations.

struct MovieListView: View {

    @StateObject var viewModel = MovieViewModel()

    var body: some View {
        MovieListViewInternal(viewModel: viewModel)
    }
}

private struct MovieListViewInternal<ViewModel: MovieViewModelable>: View {

    @ObservedObject var viewModel: ViewModel

    var body: some View {
       List {
           ForEach(viewModel.movies) { movie in
               MovieRow(movie: movie)
           }
       }
       .onAppear {
           viewModel.fetchMovieRatings()
       }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MovieListViewInternal(viewModel: PreviewMovieViewModel())
    }
}
```
<p>The View model protocols and implementations:</p>
<pre class="lang-swift prettyprint-override"><code>protocol MovieViewModelable: ObservableObject {
    var movies: [Movie] { get }
    func fetchMovieRatings()
    // Define vars or funcs for anything else your view accesses in your view model
}

class MovieViewModel: MovieViewModelable {

    @Published var movies = [Movie]()

    init() {
       loadNewMovies()
    }

    private func loadNewMovies() {
        // do the network call
    }

    func fetchMovieRatings() {
        // do the network call
    }
}

class PreviewMovieViewModel: MovieViewModelable {
    @Published var movies = [fakeMovie1, fakeMovie2]

    func fetchMovieRankings() {} // do nothing while in a Preview
}
</code>```

This way your external interface to MovieListView is exactly the same, but for your previews you can use the internal view definition and override the view model type.

Title: SwiftUI: Preview with data in ViewModel

Body:
I load my data from a viewModel which is loading data from web. Problem: I want to set some preview sample data to have content in preview window. Currently my preview contains an empty list as I do not provide data.

How can I achieve this?

struct MovieListView: View {

    @ObservedObject var viewModel = MovieViewModel()

    var body: some View {
       List{
        ForEach(viewModel.movies) { movie in
                MovieRow(movie: movie)
                    .listRowInsets(EdgeInsets())
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MovieListView()
    }
}

class MovieViewModel: ObservableObject{

    private let provider = NetworkManager()

    @Published var movies = [Movie]()

    init() {
       loadNewMovies()
    }

    func loadNewMovies(){
         provider.getNewMovies(page: 1) {[weak self] movies in
                   print("\(movies.count) new movies loaded")
                   self?.movies.removeAll()
            self?.movies.append(contentsOf: movies)}
    }
}

Body:
This question was written before @StateObject was introduced at WWDC 2020. I believe these days you'd want to use @StateObject instead of @ObservedObject because otherwise your view model can be re-initialized numerous times (which would result in multiple network calls in this case).

I wanted to do the exact same thing as OP, but with @StateObject. Here's my solution that doesn't rely on any build configurations.

struct MovieListView: View {

    @StateObject var viewModel = MovieViewModel()

    var body: some View {
        MovieListViewInternal(viewModel: viewModel)
    }
}

private struct MovieListViewInternal<ViewModel: MovieViewModelable>: View {

    @ObservedObject var viewModel: ViewModel

    var body: some View {
       List {
           ForEach(viewModel.movies) { movie in
               MovieRow(movie: movie)
           }
       }
       .onAppear {
           viewModel.fetchMovieRatings()
       }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MovieListViewInternal(viewModel: PreviewMovieViewModel())
    }
}

The View model protocols and implementations:

protocol MovieViewModelable: ObservableObject {
    var movies: [Movie] { get }
    func fetchMovieRatings()
    // Define vars or funcs for anything else your view accesses in your view model
}

class MovieViewModel: MovieViewModelable {

    @Published var movies = [Movie]()

    init() {
       loadNewMovies()
    }

    private func loadNewMovies() {
        // do the network call
    }

    func fetchMovieRatings() {
        // do the network call
    }
}

class PreviewMovieViewModel: MovieViewModelable {
    @Published var movies = [fakeMovie1, fakeMovie2]

    func fetchMovieRankings() {} // do nothing while in a Preview
}

This way your external interface to MovieListView is exactly the same, but for your previews you can use the internal view definition and override the view model type.


答:
What about

```<code>import re

a = '''effects on the skin is fully under-
stood one fights'''

re.sub(r'-~([a-zA-Z0-9]*) ', r'\1\n', a.replace('\n', '~')).replace('~','\n')
</code>```

Explanation

a.replace('\n', '~') concatenate input string into one line with (~ instead of \n - You need to choose some other if you want to use ~ char in the text.)

-~([a-zA-Z0-9]*) regex then selects all strings we want to alter with the () backreference which saves it to re.sub memory. Using '\1\n' it is later re-invoked.

.replace('~','\n') finally replaces all remaining ~ chars to newlines.

Title: How to remove dash/ hyphen from each line in .txt file

Body:
What about

import re

a = '''effects on the skin is fully under-
stood one fights'''

re.sub(r'-~([a-zA-Z0-9]*) ', r'\1\n', a.replace('\n', '~')).replace('~','\n')

Explanation

a.replace('\n', '~') concatenate input string into one line with (~ instead of \n - You need to choose some other if you want to use ~ char in the text.)

-~([a-zA-Z0-9]*) regex then selects all strings we want to alter with the () backreference which saves it to re.sub memory. Using '\1\n' it is later re-invoked.

.replace('~','\n') finally replaces all remaining ~ chars to newlines.


问:
Group array of string arrays with LINQ
I have array like this, values are string:

```<code>var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };
</code>```

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

```<code>[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]
</code>```

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

答:
Normally I would use an extension method for grouping runs of items based on a predicate, in this case GroupByEndingWith and then throw away the "END" record, like so:

```<code>var ans = allArrays.GroupByEndingWith(r => r[0] == "END")
                   .Select(g => g.Drop(1).ToArray())
                   .ToArray();
</code>```

But, in general, you can use Aggregate to collect items based on a predicate at the expense of comprehension. It often helps to use a tuple to track an overall accumulator and a sub-accumulator. Unfortunately, there is no + operator or Append for List<T> that returns the original list (helpful for expression based accumulation) and since C# doesn't yet have a comma operator equivalent, you need an extension method again or you can use ImmutableList.

Using Aggregate and ImmutableList, you can do:

```<code>var ans = allArrays.Aggregate(
                (ans: ImmutableList<ImmutableList<string[]>>.Empty, curr: ImmutableList<string[]>.Empty),
                (ac, r) => r[0] == "END"
                                ? (ac.ans.Add(ac.curr), ImmutableList<string[]>.Empty)
                                : (ac.ans, ac.curr.Add(r))
          ).ans
          .Select(l => l.ToArray())
          .ToArray();
</code>```

NOTE: You can also do this with List if you are willing to create new Lists a lot:

```<code>var ans = allArrays.Aggregate(
                (ans: new List<List<string[]>>(), curr: new List<string[]>()),
                (ac, r) => r[0] == "END"
                                ? (ac.ans.Concat(new[] { ac.curr }).ToList(), new List<string[]>())
                                : (ac.ans, ac.curr.Concat(new[] { r }).ToList())
          ).ans
          .Select(l => l.ToArray())
          .ToArray();
</code>```

Title: Group array of string arrays with LINQ

Body:
I have array like this, values are string:

var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

Body:
Normally I would use an extension method for grouping runs of items based on a predicate, in this case GroupByEndingWith and then throw away the "END" record, like so:

var ans = allArrays.GroupByEndingWith(r => r[0] == "END")
                   .Select(g => g.Drop(1).ToArray())
                   .ToArray();

But, in general, you can use Aggregate to collect items based on a predicate at the expense of comprehension. It often helps to use a tuple to track an overall accumulator and a sub-accumulator. Unfortunately, there is no + operator or Append for List<T> that returns the original list (helpful for expression based accumulation) and since C# doesn't yet have a comma operator equivalent, you need an extension method again or you can use ImmutableList.

Using Aggregate and ImmutableList, you can do:

var ans = allArrays.Aggregate(
                (ans: ImmutableList<ImmutableList<string[]>>.Empty, curr: ImmutableList<string[]>.Empty),
                (ac, r) => r[0] == "END"
                                ? (ac.ans.Add(ac.curr), ImmutableList<string[]>.Empty)
                                : (ac.ans, ac.curr.Add(r))
          ).ans
          .Select(l => l.ToArray())
          .ToArray();

NOTE: You can also do this with List if you are willing to create new Lists a lot:

var ans = allArrays.Aggregate(
                (ans: new List<List<string[]>>(), curr: new List<string[]>()),
                (ac, r) => r[0] == "END"
                                ? (ac.ans.Concat(new[] { ac.curr }).ToList(), new List<string[]>())
                                : (ac.ans, ac.curr.Concat(new[] { r }).ToList())
          ).ans
          .Select(l => l.ToArray())
          .ToArray();


问:
How should I manage multithreaded concurrent access to an ArrayDeque?
My Swing GUI displays a JList of items that are being sequentially removed by a background thread.

Behind the JList is an ArrayDeque<Card>, myHopper, implementing myHopper.getSize() and myHopper.getElementAt(), as per the contract of an AbstractListModel.

The background thread removes items using myHopper.poll().

Not surprisingly, I'm getting AWT array index out of bounds exceptions currently.

What should I be doing to properly synchronize access to myList between the EDT thread and my background thread?  I have seen references to Collections.synchronizedList(arrayList) but I don't think that fits my ArrayDeque.

答:
The short answer to my question appears to be "You can't: you must never attempt to access a Swing component [and that includes its model] from any thread other than the EDT."

This post shows how I eventually solved the problem.  A worker thread needs to pull an item from a JList's model, and does so using invokeAndWait() to schedule that work on the EDT, and then waits until that task is done, and then continues.

Using the synchronized LinkedBlockingDeque didn't work, and I suspect that it's because the EDT makes a nonatomic series of calls to the Deque interface when updating the GUI component.  Any change to the model between calls, by another thread, could destroy any assumptions of stability that the EDT is making.

(Perhaps that's what's being hinted at by the persistent "Warning: Swing is not thread safe" that appears throughout the Swing documentation.)


问:
How do I make the first letter of a string uppercase in JavaScript?
How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?

For example:

"this is a test" → "This is a test"

"the Eiffel Tower" → "The Eiffel Tower"

"/index.html" → "/index.html"

答:
Capitalize and Uncapitalize first Char of a String.

Functions to include:

```<code>/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}
</code>```

Example1 "First Character uppercase":

```<code>alert(capitalize("hello world"));
</code>```

Result: Hello world

Example 2 "First Character lowercase":

```<code>alert(uncapitalize("Hello World, today is sunny"));
</code>```

Result: hello World, today is sunny

Body:
Capitalize and Uncapitalize first Char of a String.

Functions to include:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

Example1 "First Character uppercase":

alert(capitalize("hello world"));

Result: Hello world

Example 2 "First Character lowercase":

alert(uncapitalize("Hello World, today is sunny"));

Result: hello World, today is sunny


问:
Put word by word in paragraphs
How can I put an output a text.txt file so that it is sorted as follows:

"This is a way

that has a little text

for it to be placed

where every word

be in a paragraph."

答:
you could do something like this to get the individual words on their own lines</p>
```<code>with open('text.txt', 'r', encoding='utf-8') as f:
    for l in f:
        line = l.replace('\n', '')
        for item in line.split(' '):
            print(item)
</code>```

Title: Put word by word in paragraphs

Body:
you could do something like this to get the individual words on their own lines

with open('text.txt', 'r', encoding='utf-8') as f:
    for l in f:
        line = l.replace('\n', '')
        for item in line.split(' '):
            print(item)


问:
.Net Core Application Parts, change view import/search location
I've been experimenting with ASP.NET Core application parts, but have ran into two problems:

Firstly, I need a way to specify an extra directory in the view engine's search path, some of the time.

Secondly, is there any way to change the import location of views when pulled in through application parts?

The reason I am asking is due to some of my application parts having identically named controllers and views (i.e., Home/Index) which causes AmbiguousMatchExceptions. I have already relocated the controllers using a namespace routing scheme detailed here: .net core replacement for MvcCodeRouting. Namespace based routing.

Any help would be appreciated. Thanks.

答:
An implementation of the IViewLocationExpander interface did the job in this case.

By creating an implementation of the IViewLocationExpander, you can specify alternative locations, in which, views may be located. The "default" locations are passed into the ExpandViewLocations method (which returns an IEnumerable<string>), only the locations returned are searched, meaning that you get the choice to either include the defaults or leave them out, forcing only your newly specified locations to be searched.


问:
How to apply Keras Normalization to a ParallelMapDataset without making it eager?
I am training a Tensorflow Keras CNN over images, too much training data to fit into memory.  I've got a tf.Dataset preprocessing pipeline that reads the images from HDF5 files using a dataset.map() pipeline step.  Now I'm trying to normalize the numeric image data to 0 mean and unit variance.

I'm following this example from this guide, except that I have that .map() in there:

def load_features_from_hdf5(filename):
    spec = tf.TensorSpec(feature_shape, dtype=tf.dtypes.float32, name=None)
    dataset = tfio.IODataset.from_hdf5(filename, "/features", spec=spec)  # returns a Dataset
    feature = dataset.get_single_element()
    feature.set_shape(feature_shape)
    return feature

train_x = tf.data.Dataset.from_tensor_slices(filenames).map(load_features_from_fbank, num_parallel_calls=tf.data.AUTOTUNE)

normalizer = tf.keras.layers.Normalization(axis=None)
normalizer.adapt(train_x.take(1000))

train_x_normalized = normalizer(train_x)  #  <-- ValueError
```

adapt() successfully computes the mean and variance from the dataset.  But when I try to actually apply normalization of values on the exact same dataset, it errors while trying to convert my ParallelMapDataset to an EagerTensor.

ValueError: Attempt to convert a value (<ParallelMapDataset shapes: (41, 682, 1), types: tf.float32>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.ParallelMapDataset'>) to a Tensor.

How can I get this working?  Since the data is so large, I wouldn't think I want to make anything eager until training starts.  Should I make the normalization an explicit pipeline step on the Dataset?  Or an explicit layer on the model itself?  (If the latter case, how can I bring the mean and variance values from training time to inference time in another process?)

答:
You could try something like this:

import tensorflow as tf

# Create dummy data
train_x = tf.data.Dataset.from_tensor_slices((tf.random.normal((100, 28, 28, 3)), tf.random.normal((100, 1)))).batch(10)

normalizer = tf.keras.layers.Normalization(axis=None)

# Adapt
normalizer.adapt(train_x.map(lambda x, y: x))

# Apply to images
train_x_normalized = train_x.map(lambda x, y: (normalizer(x), y))
```
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>for x, y in train_x_normalized.take(1):
  print(tf.reduce_mean(x), tf.math.reduce_variance(x))
</code>```
```<code>tf.Tensor(0.00930768, shape=(), dtype=float32) tf.Tensor(1.0023469, shape=(), dtype=float32)
</code>```

Or, as you mentioned in your question, your can use the normalization layer as part of your model.

Body:
I am training a Tensorflow Keras CNN over images, too much training data to fit into memory.  I've got a tf.Dataset preprocessing pipeline that reads the images from HDF5 files using a dataset.map() pipeline step.  Now I'm trying to normalize the numeric image data to 0 mean and unit variance.

I'm following this example from this guide, except that I have that .map() in there:

def load_features_from_hdf5(filename):
    spec = tf.TensorSpec(feature_shape, dtype=tf.dtypes.float32, name=None)
    dataset = tfio.IODataset.from_hdf5(filename, "/features", spec=spec)  # returns a Dataset
    feature = dataset.get_single_element()
    feature.set_shape(feature_shape)
    return feature

train_x = tf.data.Dataset.from_tensor_slices(filenames).map(load_features_from_fbank, num_parallel_calls=tf.data.AUTOTUNE)

normalizer = tf.keras.layers.Normalization(axis=None)
normalizer.adapt(train_x.take(1000))

train_x_normalized = normalizer(train_x)  #  <-- ValueError

adapt() successfully computes the mean and variance from the dataset.  But when I try to actually apply normalization of values on the exact same dataset, it errors while trying to convert my ParallelMapDataset to an EagerTensor.

ValueError: Attempt to convert a value (<ParallelMapDataset shapes: (41, 682, 1), types: tf.float32>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.ParallelMapDataset'>) to a Tensor.

How can I get this working?  Since the data is so large, I wouldn't think I want to make anything eager until training starts.  Should I make the normalization an explicit pipeline step on the Dataset?  Or an explicit layer on the model itself?  (If the latter case, how can I bring the mean and variance values from training time to inference time in another process?)

Body:
You could try something like this:

import tensorflow as tf

# Create dummy data
train_x = tf.data.Dataset.from_tensor_slices((tf.random.normal((100, 28, 28, 3)), tf.random.normal((100, 1)))).batch(10)

normalizer = tf.keras.layers.Normalization(axis=None)

# Adapt
normalizer.adapt(train_x.map(lambda x, y: x))

# Apply to images
train_x_normalized = train_x.map(lambda x, y: (normalizer(x), y))

Example:

for x, y in train_x_normalized.take(1):
  print(tf.reduce_mean(x), tf.math.reduce_variance(x))

tf.Tensor(0.00930768, shape=(), dtype=float32) tf.Tensor(1.0023469, shape=(), dtype=float32)

Or, as you mentioned in your question, your can use the normalization layer as part of your model.


问:
How can I get a value from an if statement and work out the difference
I have a function that checks if a user has the app open or closed. If opened take the current time and store it in a variable, if the app is closed, do the same. then it should work out the difference and print it back.

I'm trying to work out how long the user has spent on the app.

I just not sure how to get it to work, I've tried to assign it to a global and use it from there but that did not work, I've tried sending the values to another function but I keep getting null returned.

What can I do to fix this?

*.dart

```<code>activeTimer(value) {
    print(value);

    if (value == true) {
      startTimer();
      print("TRUE 1");
      DateTime dateTimeStart = DateTime.now();
    } else {
      print("FALSE 1");
      stopTimer();
      DateTime dateTimeEnd = DateTime.now();
    };

  final differenceInDays = dateTimeEnd.difference(dateTimeStart).inMinutes;
    print(differenceInDays);

  }
</code>```

答:
You can check when your app is being closed (or placed in background), so just initialize a variable when the app starts and calculate the time when the app closes:

in your main.dart file

```<code>late DateTime app_start;
@override
  initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    app_start = DateTime.now();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // check if app is closed -> substract current time from app_start
    // save to local storage or send to cloud or smth
  }
</code>```

Body:
I have a function that checks if a user has the app open or closed. If opened take the current time and store it in a variable, if the app is closed, do the same. then it should work out the difference and print it back.

I'm trying to work out how long the user has spent on the app.

I just not sure how to get it to work, I've tried to assign it to a global and use it from there but that did not work, I've tried sending the values to another function but I keep getting null returned.

What can I do to fix this?

*.dart

activeTimer(value) {
    print(value);

    if (value == true) {
      startTimer();
      print("TRUE 1");
      DateTime dateTimeStart = DateTime.now();
    } else {
      print("FALSE 1");
      stopTimer();
      DateTime dateTimeEnd = DateTime.now();
    };

  final differenceInDays = dateTimeEnd.difference(dateTimeStart).inMinutes;
    print(differenceInDays);

  }

Body:
You can check when your app is being closed (or placed in background), so just initialize a variable when the app starts and calculate the time when the app closes:

in your main.dart file

late DateTime app_start;
@override
  initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    app_start = DateTime.now();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // check if app is closed -> substract current time from app_start
    // save to local storage or send to cloud or smth
  }


问:
React: Data.map not rerendering after data state has been updated
I am trying to learn how to sort some data using react and TailwindCss, but upon trying I found a problem which I can't put my finger on, after sorting the data array it's not data.map is not re-rendering and I don't know why, can someone help me understand how to fix it, and why this happens.

```<code>import { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);

  // this is the sorting function
  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
    console.log("sort",data);
  };

  useEffect(() => {
    axios
      .get("https://dummyapi.io/data/v1/user?limit=50", {
        headers: {
          "app-id": "6200ff0858dcad3e84d67c55",
        },
      })
      .then((res) => {
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    console.log(data);
  }, [data])

  return (
    <div className="flex justify-center min-h-screen App bg-background min-w-screen">
      <div className="container">
        <div className="flex flex-col items-center gap-4 py-5">
          <h1 className="text-3xl">Filter & sorting app</h1>
          <div className="relative w-full">
            <div className="right-0 ">
              <select className="flex content-end px-3 py-2 bg-white shadow-sm rounded-xl">
                <option
                  value="volvo"
                  className="text-gray-100"
                  selected
                  disabled
                  hidden
                >
                  Sort by
                </option>
                <option value="saab" onClick={sortData}>
                  Ascending
                </option>
                <option value="opel">Descending</option>
              </select>
            </div>
          </div>
          <div className="w-full flex justify-center gap-8 flex-wrap bg-white p-8 min-h-[300px] border-2 rounded-xl">
            {/* here i map on the data state but it does nor re-render after data has changed  */}
            {data?.length > 0 ? (
              data.map((user) => (
                <div
                  className="bg-blue-300 sm:w-[200px] sm:h-[200px] w-[150px] h-[150px] rounded-3xl p-4 flex flex-col items-center mt-8"
                  key={user.id}
                >
                  <img
                    src={user.picture}
                    alt={`"user_"${user.id}`}
                    className="relative w-20 h-20 rounded-full -top-12"
                  />
                  <div className="flex flex-row -mt-6 text-center sm:mt-0">
                    <h1 className="text-xl capitalize sm:text-3xl">
                      {user.title}.
                      <p className="text-sm sm:text-xl">
                        {user.firstName} {user.lastName}
                      </p>
                    </h1>
                  </div>
                </div>
              ))
            ) : (
              <div className="flex items-center justify-center">
                <h1 className="text-3xl">Loading...</h1>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;
</code>```

EDIT: if you have a better implementation of this please let me know.

答:
This sort function does not return any array. so instead to this:

```<code>  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
  };
</code>```

Try this

```<code>  const sortData = () => {
    var newArr = [...data];
    newArr.sort((a, b) => a.firstName.localeCompare(b.firstName))
    setData(newArr);
  };
</code>```

Body:
I am trying to learn how to sort some data using react and TailwindCss, but upon trying I found a problem which I can't put my finger on, after sorting the data array it's not data.map is not re-rendering and I don't know why, can someone help me understand how to fix it, and why this happens.

import { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);

  // this is the sorting function
  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
    console.log("sort",data);
  };

  useEffect(() => {
    axios
      .get("https://dummyapi.io/data/v1/user?limit=50", {
        headers: {
          "app-id": "6200ff0858dcad3e84d67c55",
        },
      })
      .then((res) => {
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    console.log(data);
  }, [data])

  return (

Filter & sorting app

              <select className="flex content-end px-3 py-2 bg-white shadow-sm rounded-xl">
                <option
                  value="volvo"
                  className="text-gray-100"
                  selected
                  disabled
                  hidden
                >
                  Sort by
                </option>
                <option value="saab" onClick={sortData}>
                  Ascending
                </option>
                <option value="opel">Descending</option>
              </select>

            {/* here i map on the data state but it does nor re-render after data has changed  */}
            {data?.length > 0 ? (
              data.map((user) => (

                  <img
                    src={user.picture}
                    alt={`"user_"${user.id}`}
                    className="relative w-20 h-20 rounded-full -top-12"
                  />

                      {user.title}.

                        {user.firstName} {user.lastName}

              ))
            ) : (

Loading...

            )}

  );
}

export default App;

EDIT: if you have a better implementation of this please let me know.

Body:
This sort function does not return any array. so instead to this:

  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
  };

Try this

  const sortData = () => {
    var newArr = [...data];
    newArr.sort((a, b) => a.firstName.localeCompare(b.firstName))
    setData(newArr);
  };


问:
Can't access a specific element in a 2D Matrix represented as a List of Lists
I am trying to access a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

```<code>(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (elt 0 (elt 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))
</code>```

The following output is:

"- ELT: 0 is not a SEQUENCE"

This seems strange, as I thought that the ELT method can be used to get values within a list?

答:
Wrong argument order for elt:

elt sequence index => object

Body:
I am trying to access a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (elt 0 (elt 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))

The following output is:

"- ELT: 0 is not a SEQUENCE"

This seems strange, as I thought that the ELT method can be used to get values within a list?


问:
Is there a good tool for Makefile generation?
I'm looking for a tool which can generate a Makefile for a C/C++ project for different compilers (GCC, Microsoft Visual C++, C++Builder, etc.) and different platforms (Windows, Linux, and Mac).</p>

答: A recent addition to the list of make replacements is waf. From personal experience, SCons does the job pretty well.</p>

OwnerDisplayName: Serge


问:
BeautifulSoup and Pandas read_html is not pulling all of the rows in a table
When I am scraping a table from a website, it is missing the bottom 5 rows of data and I do not know how to pull them. I am using a combination of BeautifulSoup and Selenium. I thought that they were not loading, so I tried scrolling to the bottom with Selenium, but that still did not work.

Code trials:

```<code>site = 'https://fbref.com//en/comps/15/10733/schedule/2020-2021-League-One'
PATH = my_path
driver = webdriver.Chrome(PATH)
driver.get(site)
webpage = bs.BeautifulSoup(driver.page_source, features='html.parser')

table = webpage.find('table', {'class': 'stats_table sortable min_width now_sortable'})
print(table.prettify())
df = pd.read_html(str(table))[0]

print(df.tail())
</code>```

Please could you help with scraping the full table?

答:
Using only Selenium to pull all the rows from the table within the website you need to induce WebDriverWait for the visibility_of_element_located() and using DataFrame from Pandas you can use the following Locator Strategy:

Using CSS_SELECTOR:

```<code>tabledata = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "table.stats_table.sortable.min_width.now_sortable"))).get_attribute("outerHTML")
tabledf = pd.read_html(tabledata)
print(tabledf)
</code>```

Using XPATH:

```<code>driver.get('https://fbref.com//en/comps/15/10733/schedule/2020-2021-League-One')
data = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@class='stats_table sortable min_width now_sortable']"))).get_attribute("outerHTML")
df = pd.read_html(data)
print(df)
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Console Output:

```<code>[              Round   Wk  Day  ...             Referee  Match Report                         Notes
0    Regular Season    1  Sat  ...  Charles Breakspear  Match Report                           NaN
1    Regular Season    1  Sat  ...       Andrew Davies  Match Report                           NaN
2    Regular Season    1  Sat  ...       Kevin Johnson  Match Report                           NaN
3    Regular Season    1  Sat  ...   Anthony Backhouse  Match Report                           NaN
4    Regular Season    1  Sat  ...        Marc Edwards  Match Report                           NaN
..              ...  ...  ...  ...                 ...           ...                           ...
685     Semi-finals  NaN  Tue  ...       Robert Madley  Match Report                    Leg 1 of 2
686     Semi-finals  NaN  Wed  ...         Craig Hicks  Match Report                    Leg 1 of 2
687     Semi-finals  NaN  Fri  ...        Keith Stroud  Match Report     Leg 2 of 2; Blackpool won
688     Semi-finals  NaN  Sat  ...   Michael Salisbury  Match Report  Leg 2 of 2; Lincoln City won
689           Final  NaN  Sun  ...     Tony Harrington  Match Report                           NaN

    [690 rows x 13 columns]]
</code>```

Body:
When I am scraping a table from a website, it is missing the bottom 5 rows of data and I do not know how to pull them. I am using a combination of BeautifulSoup and Selenium. I thought that they were not loading, so I tried scrolling to the bottom with Selenium, but that still did not work.

Code trials:

site = 'https://fbref.com//en/comps/15/10733/schedule/2020-2021-League-One'
PATH = my_path
driver = webdriver.Chrome(PATH)
driver.get(site)
webpage = bs.BeautifulSoup(driver.page_source, features='html.parser')

table = webpage.find('table', {'class': 'stats_table sortable min_width now_sortable'})
print(table.prettify())
df = pd.read_html(str(table))[0]

print(df.tail())

Please could you help with scraping the full table?

Body:
Using only Selenium to pull all the rows from the table within the website you need to induce WebDriverWait for the visibility_of_element_located() and using DataFrame from Pandas you can use the following Locator Strategy:

Using CSS_SELECTOR:

tabledata = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "table.stats_table.sortable.min_width.now_sortable"))).get_attribute("outerHTML")
tabledf = pd.read_html(tabledata)
print(tabledf)

Using XPATH:

driver.get('https://fbref.com//en/comps/15/10733/schedule/2020-2021-League-One')
data = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@class='stats_table sortable min_width now_sortable']"))).get_attribute("outerHTML")
df = pd.read_html(data)
print(df)

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Console Output:

[              Round   Wk  Day  ...             Referee  Match Report                         Notes
0    Regular Season    1  Sat  ...  Charles Breakspear  Match Report                           NaN
1    Regular Season    1  Sat  ...       Andrew Davies  Match Report                           NaN
2    Regular Season    1  Sat  ...       Kevin Johnson  Match Report                           NaN
3    Regular Season    1  Sat  ...   Anthony Backhouse  Match Report                           NaN
4    Regular Season    1  Sat  ...        Marc Edwards  Match Report                           NaN
..              ...  ...  ...  ...                 ...           ...                           ...
685     Semi-finals  NaN  Tue  ...       Robert Madley  Match Report                    Leg 1 of 2
686     Semi-finals  NaN  Wed  ...         Craig Hicks  Match Report                    Leg 1 of 2
687     Semi-finals  NaN  Fri  ...        Keith Stroud  Match Report     Leg 2 of 2; Blackpool won
688     Semi-finals  NaN  Sat  ...   Michael Salisbury  Match Report  Leg 2 of 2; Lincoln City won
689           Final  NaN  Sun  ...     Tony Harrington  Match Report                           NaN

    [690 rows x 13 columns]]


问:
Error setting-up flutter_localizations package "Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/app_localizations.dart'."
This error appears when I try to add language support to my flutter application:

```<code>Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/app_localizations.dart'. Try creating the file referenced by the URI, or Try using a URI for a file that does exist.
</code>```

I’m using flutter_localizations, the project is built with dart 2.7.0

It seems that flutter_localizations needs latest sdk which is dart 2.13.0

How can I fix this?

答:
Be sure that there's an l10n.yaml file in your project root as follows.

Example

Demonstration variables

foldername = l10n

defaultIntlFile = intl_en.arb

importFileName = app_localizations.dart

Import

import 'package:flutter_gen/gen_l10n/importFileName';

l10n.yaml

arb-dir: lib/foldername

template-arb-file: intl_en.arb

output-localization-file: app_localizations.dart

Structure

lib/foldername/defaultIntlFile

Body:
This error appears when I try to add language support to my flutter application:

Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/app_localizations.dart'. Try creating the file referenced by the URI, or Try using a URI for a file that does exist.

I’m using flutter_localizations, the project is built with dart 2.7.0

It seems that flutter_localizations needs latest sdk which is dart 2.13.0

How can I fix this?


问:
WebClient should ignore unsucessful requests
The following code causes an empty list if url1 returns many results but url2 returns a 404. How to ignore error properly and just continue with the succesful responses of url1?</p>
```<code>        Set<String> list = new HashSet<>();

    Mono<String> first = WebClient.create(url1)
            .get()
            .retrieve()
            .bodyToMono(String.class)
            .onErrorResume(e -> {
                return Mono.empty();
            });

    Mono<String> two = WebClient.create()
            .get()
            .retrieve()
            .bodyToMono(String.class)
            .onErrorResume(e -> {
                return Mono.empty();
            });

    Flux.zip(first, two)
            .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
            .subscribe(
                    responses -> {
                        for (Object response : responses) {
                            String[] lines = ((String)response).split("\n");
                            for(String line : lines) {
                                list.add(line);
                            }
                        }
                    }
            );
</code>```

答:
I've simplified your example, replacing the two webclient calls with their expected output, mainly for demonstration purposes.

You can use merge instead zip, to avoid the entire Flux returning empty if one single source is empty.

Flux.merge(Mono.just("1\n2\n3"), Mono.empty())
                .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
                .subscribe(
                        responses -> {
                            List<String> stringList = Arrays.stream(responses.split("\n")).collect(Collectors.toList());
                            stringList.forEach(System.out::println);
                        });
```
<p>JavaDoc</p>
<p><em>NOTE</em></p>
<p>It's worth mentioning that processing the result in the <code>subscribe</code> method and adding it to a variable defined outside of the reactive stream is a little unusual. The more expected use case would be to process the data in a <code>flatMap</code>/<code>map</code> and return either a <code>Mono<List<String>></code> or <code>Flux<String></code> out of your method ie.</p>
<p><em>Example returning a <code>Mono<List<String>></code></em></p>
<pre class="lang-java prettyprint-override"><code>Flux.merge(Mono.just("1\n2\n3"), Mono.empty())
                .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
                .flatMap(strings -> Flux.fromArray(strings.split("\n")))
                .collectList()
</code>```

Body:
The following code causes an empty list if url1 returns many results but url2 returns a 404. How to ignore error properly and just continue with the succesful responses of url1?

        Set<String> list = new HashSet<>();

    Mono<String> first = WebClient.create(url1)
            .get()
            .retrieve()
            .bodyToMono(String.class)
            .onErrorResume(e -> {
                return Mono.empty();
            });

    Mono<String> two = WebClient.create()
            .get()
            .retrieve()
            .bodyToMono(String.class)
            .onErrorResume(e -> {
                return Mono.empty();
            });

    Flux.zip(first, two)
            .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
            .subscribe(
                    responses -> {
                        for (Object response : responses) {
                            String[] lines = ((String)response).split("\n");
                            for(String line : lines) {
                                list.add(line);
                            }
                        }
                    }
            );

Body:
I've simplified your example, replacing the two webclient calls with their expected output, mainly for demonstration purposes.

You can use merge instead zip, to avoid the entire Flux returning empty if one single source is empty.

Flux.merge(Mono.just("1\n2\n3"), Mono.empty())
                .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
                .subscribe(
                        responses -> {
                            List<String> stringList = Arrays.stream(responses.split("\n")).collect(Collectors.toList());
                            stringList.forEach(System.out::println);
                        });

JavaDoc

NOTE

It's worth mentioning that processing the result in the subscribe method and adding it to a variable defined outside of the reactive stream is a little unusual. The more expected use case would be to process the data in a flatMap/map and return either a Mono<List<String>> or Flux<String> out of your method ie.

Example returning a Mono<List<String>>

Flux.merge(Mono.just("1\n2\n3"), Mono.empty())
                .doOnComplete(() -> System.out.printf("done: %d\n", list.size()))
                .flatMap(strings -> Flux.fromArray(strings.split("\n")))
                .collectList()


问:
How to use nested docker.image('test_image').inside() in a Jenkins pipeline
I have a jenkins container which triggers a maven container to build a java code.
Now I want to test the same code with selenium.
I have another container for selenium server.
But the command to run the test using selenium is a mvn command which needs Maven.
Since I am executing this inside the selenium container, mvn is not recognized.
How can I use maven container inside the selenium container ? Is nesting possible ?
I don't want to install everything in the same container.
This is the Jenkinsfile :

```<code>    node {
     stage('checkout') {
                git credentialsId: 'Gitlab_cred', url: 'urlhere'
         }

         stage('Build') {
                    docker.image('mvn_custom_image').inside('-u root'){
                      //mvn commands to build the project
                    }
          }

         stage('Archive and Packaging') {
            archiveArtifacts '**/*.war'
          }

         stage('Integration Test') {
            docker.image('selenium/node-firefox:3.4.0-dysprosium').inside{
                 //I want to run mvn command using selenium here
                // This image doesn't have mvn

            }
        }
     }
</code>```

Can I use "docker.image('mvn_custom_image').inside" inside another container (in my case selenium) ?

Or any other way which has a similar result.

答:
There is good example on https://www.jenkins.io/doc/book/pipeline/docker/</p>
```<code>node {
    checkout scm
    docker.image('mysql:5').withRun('-e "MYSQL_ROOT_PASSWORD=my-secret-pw"') { c ->
        docker.image('mysql:5').inside("--link ${c.id}:db") {
            /* Wait until mysql service is up */
            sh 'while ! mysqladmin ping -hdb --silent; do sleep 1; done'
        }
        docker.image('centos:7').inside("--link ${c.id}:db") {
            /*
             * Run some tests which require MySQL, and assume that it is
             * available on the host name `db`
             */
            sh 'make check'
        }
    }
}
</code>```

Body:
I have a jenkins container which triggers a maven container to build a java code.
Now I want to test the same code with selenium.
I have another container for selenium server.
But the command to run the test using selenium is a mvn command which needs Maven.
Since I am executing this inside the selenium container, mvn is not recognized.
How can I use maven container inside the selenium container ? Is nesting possible ?
I don't want to install everything in the same container.
This is the Jenkinsfile :

    node {
     stage('checkout') {
                git credentialsId: 'Gitlab_cred', url: 'urlhere'
         }

         stage('Build') {
                    docker.image('mvn_custom_image').inside('-u root'){
                      //mvn commands to build the project
                    }
          }

         stage('Archive and Packaging') {
            archiveArtifacts '**/*.war'
          }

         stage('Integration Test') {
            docker.image('selenium/node-firefox:3.4.0-dysprosium').inside{
                 //I want to run mvn command using selenium here
                // This image doesn't have mvn

            }
        }
     }

Can I use "docker.image('mvn_custom_image').inside" inside another container (in my case selenium) ?

Or any other way which has a similar result.

Body:
There is good example on https://www.jenkins.io/doc/book/pipeline/docker/

node {
    checkout scm
    docker.image('mysql:5').withRun('-e "MYSQL_ROOT_PASSWORD=my-secret-pw"') { c ->
        docker.image('mysql:5').inside("--link ${c.id}:db") {
            /* Wait until mysql service is up */
            sh 'while ! mysqladmin ping -hdb --silent; do sleep 1; done'
        }
        docker.image('centos:7').inside("--link ${c.id}:db") {
            /*
             * Run some tests which require MySQL, and assume that it is
             * available on the host name `db`
             */
            sh 'make check'
        }
    }
}


问:
Patch request in flutter/dart
I am trying to make a patch request in flutter and in the body I write my values as:

```<code>body: {
"var" : [v]
}
</code>```

But I keep getting this error:

```<code>Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json".
</code>```

答:
You need to convert your data to JSON using json.encode:

```<code>import 'dart:convert';

body: json.encode({"var" : [v]});
</code>```

Title: Patch request in flutter/dart

Body:
I am trying to make a patch request in flutter and in the body I write my values as:

body: {
"var" : [v]
}

But I keep getting this error:

Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json".

Body:
You need to convert your data to JSON using json.encode:

import 'dart:convert';

body: json.encode({"var" : [v]});